<?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 Henrique Fernandes on Medium]]></title>
        <description><![CDATA[Stories by Henrique Fernandes on Medium]]></description>
        <link>https://medium.com/@henriqemoises?source=rss-6d074a6d395d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mzy5wudIBjjnVQ4x3Wm13w.jpeg</url>
            <title>Stories by Henrique Fernandes on Medium</title>
            <link>https://medium.com/@henriqemoises?source=rss-6d074a6d395d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:20:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@henriqemoises/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[Semi-Automatic Package Update Management in Azure DevOps]]></title>
            <link>https://medium.com/villa-plus-engineering/semi-automatic-package-update-management-in-azure-devops-ae21092505b6?source=rss-6d074a6d395d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae21092505b6</guid>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[dependabot]]></category>
            <category><![CDATA[updates]]></category>
            <category><![CDATA[management]]></category>
            <dc:creator><![CDATA[Henrique Fernandes]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 05:51:01 GMT</pubDate>
            <atom:updated>2025-06-09T05:51:01.302Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Written by </em><a href="https://medium.com/u/6d074a6d395d"><em>Henrique Fernandes</em></a><em> and </em><a href="https://medium.com/u/da389511bf03"><em>Jakub Gaborski</em></a></p><p>One very important part of software development is keeping projects up-to-date. This - generally speaking - has benefits related to efficiency and security. But how to manage the process of upgrading dependencies when there are new package versions being released on a daily basis?</p><p>In this article we introduce a CI/CD strategy to manage package upgrades in Azure DevOps, so that they can be managed on a daily basis and with low effort. It consists of a semi-automatic process that raises Pull Requests (PR) and generates Work Items (WI), which can easily be assigned to team members for review, testing and be put live.</p><h3>Automatic PR creation with Dependabot</h3><p>The first step to make this process work is to set up a mechanism that automatically raises PRs with package upgrades. To achieve this we have configured <a href="https://github.com/dependabot">Dependabot</a> - a powerful tool that automates the process of updating dependencies, alongside its <a href="https://marketplace.visualstudio.com/items?itemName=tingle-software.dependabot">Azure DevOps extension</a>. It works by scanning your repository for outdated dependencies and creating PRs to bump them to the latest version. It is highly configurable.</p><p>We decided to set it up in our repositories to run every Sunday at midnight, and to exclude patch version increments. The reason why we exclude patches is because the team doesn’t have capacity to handle the number of patches being released for the number of projects that we own. Depending on the amount and size of your projects, you may consider configuring Dependabot to scan for all types of updates, including patches.</p><p>We also added our internal nuget package sources to the configuration so Dependabot is aware of updates for those packages too. Here’s what our Dependabot configuration looks like:</p><pre>version: 2<br><br>registries: <br>    villaplus-ci:<br>      type: nuget-feed<br>      url: https://villaplusltd.pkgs.visualstudio.com/_packaging/VillaPlus-CI/nuget/v3/index.json<br>      token: PAT:${{ DEPENDABOT_PAT }}<br>    villaplus:<br>      type: nuget-feed<br>      url: https://villaplusltd.pkgs.visualstudio.com/_packaging/VillaPlus/nuget/v3/index.json<br>      token: PAT:${{ DEPENDABOT_PAT }}<br><br>updates:<br>  - package-ecosystem: &quot;nuget&quot;<br>    directory: &quot;/&quot;<br>    registries:<br>      - villaplus-ci<br>      - villaplus<br>    target-branch: &quot;main&quot;<br>    ignore:<br>      - dependency-name: &quot;*&quot;<br>        update-types: [&quot;version-update:semver-patch&quot;]</pre><p>And the Azure DevOps pipeline that runs Dependabot:</p><pre>trigger: none # Disable CI trigger<br><br>schedules:<br>- cron: &#39;0 12 * * 0&#39; # weekly on sunday at midnight UTC<br>  always: true # run even when there are no code changes<br>  branches:<br>    include:<br>      - main<br>  displayName: Every Sunday<br><br>pool:<br>  vmImage: &#39;ubuntu-latest&#39; # requires macos or ubuntu (windows is not supported)<br><br>variables:<br>- group: dependabot<br><br>steps:<br>- task: dependabot@2<br>  inputs:<br>    azureDevOpsAccessToken: $(DEPENDABOT_PAT)<br><br>- task: PowerShell@2<br>  inputs:<br>    filePath: &#39;.azuredevops/dependencies-wi-creation.ps1&#39;<br>    arguments:<br>     -token $(DEPENDABOT_PAT)<br>     -project $(PROJECT)<br>     -repo $(REPO)</pre><p>This configuration ensures that, if there are any major or minor updates to be made, a PR will be assembled containing the package update changes. Please note that Dependabot will only create up to 5 PRs per repository by default, as this is the advised maximum value according to its documentation.</p><p>There are other tools that automate the automatic PR creation. The main outcome of the first step in the context of the whole process should be the creation of PRs that can later be converted into WI in a team board.</p><h3>Automatic WI creation in Azure DevOps</h3><p>Now that the PRs have been created, it’s time to “convert” them into Work Items in a team board, to make them easily manageable. This is the second step in the process. In case you haven’t noticed, in the pipeline definition script, there is a step that executes a Powershell script:</p><pre>- task: PowerShell@2<br>  inputs:<br>    filePath: &#39;.azuredevops/dependencies-wi-creation.ps1&#39;<br>    arguments:<br>     -token $(DEPENDABOT_PAT)<br>     -project $(PROJECT)<br>     -repo $(REPO)</pre><p>This script that we have created will scan a specific repository for open PRs generated by Dependabot and create WIs in the team board, if those do not exist there already. It will ignore abandoned PRs to allow development teams to have a way of skipping troublesome or unwanted updates.</p><p>The script can be further improved and we are constantly updating it. For example, we currently rely on the PR’s title to distinguish the PRs generated by Dependabot from all the other ones. This can be changed to a more elegant solution looking, e.g. the PR’s creator. Here’s the script:</p><pre>param ($token, $project, $repo, $org)<br><br>$boardsProject = &quot;Team Boards&quot;<br><br>$headers = @{<br>    &quot;Authorization&quot; = &quot;Bearer $token&quot;<br>    &quot;Content-Type&quot;  = &quot;application/json&quot;<br>}<br><br>$activePrs = Invoke-RestMethod -Uri &quot;https://dev.azure.com/$($org)/$($project)/_apis/git/repositories/$($repo)/pullrequests?searchCriteria.status=active&amp;api-version=6.0&quot; -Headers $headers -Method Get<br>$abandonedPrs = Invoke-RestMethod -Uri &quot;https://dev.azure.com/$($org)/$($project)/_apis/git/repositories/$($repo)/pullrequests?searchCriteria.status=abandoned&amp;api-version=6.0&quot; -Headers $headers -Method Get<br>$abandonedTitles = @{}<br><br>foreach ($abandonedPr in $abandonedPrs.value.Where({$_.title.StartsWith(&quot;Bump&quot;)})) {<br>    $abandonedTitles[$abandonedPr.title] = $true<br>}<br><br>foreach ($activePr in $activePrs.value.Where({$_.title.StartsWith(&quot;Bump&quot;)})) {<br><br>    $activePrTitle = $activePr.title.Replace(&#39;Bump&#39;,&#39;&#39;)<br><br>    if ($abandonedTitles.ContainsKey($activePr.title)) {<br>        Write-Host &quot;Abandoning active PR #$($activePr.pullRequestId) with title &#39;$($activePr.title)&#39; because a matching abandoned PR exists...&quot;<br>        $body = @{ status = &quot;abandoned&quot; } | ConvertTo-Json -Compress<br>        Invoke-RestMethod -Uri &quot;https://dev.azure.com/$org/$project/_apis/git/repositories/$repo/pullrequests/$($activePr.pullRequestId)?api-version=6.0&quot; -Headers $headers -Method Patch -Body $body<br>    }<br>    else {<br><br>        $wiqlBody = @{<br>            query = &quot;<br>        SELECT [System.Id], [System.Title] <br>        FROM WorkItems <br>        WHERE <br>            [System.WorkItemType] = &#39;Dependency&#39; <br>            AND [System.Title] = &#39;$($activePrTitle)&#39;<br>            AND [Custom.Project] = &#39;$($repo)&#39;<br>        &quot;<br>        } | ConvertTo-Json -Depth 10<br><br>        $searchResponse = Invoke-RestMethod -Uri &quot;https://dev.azure.com/$org/$boardProject/_apis/wit/wiql?api-version=6.0&quot; `<br>            -Headers $headers `<br>            -Method Post `<br>            -Body $wiqlBody<br><br>        if ($searchResponse.workItems.Count -gt 0) {<br>            Write-Host &quot;Dependency with title &#39;$activePrTitle&#39; already exists. Skipping creation.&quot;<br>        }<br>        else {<br>            Write-Host &quot;No existing dependency with title &#39;$activePrTitle&#39;. Creating new dependency...&quot;<br><br>            $match = $activePrTitle -match &#39;[\w\.]+ from (?&lt;currentVersion&gt;[\d\.]+) to (?&lt;newerVersion&gt;[\d\.]+)&#39;<br><br>            $prUrl = &quot;https://dev.azure.com/$org/$project/_git/$repo/pullrequest/$($activePr.pullRequestId)&quot; <br>            $workItemBody = @(<br>                @{ &quot;op&quot; = &quot;add&quot;; &quot;path&quot; = &quot;/fields/System.Title&quot;; &quot;value&quot; = &quot;$($activePrTitle)&quot; },<br>                @{ &quot;op&quot; = &quot;add&quot;; &quot;path&quot; = &quot;/fields/System.Description&quot;; &quot;value&quot; = &quot;&lt;a href=&#39;$prUrl&#39;&gt;$prUrl&lt;/a&gt;&quot; },<br>                @{ &quot;op&quot; = &quot;add&quot;; &quot;path&quot; = &quot;/fields/System.WorkItemType&quot;; &quot;value&quot; = &quot;Dependency&quot; },<br>                @{ &quot;op&quot; = &quot;add&quot;; &quot;path&quot; = &quot;/fields/System.IterationPath&quot;; &quot;value&quot; = &quot;$($boardsProject)&quot; },<br>                @{ &quot;op&quot; = &quot;add&quot;; &quot;path&quot; = &quot;/fields/System.AreaPath&quot;; &quot;value&quot; = &quot;$($boardsProject)&quot; },<br>                @{ &quot;op&quot; = &quot;add&quot;; &quot;path&quot; = &quot;/fields/Custom.CurrentVersion&quot;; &quot;value&quot; = &quot;$($Matches.currentVersion)&quot; },<br>                @{ &quot;op&quot; = &quot;add&quot;; &quot;path&quot; = &quot;/fields/Custom.MostRecentVersion&quot;; &quot;value&quot; = &quot;$($Matches.newerVersion)&quot; },<br>                @{ &quot;op&quot; = &quot;add&quot;; &quot;path&quot; = &quot;/fields/Custom.Project&quot;; &quot;value&quot; = &quot;$($repo)&quot; }<br><br>            ) | ConvertTo-Json -Depth 3<br>    <br>            $response = Invoke-RestMethod -Uri &quot;https://dev.azure.com/$org/$boardsProject/_apis/wit/workitems/`$Dependency?api-version=6.0&quot; -Headers $headers -Method Post -Body $workItemBody -ContentType &quot;application/json-patch+json&quot;<br>            Write-Host &quot;Dependency created with ID: $($response.id) for active PR #$($activePr.pullRequestId)&quot;<br><br>            Write-Host &quot;Moving WI $($response.id) to &#39;Queue&#39; column&quot;<br>            $workItem = Invoke-RestMethod -Uri &quot;https://dev.azure.com/$org/$boardsProject/_apis/wit/workitems?ids=$($response.id)&amp;api-version=7.1&quot; -Headers $headers -Method Get -ContentType &#39;application/json&#39;<br>            <br>            # Get column fields to move WI from the Backlog column to Technical Backlog<br>            $boardColumnFields = $workItem.value[0].fields.PSObject.Properties.Name.Where({$_.Contains(&quot;Kanban&quot;)});<br>            $columnFieldsArray = [System.Collections.ArrayList]@()<br>            foreach ($columnField in $boardColumnFields.Where({!$_.Contains(&quot;Done&quot;)})){<br>                $columnFieldsArray.Add(@{ &quot;op&quot; = &quot;replace&quot;; &quot;path&quot; = &quot;/fields/$columnField&quot;; &quot;value&quot; = &quot;Technical Backlog&quot; })<br>            }<br>            $workItemBody = $columnFieldsArray | ConvertTo-Json -Depth 3;<br>            $response = Invoke-RestMethod -Uri &quot;https://dev.azure.com/$org/$boardsProject/_apis/wit/workitems/$($response.id)?bypassRules=true&amp;api-version=7.1&quot; -Headers $headers -Method Patch -Body $workItemBody -ContentType &quot;application/json-patch+json&quot;<br><br>            Write-Host &quot;Moved WI $($response.id) to &#39;Technical Backlog&#39; column&quot;<br>        }<br>    }<br>}</pre><p>In our team board setup we have created a custom Work Item type called “Dependency”, that has some fields such as “Current Version”, “Newer Version” and “Project”. Dependabot will create items of this type and fill in the required data. In the last section of the script, it will move newly created Dependency items to the appropriate column. In our case this column is called “Technical Backlog”. Our Dependency WI has its own swimlane called “Packages &amp; Dependencies”, that helps us better organise the team board. Newly create Dependencies will show up here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cezS3OZP-5xDHGCsuSl_2A.png" /><figcaption>Dependency management in Azure DevOps</figcaption></figure><h3>Dependency management</h3><p>The third and last step in the process is to actually assign the Dependency items to team members for them to take ownership of the remaining tasks. These can be picked up just like any other task. This stage is the manual part of the process, which has mostly to do with quality assurance. The assigned team member is responsible for reviewing the PR, ensure that the project and Unit Tests are still working as expected, make some smoke testing, complete the PR, release the changes to a staging environment and monitor the updated project. If no issues are found, the changes can be then pushed to a production environment and monitored, thus concluding the upgrade process life-cycle.</p><h3><strong>Bonus tip</strong></h3><p>If working with Visual Studio, there’s an option that can help cleaning up unused dependencies. If you right-click a project on the Solution Explorer tab, there’s a “Remove Unused References…” that removes them. Please take this option with a grain of salt because it is not 100% accurate and may remove used references. Always test your changes afterwards. This clean-up not only helps keeping your code maintainable and improve performance, but it will also decrease Dependabot’s execution time.</p><h3>Conclusion</h3><p>The presented strategy eliminates the laborious task of manually updating packages, making it easier to handle dependency upgrades by dividing them into bite-sized parts that can be tackled separately. Using a CI/CD approach, it ensures updated projects over time instead of the occasional (and very large) update task that may break things. It also reduces the risk of package version conflicts and the nightmare of fixing them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae21092505b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/villa-plus-engineering/semi-automatic-package-update-management-in-azure-devops-ae21092505b6">Semi-Automatic Package Update Management in Azure DevOps</a> was originally published in <a href="https://medium.com/villa-plus-engineering">Villa Plus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick tutorial — Setting up a custom event on new Google Tag Manager and Google Analytics instances]]></title>
            <link>https://medium.com/villa-plus-engineering/quick-tutorial-setting-up-a-custom-event-on-new-google-tag-manager-and-google-analytics-instances-8606e1a76000?source=rss-6d074a6d395d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8606e1a76000</guid>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[google-tag-manager]]></category>
            <dc:creator><![CDATA[Henrique Fernandes]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 04:58:56 GMT</pubDate>
            <atom:updated>2025-02-12T04:58:56.415Z</atom:updated>
            <content:encoded><![CDATA[<h3>Quick tutorial — Setting up a custom event on new Google Tag Manager and Google Analytics instances</h3><h3>Introduction</h3><p>In order to understand how users are interacting with our applications, we are often asked to set up some sort of usage metrics. This can be anything from page views to button clicks, ecommerce data tracking to product engagement, interactions in pages, etc…</p><p>Luckily, Google offers very powerful tools that are easy to set up and come with plenty of out-of-the-box features for usage analysis. In Villa Plus we use both Google Tag Manager (GTM) and Google Analytics (GA) to collect relevant data and build reports, which are then analysed to make crucial business decisions.</p><p>In this blog post I will briefly describe the steps one needs to take to set up a custom event on GTM and GA from scratch. This should give you a basic platform to work with GTM and GA, that is ready to be expanded on.</p><h3>The example</h3><p>On this tutorial we will create a custom event that should be triggered whenever a “copy-to-clipboard” button is clicked. This button’s purpose is to copy text content unto the clipboard. The event will be called “<em>response_copied</em>” and will track the name of the interacting user on an event variable called “<em>user</em>”. The button click handling and the user name retrieval are omitted for simplicity.</p><h3>The tutorial</h3><h4>1. Creating Google Tag Manager and Google Analytics instances</h4><p>The first step in the process of setting up Google Tag Manager and Google Analytics is to create both instances. There should be one of each for each environment. They will have unique identifiers that will be required further in the configuration process.</p><p>Google Tag Manager <strong>container identifier</strong> starts with “<em>GTM-</em>” and is displayed on the top right corner of the “<em>Overview</em>” page. Google Analytics unique identifier is called <strong>Measurement ID</strong> and starts with “<em>G-</em>”. It is located in the “<em>Admin” </em>section, under “<em>Data collection and modifications” &gt; “Data Streams”.</em></p><h4>2. Setting up integration code</h4><p>The next step is to add some scripts to the project that will push the custom events. Clicking on the GTM identifier on the “<em>Overview” </em>page will display a popup with some instructions. The GTM identifier will be included in the script themselves, so be sure to implement some code logic that will consider the environment to set this value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nts3Tz_nTEVWLm9pw89blQ.png" /></figure><p>Then, new events can be pushed from the code into the “<em>dataLayer</em>” window javascript object. This will trigger them to be sent to your specified GTM container. Here’s a code snippet on how to do it in typescript. The “<em>dataLayer</em>” variable refers to the javascript object that was set on the script that was added previously.</p><pre>export class GoogleAnalyticsHelper {<br><br>  constructor(public window: any) { }<br><br>  trackPageLoad(userName: string) {<br>    this.window.gtag(&#39;event&#39;, &#39;page_load&#39;, {<br>      &#39;user&#39;: userName,<br>    });<br>  }<br><br>  trackCTACopyResponse(userName: string) {<br>    this.window.gtag(&#39;event&#39;, &#39;response_copied&#39;, {<br>      &#39;user&#39;: userName,<br>    });<br>  }<br>}</pre><h4>3. Setup a config tag</h4><p>Now onto GTM. The first thing that needs to be configured here is a Google Tag config tag. This tag will be the connector between GTM and GA, and is required to avoid warnings when creating a custom tag (e.g. Google Tag not found on this container warning). We can achieve this by setting this tag’s <strong>Tag ID</strong> as the GA’s <strong>Measurement ID</strong>. Here’s an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bo2ID1YeGP1LWAAqffV94Q.png" /></figure><h4>4. Creating the custom tag</h4><p>To register the new custom event that we added to our code, we now need to have its representation on GTM. There are 3 things that we need to create — trigger, variables and the tag itself.</p><h4>4.1. Trigger</h4><p>The trigger should be configured to be activated whenever there’s a custom event fired with a certain name. <strong>This name needs to match the name configured in the code.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0iTrar-tMtrxY3frMhtYig.png" /></figure><h4>4.2. Variables</h4><p>To define the variables, we can specify one of GTM’s defaults or create one of our own. In this example we have created a data layer variable, so that’s what we are going to use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TKT8FUj_zRrWMspjPRPb6w.png" /></figure><h4>4.3. Tag</h4><p>Now that we have the trigger and variables, we can create the tag itself. We want to create a “<em>Google Analytics: GA4 Event</em>” tag, and reference our trigger and data layer variable so that it is activated correctly and the variable is propagated to GA. <strong>The value for the variable needs to be set inside curly brackets and exactly match the name of the previously created variable</strong> (e.g. {{dlv — user}}).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TstiXhB_PzesFOX60e0IXA.png" /></figure><h4>5. Debugging GTM</h4><p>Now that the custom tag was created, it should start showing up on GTM’s “<em>Overview and real time data</em>” section. There is a “<em>Preview</em>” functionality that allows you to connect to a specific endpoint and listen to the events being raised there. If things are configured properly, the event name and data layer variable should be in the “<em>Variables</em>” tab when the custom event is selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_Y0WWKoSYHC2xj6lIFoFA.png" /></figure><h4>6. Checking connection on GA</h4><p>Assuming all was configured properly, the data should start being published into GA, inside the “<em>Realtime Overview</em>” section. <strong>Keep in mind that it might take a few hours for everything to finish connecting if these instances were recently created</strong>. If the connection is working, a message should state that, in the section where the Measurement ID was retrieved from — <em>Web stream details</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_B9gF4MC0JtsNznbxnvtLA.png" /></figure><p>Initially, only the “<em>Realtime Overview</em>” section will contain up-to-date data regarding the event, as all the other sections will collect data over time and aggregate it by different criteria. It may take some hours (or up to a day) for data to start showing up in the reports. As long as it shows up in the “<em>Realtime Overview</em>” section everything should have been setup properly.</p><h3>Conclusion</h3><p>And that’s it! In this tutorial we explored the steps required to set up new instances of Google Tag Manager, Google Analytics and a custom event that shows up on both tools. There are some readily available events that don’t require this level of configuration, and GTM may not even be required for some scenarios, but the configuration done here should cover scenarios where the out-of-the-box events may be lacking. Hope this helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8606e1a76000" width="1" height="1" alt=""><hr><p><a href="https://medium.com/villa-plus-engineering/quick-tutorial-setting-up-a-custom-event-on-new-google-tag-manager-and-google-analytics-instances-8606e1a76000">Quick tutorial — Setting up a custom event on new Google Tag Manager and Google Analytics instances</a> was originally published in <a href="https://medium.com/villa-plus-engineering">Villa Plus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preventing timeouts in Azure Functions running on a Consumption Plan in Azure]]></title>
            <link>https://medium.com/villa-plus-engineering/preventing-timeouts-in-azure-functions-running-on-a-consumption-plan-in-azure-122dd7ca7d53?source=rss-6d074a6d395d------2</link>
            <guid isPermaLink="false">https://medium.com/p/122dd7ca7d53</guid>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Henrique Fernandes]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 05:03:42 GMT</pubDate>
            <atom:updated>2024-08-20T05:03:42.449Z</atom:updated>
            <content:encoded><![CDATA[<p>Azure Functions are a great way to automatically execute systematic processes, based on a specified trigger. If their execution is occasional but computationally demanding, you might also want to set them up on a Consumption plan, as you will only pay for the time they are running, and they will scale automatically during periods of high load.</p><p>They work just fine for simple tasks or short flows. However, if you have a process that deals with large amounts of data, contains some complex actions or external dependencies, the volume of processing data grows over time, etc… you might run into timeouts since the execution time of Azure Functions on a Consumption plan is limited to 5 minutes by default.</p><p>In this post I will share some tips and ways to work around these timeouts, which are based on personal experience working with this type of setup. The steps/actions on this post will be sorted by their ascending complexity but this is subjective as each case is unique. These solutions also assume that you do not want to change to something like Azure Durable Function, which would nullify this problem altogether.</p><h4><strong>Double it</strong></h4><p>This is the naïve approach but honestly the first one that you should try. It appears on the top search results when you search online for “Azure Function timeout” and similar queries. By default, the maximum duration of an Azure Function running on a Consumption plan is set to 5 minutes. You can, however, extend it to a maximum of 10 minutes by setting the following configuration on your host.json file:</p><pre>&quot;functionTimeout&quot;: &quot;00:10:00&quot;</pre><p>Did that work for you? Great! But what if it did not? What if you are too close to that 10-minute limit? What if the execution time varies so much that it just might reach that 10-minute mark? What if the volume of data that you need to process keeps growing over time? <br> Don’t worry, I got you covered in the next steps.</p><h4><strong>Use parallel processing</strong></h4><p>This might not be applicable for all cases but if you are currently doing a sequential processing of independent items and/or getting data from different sources, you might want to implement some parallel instructions to leverage the benefit of their simultaneous processing. There are different ways to do that in .NET. Using the Parallel library and changing foreach cycles to Parallel.ForEach, for example. Or use ActionBlock s and wait for the termination of all tasks. You can also set the MaxDegreeOfParallelism to the maximum number of available processors on the environment. Here’s a snippet of what it might look like for the ActionBlock case:</p><pre>ActionBlock&lt;ItemToProcess&gt; processingActionBlock = ProcessItem();<br><br>foreach (var itemToBeProcessed in itemsToBeProcessed)<br>{<br>    processingActionBlock.Post(itemToBeProcessed);<br>}<br><br>processingActionBlock.Complete();<br>processingActionBlock.Completion.Wait();<br><br>…<br><br>private ActionBlock&lt;ItemToProcess&gt; ProcessItem()<br>{<br>    return new ActionBlock&lt;ItemToProcess&gt;(<br>       async itemToBeProcessed =&gt;<br>       {<br>          // Process the item              <br> },<br>       new ExecutionDataflowBlockOptions<br>       {<br>        MaxDegreeOfParallelism = Environment.ProcessorCount<br>       }<br>    );<br>}</pre><p>By using parallel processing set to use the maximum degree of parallelism available in your environment you should greatly reduce the overall duration of your process. Some examples are if the execution requires processing a large set of items, needs to get data from multiple sources, etc. If those are not your cases or if even with parallel processing you are not free from the occasional timeout, follow along.</p><h4><strong>It’s optimisation time</strong></h4><p>The next step would be to optimise your code and flow execution. There are plenty ways to do that, but you should, in the first place, have a clear understanding of the flow, rules and requirements of the logic being executed by your Azure Function. With that knowledge, you can analyse your code and see if there are any optimisations that you can do. I will list some of the most common ones that I have come across:</p><ul><li><strong>Not filtering item processing</strong> — If for some reason the item that is being processed does not need to be processed anymore (e.g., because of a business rule) you want to stop the processing of that item immediately and do not let it continue, which will take time and resources. Check how soon you can put these validations in place.</li><li><strong>Making potentially unnecessary processing/calls</strong> — To put it simply, don’t do any processing until it is necessary. An example of this would be to make an external API call whose result you might not need if, later in the flow, it is not going to be used due to some business logic. Or if the item will end up being filtered and does not need to be processed further. Same goes for complex operations. Move them closer to where you need their result and, if possible, make them async for some precious extra ms.</li><li><strong>Processing flow not optimised</strong> — The order of the different actions on your processing flow can have an impact on its total duration. Keeping in mind the two previous points, check if a reordering of the different actions can make the function execution last less time.</li><li><strong>Code not optimised</strong> — This one is self-explanatory. Make sure that there are no inefficiencies in the code that the function is running. Some of these inefficiencies are well documented and there are plenty of online articles about this topic such as <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/best-practices?view=aspnetcore-8.0">this one from Microsoft to .NET Core 8</a>, so I will not get into many details. If you have Application Insights configured on your AF, use it to understand which parts of your function are taking the longest.</li><li><strong>Overlooked Azure Functions specific optimisations</strong> — Apart from general code optimisations, there are also some <a href="https://learn.microsoft.com/en-us/azure/azure-functions/performance-reliability">specific optimisations</a> that are suggested by Microsoft when using AFs, to improve their reliability and performance. These optimisations mostly contain structure-specific tweaks and high-level advice but making sure they are covered can also decrease the function execution time.</li></ul><h4><strong>Divide to conquer</strong></h4><p>So, you’ve thoroughly optimised your code and it is running in the most efficient way possible…but you still get timeouts here and there. What know? Well, if everything up to this point did not solve the problem, you might need to consider more drastic approaches. <br>The first that I want to highlight is to try to split the data that needs processing into groupings that can be processed by different AF executions on different triggers and/or parameters. Suppose that you must process emails to customers that made a purchase 1, 3 and 5 days ago. You could split the Azure Function that processes all those emails into 3 different triggers, each one with a different set of parameters that will process each of the batches in a separate AF instance. Do they share some data required for processing? Even better! By default, MemoryCache is shared between executions of the same Azure Function, so also use that to your advantage. No need to retrieve the data all over again if you already did it once. Just remember to set the cache duration correctly.</p><h4><strong>If all else fails</strong></h4><p>If none of the above solved the issue, this is the last resort solution. You might need to change your solution architecture. If the volume of data is just too large or if there is no possible segregation of processing items, then the current solution might not be the best one. My suggestion would be to try to separate the main processing into several parts that can be done sequentially by individual Azure Functions or adopt an event-based approach where one Function periodically queues individual items to be processed and then a second Function process each item individually or in batches, through and event bus trigger, for example.</p><h4><strong>Bonus tips</strong></h4><p>Here are 2 different tips that have also been extremely useful when dealing with the inevitable Azure Function timeouts. While they will not solve the problem, they will help you react to it in a timely manner:</p><ul><li><strong>Add alerts to be notified whenever a function times out </strong>— If you have Application Insights configured in your Azure Function, you can add an alert that will periodically monitor if there was a failure in that specific AF. Timeouts do count as failures, so the alert will be triggered, and you will know that the function execution failed. Check the “Failed Operations” alert signal and use it as is for any failure in the Azure Function or modify the query to react to Timeout failures only by filtering the failed requests by their duration.</li><li><strong>Have a way to deal with occasional failures </strong>— If your solution allows, set up a way to process the items that never got a change to be processed. This can come as an HTTP trigger on the same Azure Function that you’re using, for example, or any other solution that you see fit. A retry mechanism in your Azure Function is also an option, assuming you have a way of filtering what was already processed to avoid processing it again. Just make sure that you have a way of identifying what was already processed and what is still pending.</li></ul><h4><strong>Conclusion</strong></h4><p>These are some tips that will help you build more resilient and efficient Azure Functions and, hopefully, get rid of timeouts. Some or even all of them might not be applicable in all cases, but they have served me well in the past. There are other alternatives to this “Azure Functions in a Consumption plan” setup, even within the Azure ecosystem, but as it stands, this continues to be a very cost-effective way of automating processes. Therefore, the next time you are working on this configuration, keep in mind: “Every second counts” and “Time is money.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=122dd7ca7d53" width="1" height="1" alt=""><hr><p><a href="https://medium.com/villa-plus-engineering/preventing-timeouts-in-azure-functions-running-on-a-consumption-plan-in-azure-122dd7ca7d53">Preventing timeouts in Azure Functions running on a Consumption Plan in Azure</a> was originally published in <a href="https://medium.com/villa-plus-engineering">Villa Plus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rescheduling an Azure service bus message using the Azure service Bus client library for .NET]]></title>
            <link>https://medium.com/villa-plus-engineering/rescheduling-an-azure-service-bus-message-using-the-azure-service-bus-client-library-for-net-a80faae4d246?source=rss-6d074a6d395d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a80faae4d246</guid>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[azure-service-bus]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Henrique Fernandes]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 14:17:17 GMT</pubDate>
            <atom:updated>2024-03-04T14:33:00.990Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rescheduling an Azure service bus message using the Azure service bus client library for .NET</h3><p>The Azure Service Bus allows for the development of event-driven applications that take advantage of asynchronous messaging patterns using a highly-reliable service to broker messages between producers and consumers. It provides flexible, brokered messaging between client and server, along with structured FIFO messaging and publish/subscribe capabilities.</p><p>Microsoft’s Azure.Messaging.ServiceBus NuGet package is the .NET library that allows the integration of .NET projects with Azure Service Buses by providing classes, methods and properties that can be used — with a high degree of customisation — to interact with many elements of Azure’s service buses, such as queues, topics, subscriptions and messages, to name a few.</p><h4>The problem</h4><p>There may be some reasons why we would not want a service bus message to be processed immediately. For example, if a certain service or database connection is faulted, we may want to delay its processing, to avoid ineffectual retries and the potential placement of the message on the dead-letter queue. Or maybe we want all of the messages to be processed at the same time because of some business logic or other requirement.</p><p>In our particular case, we wanted messages of a certain type to be processed under a specified schedule, such that we could control the “active” hours when clients or operations team members might receive an email sent by an automatic function. There is — at the time of this article’s writing — no way to configure such behaviour in Azure portal, which means that we had to take the programmatical approach.</p><h4>Solution part 1 — It’s schedule time!</h4><p>In order to process the service bus messages, we set up an Azure function with a <em>ServiceBusTrigger </em>trigger listening to a specific subscription inside a topic. Then, when a message is received, one of the first things that we need to do is to check if we are inside the “active” schedule time: If the message is within the “active” time, then we execute the normal message processing. If, on the other hand, the message is being executed outside of the “active” schedule time, we want a different flow to be executed, I.e. one where the message gets rescheduled to the next available “active” time.</p><pre>if (_messageScheduler.IsDateTimeInScheduleTime())<br>{<br>  await _messageProcessingService.ProcessAsync(message);<br>}<br>else<br>{<br>  await _messageScheduler.RescheduleMessageAsync(message);<br>}</pre><p>The <em>IsDateTimeInScheduleTime </em>method checks the current date and time and compares it with a configured set of values (I.e. the “active” schedule). This is what the configuration would look like if the “active” schedule was on Tuesday only, from 9h to 18h:</p><pre>{<br>  // DayOfWeek codification<br>  // 0 - Sunday, 1 - Monday, 2 - Tuesday, 3 -Wednesday, 4 - Thursday, 5 - Friday, 6 - Saturday<br>  &quot;ScheduledConfigurations&quot;: [<br>    {<br>      &quot;DayOfWeek&quot;: 2,<br>      &quot;StartTime&quot;: 9,<br>      &quot;EndTime&quot;: 18<br>    }<br>  ]<br>}</pre><h4>Solution part 2 — Hitting the snooze button</h4><p>The second part of the solution consists of actually changing the scheduled enqueue time of the message and sending it again to the same queue or a totally different queue. In our architecture we decided to send it to a different queue but we could have used the same one. The <em>RescheduleMessageAsync </em>method looks something like this:</p><pre>public async Task ScheduleMessage(string originalMessage)<br>{<br>  await using var client = new ServiceBusClient(_serviceBusConfigurations.ServiceBusConnectionString);<br>  ServiceBusSender sender = client.CreateSender(_serviceBusConfigurations.QueueName);<br>  ServiceBusMessage rescheduledMessage = new ServiceBusMessage(originalMessage);<br>  rescheduledMessage.ScheduledEnqueueTime = SetRescheduledTime();<br>  rescheduledMessage.Subject = _serviceBusConfigurations.FilterSubjectName;<br>  await sender.SendMessageAsync(rescheduledMessage);<br>}</pre><p>After configuring the <em>ServiceBusClient </em>and <em>ServiceBusSender</em>, we create a new message that is a copy of the original one, assign it a <em>Subject </em>to be properly queued on another queue and assign it the desired new time of processing — <em>ScheduledEnqueueTime</em>. The <em>SetRescheduledTime </em>method uses the same configuration as described on part 1 to know when the next “active” schedule time is and returns a <em>DateTimeOffset </em>type.</p><h4><em>ScheduledEnqueueTime </em>important notes</h4><p>This property gets or sets the date and time in UTC at which the message will be enqueued. This property returns the time in UTC; when setting the property, the supplied <em>DateTime </em>value must also be in UTC. Message enqueuing time does not mean that the message will be sent at the same time. It will get enqueued, but the actual sending time depends on the queue’s workload and its state.</p><h4>Summary</h4><p>In this article we briefly went through the solution that we have developed to reschedule an Azure service bus message instead of processing it immediately. In our particular case it came as a business requirement but the same logic can be followed to handle processing errors. While the Azure portal provides a great way to thoroughly configure most service bus elements, custom behaviour may need to be implemented programmatically. And the Azure Service Bus client library for .NET allowed us to do just that (and stop time-sensitive emails from being sent outside of business hours).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a80faae4d246" width="1" height="1" alt=""><hr><p><a href="https://medium.com/villa-plus-engineering/rescheduling-an-azure-service-bus-message-using-the-azure-service-bus-client-library-for-net-a80faae4d246">Rescheduling an Azure service bus message using the Azure service Bus client library for .NET</a> was originally published in <a href="https://medium.com/villa-plus-engineering">Villa Plus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>