<?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"><channel><title><![CDATA[Dev-ish]]></title><description><![CDATA[Dev-ish is for people that don't write code all the time. I talk about the Power Platform, Azure, and also...code.]]></description><link>https://richardcarrigan.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 22:13:55 GMT</lastBuildDate><atom:link href="https://richardcarrigan.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Managing connections between Power Platform environments using Azure DevOps pipelines]]></title><description><![CDATA[For organizations that are using Application Lifecycle Management (ALM) to deploy and maintain their Power Platform solutions, connections can be…]]></description><link>https://richardcarrigan.hashnode.dev/managing-connections-between-power-platform-environments-using-azure-devops-pipelines</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/managing-connections-between-power-platform-environments-using-azure-devops-pipelines</guid><category><![CDATA[PowerPlatform]]></category><category><![CDATA[azure-devops]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Tue, 05 Mar 2024 18:00:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/l090uFWoPaI/upload/f357c2853ff5a1852a2ce4cb547a7620.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>For organizations that are using Application Lifecycle Management (ALM) to deploy and maintain their Power Platform solutions, connections can be especially tricky for many reasons, such as personnel turnover, different permissions in different environments, as well as many others. In this article, I hope to help you navigate these scenarios by providing you with a clear mental model for how connections work in an ALM solution. In this article, we'll cover:</p>
<ol>
<li><p>Relationship between connectors, connections, and connection references.</p>
</li>
<li><p>Special considerations for service accounts.</p>
</li>
<li><p>How to declare and maintain connections and connection references across multiple Power Platform environments.</p>
</li>
</ol>
<h2 id="heading-connectors-connections-and-connection-references">Connectors, connections, and connection references</h2>
<p>To understand how to manage connections across multiple Power Platform environments using ALM, it's necessary to first understand what <strong>connectors</strong>, <strong>connections</strong>, and <strong>connection references</strong> are, and how they are related.</p>
<ul>
<li><p>Connector: A built-in or custom component that surfaces some (or sometimes all) of a REST API's available endpoints, with information on what parameters can be provided, as well as what information will be returned. Example connectors include Dataverse, Office 365 Users, and SharePoint.</p>
</li>
<li><p>Connection: A set of credentials used to authenticate to a specific service. For example, if you create a Power Automate Flow and manually connect it to Dataverse, Power Platform stores information (such as an authentication token received from the API) so that you don't need to authenticate every time the Flow runs.</p>
</li>
<li><p>Connection reference: In Power Platform solutions (not applicable to Flows created outside of a solution), this component <em>references</em> a connection that exists within that environment. This is the key to managing connections in ALM, as it allows the <em>same</em> connection reference to point to a <em>different</em> connection in each environment. For example, you might have a connection reference called "Dataverse connection reference" that points to your personal connection in the Dev environment, but points to your service account's connection in the Test and Prod environments.</p>
</li>
</ul>
<h2 id="heading-service-account-considerations">Service account considerations</h2>
<p>In a perfect world, we would all find our perfect team and no one would ever leave. In the real world, however, personnel turnover happens. This causes serious issues when the person leaving the team is using their credentials to connect to the various services that are used by the team's Flows and Apps. But the team still needs to securely connect to those services, so what are we supposed to do? One solution for this is "service accounts", which are actually just user accounts created in Microsoft Entra ID that aren't associated with a specific person. The benefit to using a service account instead of a standard user account is that, aside from regular password changes and any conditional access policies (such as requiring on-prem access) that are specific to service accounts, there is no action required when the team changes.</p>
<p>That's great! So, we can just log in as the service account and connect each of our Flows and Apps to their respective connectors using this service account, right? Unfortunately, not. There's one other hidden step that must be completed in order for the connection references to use these connections - each connection created by a service account <strong>must</strong> be shared with the service principal (not to be confused with the service account) that is listed as the owner for the deployed Flows and Apps in that environment. We'll go over this in greater detail in the next section, but I felt it necessary to specifically call out this "gotcha" as it can lead to many difficult-to-debug issues.</p>
<h2 id="heading-declaring-and-maintaining-connections-across-multiple-environments">Declaring and maintaining connections across multiple environments</h2>
<p>For the purposes of this discussion, we'll start with an existing Azure DevOps Repo with the following folder structure:</p>
<pre><code class="lang-bash">DemoRepo/
-- DemoSolution/
-- azure-pipelines.yml
</code></pre>
<p>This repo deploys a Power Platform solution named <code>DemoSolution</code> using Azure DevOps Pipelines. The deployment steps are defined in the following <code>azure-pipelines.yml</code> file:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">trigger:</span>
<span class="hljs-bullet">-</span> <span class="hljs-string">main</span>

<span class="hljs-attr">pool:</span>
  <span class="hljs-attr">vmImage:</span> <span class="hljs-string">windows-latest</span>

<span class="hljs-attr">stages:</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">stage:</span> <span class="hljs-string">Deploy_To_Test</span>
  <span class="hljs-attr">jobs:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">deployment:</span> <span class="hljs-string">DeployToTest</span>
    <span class="hljs-attr">displayName:</span> <span class="hljs-string">'Build, check, and deploy PP solution to test environment'</span>
    <span class="hljs-attr">environment:</span> <span class="hljs-string">'test'</span>
    <span class="hljs-attr">strategy:</span>
      <span class="hljs-attr">runOnce:</span>
        <span class="hljs-attr">deploy:</span>
          <span class="hljs-attr">steps:</span>
          <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformToolInstaller@2</span>
            <span class="hljs-attr">displayName:</span> <span class="hljs-string">'Install PP tools required for later steps'</span>
            <span class="hljs-attr">inputs:</span>
              <span class="hljs-attr">DefaultVersion:</span> <span class="hljs-literal">true</span>
          <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformPackSolution@2</span>
            <span class="hljs-attr">displayName:</span> <span class="hljs-string">'Pack unpacked, managed solution'</span>
            <span class="hljs-attr">inputs:</span>
              <span class="hljs-attr">SolutionSourceFolder:</span> <span class="hljs-string">'$(System.DefaultWorkingDirectory)\DemoSolution'</span>
              <span class="hljs-attr">SolutionOutputFile:</span> <span class="hljs-string">'$(Build.ArtifactStagingDirectory)\DemoSolution.zip'</span>
              <span class="hljs-attr">SolutionType:</span> <span class="hljs-string">'Managed'</span>
          <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformChecker@2</span>
            <span class="hljs-attr">displayName:</span> <span class="hljs-string">'Check PP solution for issues'</span>
            <span class="hljs-attr">inputs:</span>
              <span class="hljs-attr">authenticationType:</span> <span class="hljs-string">'PowerPlatformSPN'</span>
              <span class="hljs-attr">PowerPlatformSPN:</span> <span class="hljs-string">'Test Environment Service Connection Name'</span>
              <span class="hljs-attr">FilesToAnalyze:</span> <span class="hljs-string">'$(Build.ArtifactStagingDirectory)\DemoSolution.zip'</span>
              <span class="hljs-attr">RuleSet:</span> <span class="hljs-string">'0ad12346-e108-40b8-a956-9a8f95ea18c9'</span> <span class="hljs-comment"># Default ruleset</span>
          <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformImportSolution@2</span>
            <span class="hljs-attr">displayName:</span> <span class="hljs-string">'Import PP solution into target environment'</span>
            <span class="hljs-attr">inputs:</span>
              <span class="hljs-attr">authenticationType:</span> <span class="hljs-string">'PowerPlatformSPN'</span>
              <span class="hljs-attr">PowerPlatformSPN:</span> <span class="hljs-string">'Test Environment Service Connection Name'</span>
              <span class="hljs-attr">SolutionInputFile:</span> <span class="hljs-string">'$(Build.ArtifactStagingDirectory)\DemoSolution.zip'</span>
              <span class="hljs-attr">AsyncOperation:</span> <span class="hljs-literal">true</span>
              <span class="hljs-attr">MaxAsyncWaitTime:</span> <span class="hljs-string">'60'</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">stage:</span> <span class="hljs-string">Deploy_To_Prod</span>
  <span class="hljs-attr">jobs:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">deployment:</span> <span class="hljs-string">DeployToProd</span>
    <span class="hljs-attr">displayName:</span> <span class="hljs-string">'Build, check, and deploy PP solution to prod environment'</span>
    <span class="hljs-attr">environment:</span> <span class="hljs-string">'prod'</span>
    <span class="hljs-attr">strategy:</span>
      <span class="hljs-attr">runOnce:</span>
        <span class="hljs-attr">deploy:</span>
          <span class="hljs-attr">steps:</span>
          <span class="hljs-comment"># Repeat test environment steps using Prod environment service connection</span>
</code></pre>
<p>With the <code>azure-pipelines.yml</code> file defined above, we're successfully deploying the <code>DemoSolution</code> into our "Test" and "Prod" environments. Let's look at our <code>DemoSolution</code> components to get an idea of what exactly we're deploying:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1708991940210/45bedd23-d8e2-497f-bc9d-6bf56384f6b1.png" alt="List of DemoSolution components, including a Power Automate Flow called 'Send a test email' and a Connection Reference called 'Office 365 Outlook DemoSolution-6c497'" class="image--center mx-auto" /></p>
<p>As you can see, we have a Power Automate Flow that uses Outlook to send an email, as well as a <strong>connection reference</strong> that connects the Power Automate Flow to the Office 365 Outlook <strong>connection</strong>. We can see this if we open the connection reference.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709580161144/466aad61-c04c-4a72-8d36-52e7749400fa.png" alt="Office 365 Outlook connection reference details, with &quot;Connection&quot; listed in dropdown menu" class="image--center mx-auto" /></p>
<p>For our Development environment, it's fine that the connection reference is using my individual account, but let's explore how we can configure our solution to use a different connection in our Test and Prod environments.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">If you want to follow along, you can refer to my <a target="_blank" href="https://blog.richardcarrigan.dev/deploy-power-platform-solutions-using-azure-devops-pipelines">Deploy Power Platform solutions using Azure DevOps Pipelines</a> article. Once you have that set up, you'll need to create a new solution called "Demo Solution" that contains a single Flow that uses an Office 365 Outlook connection.</div>
</div>

<h3 id="heading-create-service-accounthttpsblogrichardcarrigandevdeploy-power-platform-solutions-using-azure-devops-pipelines"><a target="_blank" href="https://blog.richardcarrigan.dev/deploy-power-platform-solutions-using-azure-devops-pipelines">Create service account</a></h3>
<p>Since a service account is just a standard Microsoft Entra ID user account that isn't associated with a person (i.e., doesn't use MFA), the steps for creating one will be determined by your organization's Entra ID admins and are therefore likely to be different than the steps shown here. That being said, while logged in as a user with the ability to create a new user, go to <a target="_blank" href="https://entra.microsoft.com/#view/Microsoft_AAD_UsersAndTenants/CreateUser.ReactView">Create new user - Microsoft Entra admin center</a> to create a new service account.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709581564008/e82437ac-7fbd-41bf-8410-8c83684a9178.png" alt="Create new user form using &quot;serviceaccount&quot; as the name of the service account being created, using all default options." class="image--center mx-auto" /></p>
<p>All of the default options are fine, so you can select <strong>Review + create</strong> once you've provided a <strong>User principal name</strong> and a <strong>Display name</strong> for your service account. Make sure you save the password for later.</p>
<p>Once you've created the service account, you'll need to assign the usage location, which can be done by selecting the service account, selecting <strong>Edit properties</strong>, go to <strong>Settings</strong> tab, and select the country for the service account's usage location. Then, you'll be able to assign the necessary Power Platform licenses to this service account.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709584818082/d8ec12f3-cf16-46ba-b99f-dc9a91cd2bf0.png" alt="Adding usage location to service account properties" class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709584875944/60cbd5e6-7b07-4adf-90c7-78428318eefd.png" alt="Assigning various Power Platform licenses to service account" class="image--center mx-auto" /></p>
<h3 id="heading-add-service-account-to-target-environments">Add service account to target environment(s)</h3>
<p>Now that you've assigned the necessary licenses to your service account, for each of your target deployment environments, follow the steps to <a target="_blank" href="https://learn.microsoft.com/en-us/power-platform/admin/add-users-to-environment#add-users-to-an-environment-that-has-a-dataverse-database">Add users to an environment that has a Dataverse database</a> to add your service account. Make sure to assign the service account at least the System Customizer role so that it can manage the connections.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709585014947/172fd56c-1179-4430-bb3a-d55ec19e6213.png" alt="Adding user into Power Platform environment" class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709585052881/3abbb57c-72ca-4c12-97c9-aa6d4b919337.png" alt="Assigning System Customizer role to service account" class="image--center mx-auto" /></p>
<h3 id="heading-create-connections-in-target-environment">Create connections in target environment</h3>
<p>Great! Our service account has now been added into each of our target Power Platform environments. Next, we need to create each of the connections that will be used by our Flows and Apps. Here are the steps:</p>
<ol>
<li><p>Log into <a target="_blank" href="https://make.powerapps.com">make.powerapps.com</a> as the service account. Be sure to use separate browser window to avoid connection automatically using browser profile credentials. Update your password if prompted. If prompted to set up MFA, you can either dismiss it if you're just using it for this article or, if you plan on using this service account for production operations, discuss with your Entra ID admin for options to disable the MFA requirement for service accounts.</p>
</li>
<li><p>Select the target Power Platform environment from the list of environments in the top-right corner.</p>
</li>
<li><p>Select <strong>More</strong> from the left-side navigation menu, and then select <strong>Connections</strong>.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709585675514/76c3c26e-8290-45f4-ae33-7d65c84318fc.png" alt class="image--center mx-auto" /></p>
<ol start="4">
<li><p>Select either <strong>+ New connection</strong> or <strong>Create a connection</strong>.</p>
</li>
<li><p>Search for and select the <strong>Office 365 Outlook</strong> connection.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709585892294/f8b78f4c-27d4-4b72-a492-69695b251ff5.png" alt class="image--center mx-auto" /></p>
<ol start="6">
<li>Hit <strong>Create</strong> and authenticate using the service account.</li>
</ol>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">If you're following these instructions within a test Microsoft 365 environment, you'll receive an error that the REST API is not enabled. For our purposes, you can ignore this message since we're not actually expecting the Flow to run in the environment, but rather just exploring the process for associating service account connections to Power Platform solution connection references.</div>
</div>

<ol start="6">
<li>Repeat for additional target environments and connections needed.</li>
</ol>
<h3 id="heading-share-connections">Share connections</h3>
<p>Now that you've created the necessary connections in your target environment using your service account, you need to share this with the service principal that is used by your Azure DevOps pipeline to deploy the Power Platform solution into each environment. Here are the steps:</p>
<ol>
<li><p>From the list of connections you've created, select a connection.</p>
</li>
<li><p>Select <strong>Share</strong>.</p>
</li>
<li><p>Search for and select the service principal. If you aren't sure which service principal, you can get the service principal's application ID from the <strong>Service connections</strong> section of the Azure DevOps <strong>Project settings</strong> and then search for it that way.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709586945480/5d7ce303-a051-4e50-a1e7-f7390c96a780.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709586821106/76c491e5-e899-4bdb-bf22-4daf13423cb1.png" alt class="image--center mx-auto" /></p>
<ol start="4">
<li><p><strong>Save</strong>.</p>
</li>
<li><p>Repeat for additional environments and connections.</p>
</li>
</ol>
<h3 id="heading-add-connection-info-to-repo">Add connection info to repo</h3>
<p>With our connections created using our service account, and shared with our service principal, we're now ready to map our connection references to use these connections.</p>
<ol>
<li><p>At root of project, create <code>deployment-settings</code> folder</p>
</li>
<li><p>Within <code>deployment-settings</code> folder, create folder for each target environment, using target environment name as folder name. For example, if you have a target environment with a URL of <code>testenvironment.crm.dynamics.com</code>, you would name this folder <code>testenvironment</code>.</p>
</li>
<li><p>Within the target environment folder, create a JSON file named <code>[SolutionName].json</code> where <code>SolutionName</code> is the logical name of your solution, not the display name (i.e. without spaces).</p>
</li>
<li><p>Within the JSON file, add the following:</p>
</li>
</ol>
<pre><code class="lang-json">{
  <span class="hljs-attr">"EnvironmentVariables"</span>: [
  ],
  <span class="hljs-attr">"ConnectionReferences"</span>: [
  ]
}
</code></pre>
<ol start="5">
<li>Within the <code>ConnectionReferences</code> array, add an object containing the <code>LogicalName</code> of the connection reference, the <code>ConnectionId</code> of the connection created using your service account, and the <code>ConnectorId</code> of the type of connection being used. For example, if you have a connection reference with the name <code>My Solution Dataverse Connection</code> which has a logical name of <code>mypublisher_MySolutionDataverseConnection</code> that is using a Dataverse connection in the target environment, your connection reference object might look like this:</li>
</ol>
<pre><code class="lang-json">{
  <span class="hljs-attr">"LogicalName"</span>: <span class="hljs-string">"mypublisher_MySolutionDataverseConnection"</span>,
  <span class="hljs-attr">"ConnectionId"</span>: <span class="hljs-string">"shared-commondataser-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"</span>,
  <span class="hljs-attr">"ConnectorId"</span>: <span class="hljs-string">"/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps"</span>
}
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">To get the <code>ConnectionId</code> and <code>ConnectorId</code>, select the connection from within <a target="_blank" href="https://make.powerapps.com">make.powerapps.com</a> and copy it from the URL, which is in the format: <code>https://make.powerapps.com/environments/[EnvironmentId]/connections/[ConnectorId]/[ConnectionId]/details#</code></div>
</div>

<ol>
<li>Commit deployment settings to repo (e.g. <code>git commit -am "Adds deployment settings for [SolutionName]"</code>).</li>
</ol>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">You may be wondering why we created a <code>deployment-settings</code> folder and a folder for each environment, when we could have just named our JSON file to include the environment name and the solution name. The reason for this is scalability. Now that you have the folders, adding another solution means just adding the respective JSON files into the environment folders.</div>
</div>

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Each solution <strong>must have</strong> its own deployment settings file. If you try to deploy all of your solutions using the same deployment settings file, it will cause Power Platform to try and create multiple connection references and/or environment variables with the same name but different IDs, which will throw an error. Trust me!</div>
</div>

<h3 id="heading-update-deployment-pipeline">Update deployment pipeline</h3>
<p>Great work! Not only have you created and shared your service account's connections, but you've gone through the tedious process of mapping those connections to the connection references used in your solution. We're finally at the last step of this configuration, which is to update our Azure DevOps pipeline to use our deployment settings file when deploying the solution, like so:</p>
<pre><code class="lang-yaml"><span class="hljs-comment"># ... existing deployment steps</span>
          <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformImportSolution@2</span>
            <span class="hljs-attr">displayName:</span> <span class="hljs-string">'Import PP solution into target environment'</span>
            <span class="hljs-attr">inputs:</span>
              <span class="hljs-attr">authenticationType:</span> <span class="hljs-string">'PowerPlatformSPN'</span>
              <span class="hljs-attr">PowerPlatformSPN:</span> <span class="hljs-string">'Test Environment Service Connection Name'</span>
              <span class="hljs-attr">SolutionInputFile:</span> <span class="hljs-string">'$(Build.ArtifactStagingDirectory)\DemoSolution.zip'</span>
              <span class="hljs-attr">UseDeploymentSettingsFile:</span> <span class="hljs-literal">true</span>
              <span class="hljs-attr">DeploymentSettingsFile:</span> <span class="hljs-string">'deployment-settings\$(TargetEnvironmentName)\DemoSolution.json'</span>
              <span class="hljs-attr">AsyncOperation:</span> <span class="hljs-literal">true</span>
              <span class="hljs-attr">MaxAsyncWaitTime:</span> <span class="hljs-string">'60'</span>
<span class="hljs-comment"># ... continue existing deployment steps</span>
</code></pre>
<p>The key changes to our solution import step of the pipeline are:</p>
<ol>
<li><p>We added a <code>UseDeploymentSettingsFile</code> input with a value of <code>true</code> so the Power Platform task knows to use it.</p>
</li>
<li><p>We add a <code>DeploymentSettingsFile</code> input and specified the location of our solution- and environment-specific deployment settings JSON file, so the Power Platform task knows which file to use.</p>
</li>
</ol>
<p>Now that we've made these changes, let's commit them to the repo (e.g. <code>git commit -am "Adds deployment pipeline"</code>).</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You now have a way to connect all of your Apps and Flows to the connections they use, without relying on a team member's credentials, reliably. From here, you can also add in all of the environment variables that you use in each solution into the deployment settings JSON files.</p>
<p>Thanks for reading and, if you found this article useful, please consider sharing it across your network so others may be able to benefit from this information.</p>
<p>Take care!</p>
]]></content:encoded></item><item><title><![CDATA[Deploy Power Platform solutions using Azure DevOps Pipelines]]></title><description><![CDATA[After you've been working with the Power Platform for some time, it will become obvious that it can be difficult to present changes to an existing solution…]]></description><link>https://richardcarrigan.hashnode.dev/deploy-power-platform-solutions-using-azure-devops-pipelines</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/deploy-power-platform-solutions-using-azure-devops-pipelines</guid><category><![CDATA[PowerPlatform]]></category><category><![CDATA[application lifecycle management]]></category><category><![CDATA[azure-devops]]></category><category><![CDATA[Azure Pipelines]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Tue, 27 Feb 2024 18:00:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/E1Q1g_4HaNY/upload/b077eea854e7a163c46500be209b1731.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>After you've been working with the Power Platform for some time, it will become obvious that it can be difficult to present changes to an existing solution to stakeholders for approval without those same changes being immediately visible to your users. To solve this problem, you'll want to have at least 3 separate Power Platform environments, with a copy of the solution in each environment. These 3 environments will become your <strong>Development (Dev)</strong>, <strong>Test</strong>, and <strong>Production (Prod)</strong> environments. Later on in this article, I'll guide you through deploying your solutions to each of these environments, but for now, I want to give you a high-level overview of what a typical development workflow will look like with this configuration.</p>
<ol>
<li><p>Requested changes are worked on in the <strong>Dev</strong> environment.</p>
</li>
<li><p>Once the developer is satisfied with the changes, they are then deployed to the <strong>Test</strong> environment.</p>
</li>
<li><p>In the <strong>Test</strong> environment, stakeholders review the changes and provide approval.</p>
</li>
<li><p>Once changes are approved, changes are then deployed to the <strong>Prod</strong> environment.</p>
</li>
</ol>
<p>This workflow will allow you to simultaneously work on new features while awaiting approval on previously completed features, all while ensuring that users only see the features that have been fully reviewed and approved.</p>
<p>This multi-environment configuration is formally referred to as <strong>Application Lifecycle Management</strong>, or ALM for short. For more information on Power Platform ALM as a whole, refer to <a target="_blank" href="https://learn.microsoft.com/en-us/power-platform/alm/overview-alm">Application lifecycle management (ALM) with Microsoft Power Platform</a>.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before we can get started, you'll need to have at least 2 Power Platform environments created. You will also need to have an Azure DevOps project created, with a repo containing a Power Platform solution that has been exported and unpacked from your <strong>Dev</strong> environment. If you don't have these set up yet, or if you want to start with the same setup as mine to make following along easier, you can follow my guides on <a target="_blank" href="https://hashnode.com/post/clfsi7zdq04idx0nvb1p805kf">How to create a Power Platform test environment</a> and <a target="_blank" href="https://blog.richardcarrigan.dev/using-source-control-with-azure-devops-and-microsoft-power-platform">Using source control with Azure DevOps and Microsoft Power Platform</a> to do so, and then come back here when you're done.</p>
<p>Great! We're now ready to set up our Azure DevOps pipeline to deploy our Power Platform solution.</p>
<h2 id="heading-create-a-new-azure-devops-pipeline">Create a new Azure DevOps pipeline</h2>
<p>While it is possible to use the Power Platform CLI to upload our solution to our <strong>Test</strong> and <strong>Prod</strong> environments, it's not the best use of our time. Furthermore, if we went that route, we would need to document the entire process and <em>hope</em> that all of the developers on our team follow the same process. Instead, let's set up an Azure DevOps pipeline so that our website content automatically gets uploaded to the <strong>Test</strong> and <strong>Prod</strong> environments.</p>
<blockquote>
<p>Note: this pipeline requires the Power Platform Build Tools to be added to Azure DevOps, as well as a service connection to your target environment. See <a target="_blank" href="https://learn.microsoft.com/en-us/power-platform/alm/devops-build-tools#get-microsoft-power-platform-build-tools">Get Microsoft Power Platform Build Tools</a> for instructions on how to configure both.</p>
</blockquote>
<p>Within the <strong>Pipelines</strong> section of your Azure DevOps project, let's go to <strong>Pipelines</strong> and select <strong>Create Pipeline</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682370868144/2ece99e9-26b9-4d1b-bb31-3c5b17be81d0.png" alt="Screenshot of Azure DevOps Pipelines section with &quot;Create Pipeline&quot; button." class="image--center mx-auto" /></p>
<p>From here, choose the following options:</p>
<ul>
<li><p>Azure Repos Git</p>
</li>
<li><p>Repo name (i.e. <code>powerplatformdemos</code>)</p>
</li>
<li><p>Starter pipeline</p>
</li>
</ul>
<p>This will create a new <code>azure-pipelines.yml</code> file at the root of your project repo. With this file open in Azure DevOps, replace the default code with the following:</p>
<pre><code class="lang-yaml"><span class="hljs-comment"># only run pipeline for changes within the 'websites' folder, and only on the 'main' branch of the repo.</span>
<span class="hljs-attr">trigger:</span>
  <span class="hljs-attr">branches:</span>
    <span class="hljs-attr">include:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">main</span>
  <span class="hljs-attr">paths:</span>
    <span class="hljs-attr">include:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">solutions/*</span>

<span class="hljs-comment"># use a Windows VM, as it is necessary for the Power Platform Tools</span>
<span class="hljs-attr">pool:</span>
  <span class="hljs-attr">vmImage:</span> <span class="hljs-string">windows-latest</span>

<span class="hljs-attr">steps:</span>
  <span class="hljs-comment"># checkout the repo</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">checkout:</span> <span class="hljs-string">self</span>

  <span class="hljs-comment"># install the Power Platform tools (required before running Power Platform tasks)</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformToolInstaller@2</span>
    <span class="hljs-attr">inputs:</span>
      <span class="hljs-attr">DefaultVersion:</span> <span class="hljs-literal">true</span>

  <span class="hljs-comment"># pack solution into .zip file</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformPackSolution@2</span>
    <span class="hljs-attr">inputs:</span>
      <span class="hljs-attr">SolutionSourceFolder:</span> <span class="hljs-string">'./solutions/[solution-folder-name]'</span>
      <span class="hljs-attr">SolutionOutputFile:</span> <span class="hljs-string">'$(Build.ArtifactStagingDirectory)\solutions\[solution-name].zip'</span>
      <span class="hljs-attr">SolutionType:</span> <span class="hljs-string">'Managed'</span>

  <span class="hljs-comment"># import the solution into the test environment</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformImportSolution@2</span>
    <span class="hljs-attr">inputs:</span>
      <span class="hljs-attr">authenticationType:</span> <span class="hljs-string">'PowerPlatformSPN'</span>
      <span class="hljs-attr">PowerPlatformSPN:</span> [<span class="hljs-string">test-env-service-connection</span>]
      <span class="hljs-attr">SolutionInputFile:</span> <span class="hljs-string">'$(Build.ArtifactStagingDirectory)\solutions\[solution-name].zip'</span>
      <span class="hljs-attr">AsyncOperation:</span> <span class="hljs-literal">true</span>
      <span class="hljs-attr">MaxAsyncWaitTime:</span> <span class="hljs-string">'60'</span>

  <span class="hljs-comment"># import the solution into the prod environment</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformImportSolution@2</span>
    <span class="hljs-attr">inputs:</span>
      <span class="hljs-attr">authenticationType:</span> <span class="hljs-string">'PowerPlatformSPN'</span>
      <span class="hljs-attr">PowerPlatformSPN:</span> [<span class="hljs-string">prod-env-service-connection</span>]
      <span class="hljs-attr">SolutionInputFile:</span> <span class="hljs-string">'$(Build.ArtifactStagingDirectory)\solutions\[solution-name].zip'</span>
      <span class="hljs-attr">AsyncOperation:</span> <span class="hljs-literal">true</span>
      <span class="hljs-attr">MaxAsyncWaitTime:</span> <span class="hljs-string">'60'</span>
</code></pre>
<p>Make sure to replace <code>[test-env-service-connection]</code>, <code>[prod-env-service-connection]</code>, and <code>[solution-folder-name]</code> with their respective values from your unique configuration.</p>
<p>With our pipeline code added, let's <strong>Save and run</strong>. If you have branch security enabled, you may need to <strong>Create a new branch for this commit</strong> and then submit a pull request (PR). Otherwise, we can <strong>Commit directly to the main branch</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1708995258837/414e0ca3-73bb-420d-a686-9f45c47a740c.png" alt="Screenshot of 'Save and run' step of creating a new Azure DevOps pipeline" class="image--center mx-auto" /></p>
<p>If this is a new pipeline, you'll also need to grant your pipeline access to the service connections.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682372747005/3aa8159a-7567-46ec-942f-6e41dab67501.png" alt="Permission review menu for Azure DevOps pipeline." class="image--center mx-auto" /></p>
<p>Once you've granted access, your pipeline will now run, deploying any solution changes from your <strong>Dev</strong> environment to your <strong>Test</strong> and <strong>Prod</strong> environments.</p>
<h2 id="heading-conclusion-next-steps">Conclusion - Next steps</h2>
<p>Great job! You've now configured a true CI/CD pipeline for deploying your Power Platform solution. This is a <strong>HUGE</strong> improvement over just a single environment for your Power Platform solution, or even over manually uploading components from one environment to another.</p>
<p>Thanks for reading and, if you found this article useful, please consider sharing it across your network so others may be able to benefit from this information.</p>
<p>Take care!</p>
]]></content:encoded></item><item><title><![CDATA[Using source control with Azure DevOps and Microsoft Power Platform]]></title><description><![CDATA[Source, or version, control is a fundamental component of modern software development. Regardless of what your technology stack looks like, it is necessary…]]></description><link>https://richardcarrigan.hashnode.dev/using-source-control-with-azure-devops-and-microsoft-power-platform</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/using-source-control-with-azure-devops-and-microsoft-power-platform</guid><category><![CDATA[azure-devops]]></category><category><![CDATA[PowerPlatform]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Tue, 27 Jun 2023 17:00:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/842ofHC6MaI/upload/63eae0787d453686826c0748b1e3d34d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Source, or version, control is a fundamental component of modern software development. Regardless of what your technology stack looks like, it is necessary to track changes, match versions with releases, and revert to a previous version in case of accidental deployment of bugs or breaking changes if necessary. In this tutorial, we'll see how we can apply this to our Power Platform environment using <strong>solutions</strong>.</p>
<h2 id="heading-what-are-power-platform-solutions">What are Power Platform solutions?</h2>
<p>Simply put, a Power Platform solution is a container for grouping together related Power Platform components, such as Power Apps, Power Automate flows, Dataverse tables, and so on, so they always move together when deploying from one environment to another. To make this more concrete, let's create a simple Canvas Power App that displays a list of contacts.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This tutorial assumes that you already have a Power Platform environment that you can build within. If that's not the case, follow my guide on <a target="_blank" href="https://blog.richardcarrigan.dev/how-to-create-a-power-platform-test-environment">How to create a Power Platform test environment</a> to set one up.</div>
</div>

<h3 id="heading-create-a-new-solution">Create a new solution</h3>
<p>First, let's go to <a target="_blank" href="https://make.preview.powerapps.com/">make.powerapps.com</a>. Once you're there, make sure that you have the right environment selected in the top-right corner.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687814447885/bda2c5ac-5bd5-4d66-b92c-0a751c909d3f.png" alt="Power Apps Admin Center with environment circled" class="image--center mx-auto" /></p>
<p>Next, let's go to <strong>Solutions</strong> so we can create a new solution to group our new canvas app and related components.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687814506312/2832708e-5125-41c3-a945-e008008f55dc.png" alt="Power Apps Admin Center with solutions menu item circled" class="image--center mx-auto" /></p>
<p>From the solutions page, select <strong>+ New solution</strong> and then fill in the <strong>Display name</strong>, <strong>Publisher</strong> (default is fine)<strong>,</strong> and then hit <strong>Create</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687814719323/27adb1ae-8ab2-4409-a14f-dec6b2d48892.png" alt="New solution dialog blade" class="image--center mx-auto" /></p>
<h3 id="heading-add-new-canvas-power-app">Add new Canvas Power App</h3>
<p>Great! Now we have a Power Platform solution to put all of our components in, so let's start building. First, let's create a new canvas Power App. To do this, select the dropdown menu next to <strong>+ New</strong>, then choose <strong>App</strong>, and then choose <strong>Canvas app</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687814891233/2e566d7c-9179-4a32-af96-cc9a28047229.png" alt="New solution component menu with Canvas app circled" class="image--center mx-auto" /></p>
<p>In the dialog box that comes up, give your new app a name, such as <strong>Contact Viewer App</strong> and then choose <strong>Create</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687815001928/c3229dc0-faaf-485e-8882-27915ca266b7.png" alt="New canvas app form" class="image--center mx-auto" /></p>
<p>With our new canvas app created, let's connect it to the <strong>Contacts</strong> table to display a list of the contacts in our database. To do this, choose <strong>connect to data</strong> on the canvas, or select <strong>Add data</strong> from the top menu.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687817155678/b7230944-5b31-49cf-8b0b-ac0a06dfad2e.png" alt="Blank canvas app with connect to data circled" class="image--center mx-auto" /></p>
<p>Once the list of tables opens, select <strong>Contacts</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687817220694/ed6b3411-bf45-4c74-b7b4-75e2786eb82f.png" alt="Add data menu with Contacts table circled" class="image--center mx-auto" /></p>
<p>With our <strong>Contacts</strong> table added, now let's choose <strong>Insert</strong> and select the <strong>Data table (preview)</strong> option from within the <strong>Layout</strong> category.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687817330717/28c0559b-c1be-4bc9-b28d-ab9217b77a8e.png" alt="Insert component menu with Data table (preview) circled" class="image--center mx-auto" /></p>
<p>Once the data table gets added to our canvas, choose the <strong>Contacts</strong> table.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687817410275/9184642a-4252-4675-9cd3-1d197e134053.png" alt="Select a data source menu with Contacts table circled" class="image--center mx-auto" /></p>
<p>You should now have a data table with a list of contacts. With that, our simple canvas app is finished, so let's hit <strong>Publish</strong> in the top-right corner.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687817493722/4eb92a73-2101-4ff7-9568-6aae92a3ce72.png" alt="Completed canvas app with publish button circled" class="image--center mx-auto" /></p>
<p>Once the app finishes publishing, hit <strong>Back</strong> to get back to our solution.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687817546005/4cb56190-4f3a-41a7-b657-12463b9256d9.png" alt="Completed canvas app with back button circled" class="image--center mx-auto" /></p>
<h3 id="heading-adding-related-components">Adding related components</h3>
<p>You should now see your newly-created canvas app listed as the only component within our solution. However, we know that our solution depends on the the <strong>Contacts</strong> table from the Dataverse, so let's add that as another component in our solution.</p>
<p>To do this, select <strong>Add existing</strong>, and then choose <strong>Table</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687817694078/1252fc09-bc85-4485-860a-2dccb7b4783a.png" alt="Add existing component menu with Table circled" class="image--center mx-auto" /></p>
<p>From the <strong>Add existing tables</strong> menu, choose the <strong>Contact</strong> table and hit <strong>Next</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687817738655/e463074b-2851-49f8-bac1-9c66781b2276.png" alt="Add existing tables menu with Contact table circled" class="image--center mx-auto" /></p>
<p>From here, we could specify exactly which objects (columns, relationships, keys, etc.) to include, but we would then have to make sure this gets updated any time we update the canvas app to include other objects, so I recommend selecting <strong>Include all objects</strong>. With that selected, hit <strong>Add</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687817872054/cef8e448-3b57-4db4-984d-6cdfcc8e60ac.png" alt="Selected tables menu with Include all objects checked" class="image--center mx-auto" /></p>
<p>We now have a Power Platform solution that contains our newly-created canvas app, as well as the Dataverse table that it depends upon. Next, let's explore how to add this solution to source control.</p>
<h2 id="heading-azure-devops-setup"><strong>Azure DevOps setup</strong></h2>
<p>Now that we have our solution, we need to set up our Azure DevOps project so we have a place to store the files once we export them. In order to start working with Azure DevOps, we'll need an account. So go to <a target="_blank" href="http://dev.azure.com"><strong>dev.azure.com</strong></a> and, if you already have an Azure DevOps account, log into that. Otherwise, click <strong>Start free</strong> or <strong>Start free with GitHub</strong>, whichever you prefer.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679504224473/c763d79a-68b2-402f-a8c8-381fde835462.png?auto=compress,format&amp;format=webp" alt="Azure DevOps landing page" /></p>
<p>If this is a new Azure DevOps account, you'll be prompted to create a new project. If you're logging into an existing account, you'll need to select <strong>+ New project</strong> in the top-right corner. Once you've reached the new project wizard, simply give your new project a name and hit <strong>+ Create project</strong>. This project will be used to store all of our Power Platform environment files, so the name should reflect that. You may be given the options for version control and agile process, but the defaults are usually fine unless you know you'll need something else.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679507556824/b1754fc9-36ba-4372-89d4-a28dec964091.png?auto=compress,format&amp;format=webp" alt="Azure DevOps create project screen" /></p>
<p>Now that we have a new Azure DevOps project, we need to create a <strong>Repo</strong> (or repository) to store our Power Pages solution. To do this, select <strong>Repos</strong> on the sidebar and then choose <strong>Initialize</strong> under the heading <strong>Initialize main branch with a README or gitignore</strong>. We'll want to have the README file, but we don't need a gitignore file for now, so the defaults are fine.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679507604016/568e7087-c58a-4bc0-bc4f-d93544e13a84.png?auto=compress,format&amp;format=webp" alt="Newly-created Azure DevOps Repo" /></p>
<h2 id="heading-clone-the-project-repo-to-our-local-machine">Clone the project repo to our local machine</h2>
<p>Alright, so we have our Azure DevOps project set up. Next, we need to connect a folder on our local machine to the new project. To do that, select <strong>Clone</strong> in the top-right and then copy the HTTPS URL provided. Alternatively, if you know what you're doing, you could also use SSH or the <strong>Clone in VS Code</strong> option if you already have that installed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679507486679/0ab2d0f9-0dfe-4cbb-b01d-61770f96831b.png?auto=compress,format&amp;format=webp" alt="Clon Repository flyout menu on Azure DevOps" /></p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">the following steps assume that you already have Git installed. If that is not the case, follow <a target="_blank" href="https://git-scm.com/book/en/v2/Getting-Started-Installing-Git">these instructions</a> before continuing.</div>
</div>

<p>Back on your local machine, open a new terminal window (Git Bash, Windows Terminal, etc.) and navigate to the directory where you want your Power Pages website files stored (i.e. Documents folder) and then use <code>git clone</code> to copy your newly-created repo into this directory. For example:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> ~/Documents
git <span class="hljs-built_in">clone</span> https://powerplatformdevops2023@dev.azure.com/powerplatformdevops2023/Power%20Platform%20DevOps/_git/Power_Platform_DevOps
</code></pre>
<p>Once the cloning process finishes, you'll have a directory named the same as your Azure DevOps project, <strong>Power_Platform_DevOps</strong>.</p>
<p>Ok, so now we have a directory on our local machine containing a README file. What now? Thank you for asking 😀! Next, we need to export the Power solution, <strong>unpack</strong> it into this new directory, and then upload those files to our newly-created Azure DevOps repo.</p>
<p>But first, let's use the following commands to create a <strong>solutions</strong> directory to store these files in. This will make it easier for us to distinguish between the files needed for each of our Power Platform solutions and other files that are part of our Power Platform environment, such as Power Pages website content and deployment files.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> Power_Platform_DevOps
mkdir solutions
</code></pre>
<h2 id="heading-adding-solution-to-source-control">Adding solution to source control</h2>
<p>We now have a Power Platform solution ready to be checked into source control, and a repo ready to store the solution files. Now all that's left is to get the files from our Power Platform environment and add them to our repo.</p>
<h3 id="heading-export-solution">Export solution</h3>
<p>To get the solution onto our local machine, we need to export it out of the Power Platform environment. To do that, go back to <a target="_blank" href="https://make.powerapps.com">make.powerapps.com</a>, select <strong>Solutions</strong>, and then check the box next to the solution you created earlier. With the solution selected, hit <strong>Export solution</strong> from the top menu.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687818982888/c7eaaeed-d2bd-4490-b6fd-b530ef3347b1.png" alt="Power Apps Admin Center with Export solution circled" class="image--center mx-auto" /></p>
<p>We've already published all of our changes, so we can just hit <strong>Next</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687819016861/037a358f-7e50-4f81-9de4-3ef7df172389.png" alt="Before you export menu" class="image--center mx-auto" /></p>
<p>Now this screen is important. When we export a solution from a development environment with the intent to add it to source control and/or deploy it to a test or production (live) environment, we should always make sure to export the solution as managed. Unmanaged solutions are for moving a solution between two development environments only. Once we verify that <strong>Managed</strong> is selected, let's hit <strong>Export</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687819173082/d536ac41-e391-4692-a5f2-efd51ef273e1.png" alt="Export this solution menu with Export button circled" class="image--center mx-auto" /></p>
<p>After a few minutes, the exported solution will be ready for download. Once it is, hit <strong>Download</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687819243589/25105e9d-ecdf-4ee7-a041-c762921423b8.png" alt="Exported solution message with Download button circled" class="image--center mx-auto" /></p>
<h3 id="heading-unpack-solution">Unpack solution</h3>
<p>Before we can add the solution files to our repo, we need to <strong>unpack</strong> them. <strong>Unpacking</strong> is different from unzipping/extracting as it uses a special Power Platform CLI command to prepare the solution specifically for the purpose of checking into source control. This is also necessary because any deployment pipeline you set up later will include a <strong>pack solution</strong> step which will expect that the solution was properly unpacked.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The following steps require the Power Platform CLI installed, either by itself or as part of the Visual Studio Code extension. If you don't already have this installed, follow the instructions to <a target="_blank" href="https://learn.microsoft.com/en-us/power-platform/developer/cli/introduction#install-using-power-platform-tools-for-visual-studio-code"><strong>Install using Power Platform Tools for Visual Studio Code</strong></a><strong> </strong>or<strong> </strong>to <a target="_blank" href="https://learn.microsoft.com/en-us/power-platform/developer/cli/introduction#install-power-platform-cli-for-windows"><strong>Install Power Platform CLI for Windows</strong></a>.</div>
</div>

<p>To unpack your solution and add it to your local repo, use the following command. Be sure to replace the <code>zipfile</code> and <code>folder</code> parameters with the appropriate file paths based on where you downloaded the solution to, and where you cloned your repo to, respectively.</p>
<pre><code class="lang-bash">pac solution unpack --zipfile ~/Downloads/ContactViewer_1_0_0_1_managed.zip --folder ~/Documents/Power_Platform_DevOps/solutions/ContactViewer --packagetype Managed
</code></pre>
<p>Once that command executes, you should now see that your repo contains a single folder named <code>ContactViewer</code> within your <code>solutions</code> folder, which contains all of the solution components (i.e. <code>CanvasApps</code> and <code>Entities</code>), along with <code>Other</code> necessary files for source control tracking and deployments.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687820225001/622d1178-8eeb-44fe-8594-ede85f376762.png" alt="Screenshot of repo folder structure including solution files" class="image--center mx-auto" /></p>
<h3 id="heading-checking-solution-into-source-control">Checking solution into source control</h3>
<p>Now that we have exported and unpacked our solution, all that's left is to check it into our Azure DevOps repo. To do that, we'll use the <code>git add</code>, <code>git commit</code>, and <code>git push</code> commands, like so:</p>
<pre><code class="lang-bash">git add . <span class="hljs-comment"># adds all untracked/changed files to the 'staging area' to be committed</span>
git commit -m <span class="hljs-string">"Adds ContactViewer solution to source control"</span> <span class="hljs-comment"># commits the changes to version history</span>
git push origin main <span class="hljs-comment"># pushes any new local commits to the remote (origin) repo</span>
</code></pre>
<p>If the commands all executed successfully, you should see an output similar to this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687820523074/1bc40abc-7ee3-4e2a-8605-228e0ac8f64c.png" alt="Screenshot of bash terminal with git command output" class="image--center mx-auto" /></p>
<p>And if you go back to your Azure DevOps repo and refresh, you should now see your exported solution files added, like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687820578443/7bf317f1-8c8f-4208-9de3-000062fc4ace.png" alt="Azure DevOps repo with solution files circled" class="image--center mx-auto" /></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thanks for sticking around! You have now seen how to track changes in Power Platform components using solutions and Azure DevOps, but this is just the beginning. Now you can build a CI/CD pipeline that will test and deploy your solutions to other environments, which will enable more consistent and traceable deployments.</p>
<p>Thanks for reading and, if you found this article useful, please consider sharing it across your network so others may be able to benefit from this information.</p>
<p>Take care!</p>
]]></content:encoded></item><item><title><![CDATA[Get Microsoft Teams private channel members using PowerShell]]></title><description><![CDATA[When managing teams within Microsoft Teams, you may run into an odd situation in which you are an owner of the team but are unable to view that team's…]]></description><link>https://richardcarrigan.hashnode.dev/get-microsoft-teams-private-channel-members-using-powershell</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/get-microsoft-teams-private-channel-members-using-powershell</guid><category><![CDATA[MicrosoftTeams]]></category><category><![CDATA[Powershell]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Tue, 20 Jun 2023 17:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/1Y-hk45tyMs/upload/a568b8feafdbbc54dc60aeb0f8b13559.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When managing teams within Microsoft Teams, you may run into an odd situation in which you are an owner of the team but are unable to view that team's private channels. In this article, I'll show you how you can not only view the <em>complete</em> list of channels within a team that you own but also view the membership list for those channels. In addition, we'll format and print the entire list of channels and members to a text file for future reference or to serve as a sort of backup when preparing to make potentially breaking changes.</p>
<h2 id="heading-im-an-owner-why-cant-i-see-all-the-channels">I'm an owner. Why can't I see all the channels?</h2>
<p>While this may not make sense at first glance, there is a great reason for this. Consider the following configuration:</p>
<ul>
<li><p>Manager A is working on a project containing sensitive documents</p>
</li>
<li><p>Admin B is responsible for managing access to the team, but doesn't have a business requirement for accessing those sensitive documents</p>
</li>
</ul>
<p>If Admin B were to have the ability to make changes to any private channel within a team that they own, nothing would prevent them from granting themselves or anyone else access to these sensitive documents and discussions contained within the private channel. Therefore, it makes sense that the owner of a team isn't authorized to make changes to its membership.</p>
<h2 id="heading-fine-but-why-cant-i-view-the-membership">Fine, but why can't I view the membership?</h2>
<p>This is a great question, and it's the exact question that drove me to create the PowerShell script and this accompanying blog post. Referring to the Microsoft documentation regarding <a target="_blank" href="https://learn.microsoft.com/en-us/microsoftteams/private-channels">Private channels in Microsoft Teams</a>, we can see that "Team owners can see the names of all private channels in their team". That's great, but we can easily see that we, in fact, can <em>not</em> see the private channels while in Microsoft Teams. However, as I'll show you, this is possible using PowerShell.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before we can start building our PowerShell script, let's make sure we have all the necessary pieces installed.</p>
<h3 id="heading-install-powershell">Install PowerShell</h3>
<p>If you're using Windows, you already have PowerShell installed. For any other operating system, or if you'd like to install a different version of PowerShell than the one installed by default, follow these instructions for <a target="_blank" href="https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-windows?view=powershell-7.3">Windows</a>, <a target="_blank" href="https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-macos?view=powershell-7.3">MacOS</a>, or <a target="_blank" href="https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-linux?view=powershell-7.3">Linux</a>.</p>
<h3 id="heading-install-the-microsoft-teams-powershell-module">Install the Microsoft Teams PowerShell module</h3>
<p>Now that we have PowerShell installed, we'll need to also install the Microsoft Teams module to connect and perform operations with Microsoft Teams. To do this, follow these instructions to <a target="_blank" href="https://learn.microsoft.com/en-us/microsoftteams/teams-powershell-install">Install Microsoft Teams PowerShell Module</a>.</p>
<h2 id="heading-the-script">The script</h2>
<p>Alright, we now understand why we need to view the private channels and members within a team that we own, we know that it's not possible through Microsoft Teams and must be done through PowerShell, and we've even installed all the necessary tools for the job. The only thing left to do now is to actually write the script.</p>
<h3 id="heading-authenticating-to-microsoft-teams">Authenticating to Microsoft Teams</h3>
<p>To be able to perform any operations against the teams that we own, we first need to tell Microsoft Teams who we are, so our authorization can be verified. To do this, we simply run the command:</p>
<pre><code class="lang-powershell"><span class="hljs-built_in">Connect-MicrosoftTeams</span>;
</code></pre>
<p>Running this command will open a new browser window and walk us through the Microsoft authentication process. Be sure to use the same login credentials that correspond to the teams that you are looking to perform operations against.</p>
<h3 id="heading-get-the-groupid-and-private-channels">Get the <code>GroupId</code> and private <code>Channels</code></h3>
<p>Now that we've connected to Microsoft Teams, let's get the <code>GroupId</code> for our team, as well as the list of private <code>Channels</code>. The <code>GroupId</code> is necessary for us to get the list of channels, as well as when we start requesting the members for each channel.</p>
<p>To get the <code>GroupId</code>, the command is:</p>
<pre><code class="lang-powershell"><span class="hljs-variable">$GroupId</span> = (<span class="hljs-built_in">Get-Team</span> <span class="hljs-literal">-DisplayName</span> <span class="hljs-string">"Your team name here"</span>).GroupId;
</code></pre>
<p>Then, to get the list of channels, the command is:</p>
<pre><code class="lang-powershell"><span class="hljs-variable">$Channels</span> = <span class="hljs-built_in">Get-TeamChannel</span> <span class="hljs-literal">-GroupId</span> <span class="hljs-variable">$GroupId</span> | <span class="hljs-built_in">Where-Object</span> { <span class="hljs-variable">$_</span>.MembershipType <span class="hljs-operator">-eq</span> <span class="hljs-string">"Private"</span> };
</code></pre>
<p>To make sure we were successful, let's write the output to our terminal window, like so:</p>
<pre><code class="lang-powershell"><span class="hljs-built_in">Write-Host</span> <span class="hljs-variable">$GroupId</span>;
<span class="hljs-keyword">foreach</span> (<span class="hljs-variable">$channel</span> <span class="hljs-keyword">in</span> <span class="hljs-variable">$Channels</span>) {
  <span class="hljs-built_in">Write-Host</span> <span class="hljs-variable">$channel</span>.DisplayName;
}
</code></pre>
<p>If successful, we should see an output similar to this:</p>
<pre><code class="lang-powershell">Your team name here
Channel <span class="hljs-number">1</span>
Channel <span class="hljs-number">2</span>
...
</code></pre>
<h3 id="heading-get-the-members-for-each-private-channel">Get the members for each private channel</h3>
<p>We now have a list of the private <code>Channels</code>, so that's great. Next, let's see if we can get a list of the members within each private channel. To do this, add the following command within the <code>foreach</code> loop you created earlier:</p>
<pre><code class="lang-powershell"><span class="hljs-variable">$members</span> = <span class="hljs-built_in">Get-TeamChannelUser</span> <span class="hljs-literal">-GroupId</span> <span class="hljs-variable">$GroupId</span> <span class="hljs-literal">-DisplayName</span> <span class="hljs-variable">$channel</span>.DisplayName;
</code></pre>
<p>Just like before, let's check it by writing the output to the terminal, like so:</p>
<pre><code class="lang-powershell"><span class="hljs-keyword">foreach</span> (<span class="hljs-variable">$member</span> <span class="hljs-keyword">in</span> <span class="hljs-variable">$members</span>) {
  <span class="hljs-built_in">Write-Host</span> <span class="hljs-variable">$member</span>.Name
}
</code></pre>
<p>If successful, we should see an output similar to this:</p>
<pre><code class="lang-powershell">Member <span class="hljs-number">1</span>
Member <span class="hljs-number">2</span>
...
</code></pre>
<h3 id="heading-putting-it-all-together">Putting it all together</h3>
<p>Sweet! We are now able to get a list of all private <code>Channels</code> within a team and, for each channel, we can get a list of all members. At this point, you're full script should look like this:</p>
<pre><code class="lang-powershell"><span class="hljs-built_in">Connect-MicrosoftTeams</span>;

<span class="hljs-variable">$GroupId</span> = (<span class="hljs-built_in">Get-Team</span> <span class="hljs-literal">-DisplayName</span> <span class="hljs-string">"Your team name here"</span>).GroupId;
<span class="hljs-variable">$Channels</span> = <span class="hljs-built_in">Get-TeamChannel</span> <span class="hljs-literal">-GroupId</span> <span class="hljs-variable">$GroupId</span> | <span class="hljs-built_in">Where-Object</span> { <span class="hljs-variable">$_</span>.MembershipType <span class="hljs-operator">-eq</span> <span class="hljs-string">"Private"</span> };

<span class="hljs-built_in">Write-Host</span> <span class="hljs-variable">$GroupId</span>;
<span class="hljs-keyword">foreach</span> (<span class="hljs-variable">$channel</span> <span class="hljs-keyword">in</span> <span class="hljs-variable">$Channels</span>) {
  <span class="hljs-built_in">Write-Host</span> <span class="hljs-variable">$channel</span>.DisplayName;

  <span class="hljs-variable">$members</span> = <span class="hljs-built_in">Get-TeamChannelUser</span> <span class="hljs-literal">-GroupId</span> <span class="hljs-variable">$GroupId</span> <span class="hljs-literal">-DisplayName</span> <span class="hljs-variable">$channel</span>.DisplayName;

  <span class="hljs-keyword">foreach</span> (<span class="hljs-variable">$member</span> <span class="hljs-keyword">in</span> <span class="hljs-variable">$members</span>) {
    <span class="hljs-built_in">Write-Host</span> <span class="hljs-variable">$member</span>.Name
  }
}
</code></pre>
<p>Which should generate the following output:</p>
<pre><code class="lang-powershell">Your team name here
Channel <span class="hljs-number">1</span>
Member <span class="hljs-number">1</span>
Member <span class="hljs-number">2</span>
...
Channel <span class="hljs-number">2</span>
Member <span class="hljs-number">1</span>
Member <span class="hljs-number">2</span>
...
</code></pre>
<h2 id="heading-improvements">Improvements</h2>
<p>The script above is great, but there are a couple of key improvements I'd like to make, which will make this script even more useful. First, we'll refactor the script to loop through a list of teams instead of just a single team. Then, we'll replace our <code>Write-Host</code> commands with something else so that the output is saved into a text file.</p>
<h3 id="heading-looping-through-a-list-of-teams">Looping through a list of teams</h3>
<p>Right after we connect to Microsoft Teams, but before we request the <code>GroupId</code>, let's add an array or list of teams containing the <code>Name</code> of each team we want to look at, along with a <code>GroupId</code> that will contain the unique ID for this team, and an array of <code>Channels</code> that will contain the information for each private channel within this team.</p>
<pre><code class="lang-powershell"><span class="hljs-variable">$teams</span> = <span class="hljs-selector-tag">@</span>(
  [<span class="hljs-type">PSCustomObject</span>]<span class="hljs-selector-tag">@</span>{
    Name = <span class="hljs-string">"Your first team name here"</span>
    GroupId = <span class="hljs-string">""</span> <span class="hljs-comment"># Empty for now</span>
    Channels = <span class="hljs-selector-tag">@</span>() <span class="hljs-comment"># Also empty for now</span>
  },
  [<span class="hljs-type">PSCustomObject</span>]<span class="hljs-selector-tag">@</span>{
    Name = <span class="hljs-string">"Your second team name here"</span>
    GroupId = <span class="hljs-string">""</span> <span class="hljs-comment"># Empty for now</span>
    Channels = <span class="hljs-selector-tag">@</span>() <span class="hljs-comment"># Also empty for now</span>
  },
  [<span class="hljs-type">PSCustomObject</span>]<span class="hljs-selector-tag">@</span>{
    Name = <span class="hljs-string">"Your third team name here"</span>
    GroupId = <span class="hljs-string">""</span> <span class="hljs-comment"># Empty for now</span>
    Channels = <span class="hljs-selector-tag">@</span>() <span class="hljs-comment"># Also empty for now</span>
  }
);
</code></pre>
<blockquote>
<p>If this syntax is unfamiliar to you, refer to <a target="_blank" href="https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-arrays?view=powershell-7.3"><strong>Everything you wanted to know about arrays</strong></a><strong>, specifically the section on</strong> <a target="_blank" href="https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-arrays?view=powershell-7.3#arrays-of-objects"><strong>Arrays of Objects</strong></a><strong>.</strong></p>
</blockquote>
<p>Next, let's enclose the rest of our script within a <code>foreach</code> loop, which will iterate through each team in our <code>$teams</code> array.</p>
<pre><code class="lang-powershell"><span class="hljs-comment"># $teams array above</span>
<span class="hljs-keyword">foreach</span> (<span class="hljs-variable">$team</span> <span class="hljs-keyword">in</span> <span class="hljs-variable">$teams</span>) {
  <span class="hljs-comment"># team-specific scripts go here</span>
};
</code></pre>
<p>Finally, let's replace every instance of <code>$GroupId</code> and <code>$Channels</code> with <code>$team.GroupId</code> and <code>$team.Channels</code>, respectively. Also, make sure to replace the text <code>"Your team name here"</code> with <code>$team.Name</code> to refer to the current team being processed. Let's also write each team name instead of the <code>GroupId</code> to the output and do a bit of formatting so it's easier to see the hierarchy of teams, channels, and members. The end result of these changes looks like this:</p>
<pre><code class="lang-powershell"><span class="hljs-built_in">Connect-MicrosoftTeams</span>;

<span class="hljs-variable">$teams</span> = <span class="hljs-selector-tag">@</span>(
  [<span class="hljs-type">PSCustomObject</span>]<span class="hljs-selector-tag">@</span>{
    Name = <span class="hljs-string">"Your first team name here"</span>
    GroupId = <span class="hljs-string">""</span> <span class="hljs-comment"># Empty for now</span>
    Channels = <span class="hljs-selector-tag">@</span>() <span class="hljs-comment"># Also empty for now</span>
  },
  [<span class="hljs-type">PSCustomObject</span>]<span class="hljs-selector-tag">@</span>{
    Name = <span class="hljs-string">"Your second team name here"</span>
    GroupId = <span class="hljs-string">""</span> <span class="hljs-comment"># Empty for now</span>
    Channels = <span class="hljs-selector-tag">@</span>() <span class="hljs-comment"># Also empty for now</span>
  },
  [<span class="hljs-type">PSCustomObject</span>]<span class="hljs-selector-tag">@</span>{
    Name = <span class="hljs-string">"Your third team name here"</span>
    GroupId = <span class="hljs-string">""</span> <span class="hljs-comment"># Empty for now</span>
    Channels = <span class="hljs-selector-tag">@</span>() <span class="hljs-comment"># Also empty for now</span>
  }
);

<span class="hljs-keyword">foreach</span> (<span class="hljs-variable">$team</span> <span class="hljs-keyword">in</span> <span class="hljs-variable">$teams</span>) {
  <span class="hljs-variable">$team</span>.GroupId = (<span class="hljs-built_in">Get-Team</span> <span class="hljs-literal">-DisplayName</span> <span class="hljs-variable">$team</span>.Name).GroupId;
  <span class="hljs-variable">$team</span>.Channels = <span class="hljs-built_in">Get-TeamChannel</span> <span class="hljs-literal">-GroupId</span> <span class="hljs-variable">$team</span>.GroupId | <span class="hljs-built_in">Where-Object</span> { <span class="hljs-variable">$_</span>.MembershipType <span class="hljs-operator">-eq</span> <span class="hljs-string">"Private"</span> };

  <span class="hljs-built_in">Write-Host</span> <span class="hljs-variable">$team</span>.Name;
  <span class="hljs-keyword">foreach</span> (<span class="hljs-variable">$channel</span> <span class="hljs-keyword">in</span> <span class="hljs-variable">$team</span>.Channels) {
    <span class="hljs-built_in">Write-Host</span> <span class="hljs-string">"--<span class="hljs-variable">$</span>(<span class="hljs-variable">$channel</span>.DisplayName)"</span>;

    <span class="hljs-variable">$members</span> = <span class="hljs-built_in">Get-TeamChannelUser</span> <span class="hljs-literal">-GroupId</span> <span class="hljs-variable">$GroupId</span> <span class="hljs-literal">-DisplayName</span> <span class="hljs-variable">$channel</span>.DisplayName;

    <span class="hljs-keyword">foreach</span> (<span class="hljs-variable">$member</span> <span class="hljs-keyword">in</span> <span class="hljs-variable">$members</span>) {
      <span class="hljs-built_in">Write-Host</span> <span class="hljs-string">"----<span class="hljs-variable">$</span>(<span class="hljs-variable">$member</span>.Name)"</span>;
    };
  };
};
</code></pre>
<p>Now, if we run this updated script, we should see the output:</p>
<pre><code class="lang-powershell">Your first team name here
-<span class="hljs-literal">-Channel</span> <span class="hljs-number">1</span>
---<span class="hljs-literal">-Member</span> <span class="hljs-number">1</span>
---<span class="hljs-literal">-Member</span> <span class="hljs-number">2</span>
...
-<span class="hljs-literal">-Channel</span> <span class="hljs-number">2</span>
---<span class="hljs-literal">-Member</span> <span class="hljs-number">1</span>
---<span class="hljs-literal">-Member</span> <span class="hljs-number">2</span>
...
Your second team name here
...
Your third team name here
...
</code></pre>
<h3 id="heading-writing-to-a-text-file">Writing to a text file</h3>
<p>Our terminal output is getting quite long, so let's send it to a text file instead. This also has the benefit of giving you a file that you can save as a reference of the membership status on a given date and time, in case you need it later.</p>
<p>First, let's create the new file right after we create the list of teams, like so:</p>
<pre><code class="lang-powershell"><span class="hljs-variable">$filePath</span> = <span class="hljs-string">"Teams private channel members.txt"</span>;
<span class="hljs-string">""</span> | <span class="hljs-built_in">Out-File</span> <span class="hljs-literal">-FilePath</span> <span class="hljs-variable">$filePath</span>;
</code></pre>
<p>This line creates a new text file in the same directory as your PowerShell script, containing a blank line.</p>
<p>Now that we have a new text file to write to, we simply need to replace all instances of <code>Write-Host ...</code> with <code>... | Out-File -FilePath $filePath -Append</code>. The <code>-Append</code> flag will ensure that the content being written doesn't replace the existing content in the file.</p>
<p>With those small changes made, our final script looks like this:</p>
<pre><code class="lang-powershell"><span class="hljs-built_in">Connect-MicrosoftTeams</span>;

<span class="hljs-variable">$teams</span> = <span class="hljs-selector-tag">@</span>(
  [<span class="hljs-type">PSCustomObject</span>]<span class="hljs-selector-tag">@</span>{
    Name = <span class="hljs-string">"Your first team name here"</span>
    GroupId = <span class="hljs-string">""</span> <span class="hljs-comment"># Empty for now</span>
    Channels = <span class="hljs-selector-tag">@</span>() <span class="hljs-comment"># Also empty for now</span>
  },
  [<span class="hljs-type">PSCustomObject</span>]<span class="hljs-selector-tag">@</span>{
    Name = <span class="hljs-string">"Your second team name here"</span>
    GroupId = <span class="hljs-string">""</span> <span class="hljs-comment"># Empty for now</span>
    Channels = <span class="hljs-selector-tag">@</span>() <span class="hljs-comment"># Also empty for now</span>
  },
  [<span class="hljs-type">PSCustomObject</span>]<span class="hljs-selector-tag">@</span>{
    Name = <span class="hljs-string">"Your third team name here"</span>
    GroupId = <span class="hljs-string">""</span> <span class="hljs-comment"># Empty for now</span>
    Channels = <span class="hljs-selector-tag">@</span>() <span class="hljs-comment"># Also empty for now</span>
  }
);

<span class="hljs-variable">$filePath</span> = <span class="hljs-string">"Teams private channel members.txt"</span>;
<span class="hljs-string">""</span> | <span class="hljs-built_in">Out-File</span> <span class="hljs-literal">-FilePath</span> <span class="hljs-variable">$filePath</span>;

<span class="hljs-keyword">foreach</span> (<span class="hljs-variable">$team</span> <span class="hljs-keyword">in</span> <span class="hljs-variable">$teams</span>) {
  <span class="hljs-variable">$team</span>.GroupId = (<span class="hljs-built_in">Get-Team</span> <span class="hljs-literal">-DisplayName</span> <span class="hljs-variable">$team</span>.Name).GroupId;
  <span class="hljs-variable">$team</span>.Channels = <span class="hljs-built_in">Get-TeamChannel</span> <span class="hljs-literal">-GroupId</span> <span class="hljs-variable">$team</span>.GroupId | <span class="hljs-built_in">Where-Object</span> { <span class="hljs-variable">$_</span>.MembershipType <span class="hljs-operator">-eq</span> <span class="hljs-string">"Private"</span> };

  <span class="hljs-variable">$team</span>.Name | <span class="hljs-built_in">Out-File</span> <span class="hljs-literal">-FilePath</span> <span class="hljs-variable">$filePath</span> <span class="hljs-literal">-Append</span>;
  <span class="hljs-keyword">foreach</span> (<span class="hljs-variable">$channel</span> <span class="hljs-keyword">in</span> <span class="hljs-variable">$team</span>.Channels) {
    <span class="hljs-string">"--<span class="hljs-variable">$</span>(<span class="hljs-variable">$channel</span>.DisplayName)"</span> | <span class="hljs-built_in">Out-File</span> <span class="hljs-literal">-FilePath</span> <span class="hljs-variable">$filePath</span> <span class="hljs-literal">-Append</span>;

    <span class="hljs-variable">$members</span> = <span class="hljs-built_in">Get-TeamChannelUser</span> <span class="hljs-literal">-GroupId</span> <span class="hljs-variable">$GroupId</span> <span class="hljs-literal">-DisplayName</span> <span class="hljs-variable">$channel</span>.DisplayName;

    <span class="hljs-keyword">foreach</span> (<span class="hljs-variable">$member</span> <span class="hljs-keyword">in</span> <span class="hljs-variable">$members</span>) {
      <span class="hljs-string">"----<span class="hljs-variable">$</span>(<span class="hljs-variable">$member</span>.Name)"</span> | <span class="hljs-built_in">Out-File</span> <span class="hljs-literal">-FilePath</span> <span class="hljs-variable">$filePath</span> <span class="hljs-literal">-Append</span>;
    };
  };
};
</code></pre>
<p>Now, when we run this script, a text file named "Teams private channel members" will be created and will contain the same output that we were previously writing to the terminal.</p>
<p>Great work!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we discussed why you might want to view the private channels and members of a team that you own, even if you're not a member of those channels. We also wrote a PowerShell script that:</p>
<ul>
<li><p>Loops through a list of teams that you provide</p>
</li>
<li><p>Gets a list of private channels for each team</p>
</li>
<li><p>Gets a list of members for each private channel</p>
</li>
<li><p>Writes the information to a text file</p>
</li>
</ul>
<p>Thanks for reading and, if you found this article useful, please consider sharing it across your network so others may be able to benefit from this information.</p>
<p>Take care!</p>
]]></content:encoded></item><item><title><![CDATA[What is "Dev-ish"?]]></title><description><![CDATA[I write code, but I am not employed as a "Software Engineer", "Web Developer" or any other role that is primarily focused on developing software. My…]]></description><link>https://richardcarrigan.hashnode.dev/what-is-dev-ish</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/what-is-dev-ish</guid><category><![CDATA[Welcome]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Tue, 16 May 2023 17:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/376KN_ISplE/upload/28201c7f659099d0f7f77fc7f2ea83e5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I write code, but I am not employed as a "Software Engineer", "Web Developer" or any other role that is primarily focused on developing software. My current role is "Technical Program Manager Consultant", and before that I was a "Logistics/Operations Manager" but I was also responsible for managing the company's multiple web assets. While this may seem odd to some, I think it's actually more common than we think, especially in small to medium-sized businesses (SMBs) outside of the tech industry, as they still need technical work done (building/maintaining websites, business process automation, etc.) but may not have the budget to afford an agency or would prefer to keep the work in-house. However, despite this most likely common practice, there seems to be a severe lack of representation across the industry. Instead, what we see are tutorials written by full-time software engineers and developers, for full-time software engineers and developers. The reason I feel this is an issue, and why I created Dev-ish, is that people that only work on code for a portion of their work fundametally approach it in a different way.</p>
<h2 id="heading-example">Example</h2>
<h3 id="heading-scenario">Scenario</h3>
<p>Create a process for sending an approval request and then perform some actions after that approval is granted or denied.</p>
<h3 id="heading-software-engineer-response">Software Engineer response</h3>
<p>They would most likely choose their preferred coding language and start building some type of service or application. Surely they would spend time determining the best language and/or tech stack to use for the job, based on many factors such as team familiarity, performance requirements, etc., but they would absolutely end up choosing to write code.</p>
<h3 id="heading-part-time-coder-response">"Part-time coder" response</h3>
<p>They would probably consider what tools are available to them, including but not limited to code, and choose the tool that is easiest to implement and maintain, which would very likely be a low/no-code tool such as Power Automate these days. There may be other factors that preclude low/no-code tools as an option, so they might choose to write code, but it would be considered more as a last resort, rather than the default.</p>
<h2 id="heading-the-purpose">The Purpose</h2>
<p>To be clear, the purpose of this article is not to advocate for everyone to use low/no-code tools and stop writing code. The point is that there are many people that write code as <em>part</em> of their job, but they also have many other tasks that have nothing to do with code, so they need different advice and tools: <strong>this is what "Dev-ish" is all about</strong>. My goal is to provide information and guidance from the perspective of someone that writes code when necessary, but also spends a large portion of my time <em>not</em> writing code, so that other prople like me can provide better results to our stakeholders, plan our work more efficiently, and generally succeed in both worlds without feeling uncomfortable in either.</p>
<h2 id="heading-the-ask">The Ask</h2>
<p>If my description of a "part-time coder" sounds like you or one of your colleagues, I encourage you to subscribe to this newsletter. I post new articles every Tuesday (because I know how busy Mondays already are) on various topics such as:</p>
<ul>
<li><p>Cloud Administration and Development</p>
</li>
<li><p>DevOps</p>
</li>
<li><p>Microsoft Power Platform tools and concepts</p>
</li>
<li><p>Coding (JavaScript, TypeScript, React, GraphQL, and C#/.NET primarily)</p>
</li>
<li><p>Accessibility, Privacy, and Security</p>
</li>
<li><p>Soft skills</p>
</li>
<li><p>Responsible AI</p>
</li>
</ul>
<p>My hope is that we can grow a community of working professionals that can share knowledge, advice, and encouragement for the betterment of us all. "A rising tide lifts all boats".</p>
]]></content:encoded></item><item><title><![CDATA[How to deploy a Power Pages website using Azure DevOps Pipelines]]></title><description><![CDATA[After you've been working with Power Pages for some time, it will become obvious that it can be difficult to present website changes to stakeholders for…]]></description><link>https://richardcarrigan.hashnode.dev/how-to-deploy-a-power-pages-website-using-azure-devops-pipelines</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/how-to-deploy-a-power-pages-website-using-azure-devops-pipelines</guid><category><![CDATA[azure-devops]]></category><category><![CDATA[ci-cd]]></category><category><![CDATA[PowerPlatform]]></category><category><![CDATA[PowerPages]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Tue, 09 May 2023 17:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/O1jUvZX9DOA/upload/61bebff30dd4f5413f5d7040f8388174.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>After you've been working with Power Pages for some time, it will become obvious that it can be difficult to present website changes to stakeholders for approval without those same changes being immediately visible to your website visitors. To solve this problem, you'll want to have at least 3 separate Power Platform environments, with a copy of the website in each environment. These 3 environments will become your <strong>Development (Dev)</strong>, <strong>Test</strong>, and <strong>Production (Prod)</strong> environments. Later on in this article, I'll guide you through creating and deploying your website to each of these environments, but for now, I want to give you a high-level overview of what a typical development workflow will look like with this configuration.</p>
<ol>
<li><p>Requested changes are worked on in the <strong>Dev</strong> environment.</p>
</li>
<li><p>Once the developer is satisfied with the changes, they are then deployed to the <strong>Test</strong> environment.</p>
</li>
<li><p>In the <strong>Test</strong> environment, stakeholders review the changes and provide approval.</p>
</li>
<li><p>Once changes are approved, changes are then deployed to the <strong>Prod</strong> environment.</p>
</li>
</ol>
<p>This workflow will allow you to simultaneously work on new features for the website while awaiting approval on previously completed features, all while ensuring that users only see the features that have been fully reviewed and approved.</p>
<p>This multi-environment configuration is formally referred to as <strong>Application Lifecycle Management</strong>, or ALM for short. For more information on Power Pages ALM as a whole, refer to <a target="_blank" href="https://learn.microsoft.com/en-us/power-pages/configure/portals-alm">Overview of Power Pages ALM</a>.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before we can get started, you'll need to have at least 2 Power Platform environments created, with one of them (your <strong>Dev</strong> environment) containing your website content. You will also need to have an Azure DevOps project created, with a repo containing the website content downloaded from your <strong>Dev</strong> environment. If you don't have these set up yet, or if you want to start with the same setup as mine to make following along easier, you can follow my guides on <a target="_blank" href="https://hashnode.com/post/clfsi7zdq04idx0nvb1p805kf">How to create a Power Platform test environment</a>, <a target="_blank" href="https://hashnode.com/post/clg2iaxrl01kikmnvc3jl3l9m">How to create a new Power Pages website</a>, and <a target="_blank" href="https://hashnode.com/post/clgcidwhx05kxfnnvfs87c4o7">Using source control with Azure DevOps and Power Pages websites</a> to do so, and then come back here when you're done.</p>
<h2 id="heading-prepare-target-environments">Prepare target environments</h2>
<p>You now have 3 Power Platform environments and a Power Pages website stored in your <strong>Dev</strong> environment and an Azure DevOps project repo. Logically, you might think that simply uploading your website content to the target environment will automatically create and configure a new website if one doesn't already exist. Unfortunately, this isn't the case, so you'll need to go through a specific one-time process of "preparing" each of your target Power Platform environments so that they are ready to receive the website content.</p>
<h3 id="heading-create-a-new-website">Create a new website</h3>
<p>Follow the same steps that you took in your <strong>Dev</strong> environment (i.e. <a target="_blank" href="https://hashnode.com/post/clg2iaxrl01kikmnvc3jl3l9m">How to create a new Power Pages website</a>) to create a new website in each of your target environments (i.e. <strong>Dev</strong> and <strong>Test</strong>). Make sure to choose the same template, such as "Blank app". Otherwise, the website content from your <strong>Dev</strong> environment won't be compatible with your <strong>Test</strong> and/or <strong>Prod</strong> websites.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683578203600/9edc27f0-77cd-4469-88c0-39b2815d2c05.png" alt="New app creation screen" class="image--center mx-auto" /></p>
<p>Once you select the right template, I recommend giving the website an environment-specific name, such as "[website name] Test Site" for your <strong>Test</strong> environment, and "[website name]" for the <strong>Prod</strong> environment, as the name will be visible to your users.</p>
<p>Finish configuring your site similarly to the one in your <strong>Dev</strong> environment and hit the final <strong>Create</strong>. Repeat these steps for each of your target environments. Once the site has been fully created in each of the target environments, we're ready to proceed to the next step: deleting the site we just created.</p>
<p>Wait...<em>what?!</em></p>
<h3 id="heading-deleting-the-website-record-and-portal-app">Deleting the website record and portal app</h3>
<p>That's right. In order for the website content from our <strong>Dev</strong> environment to successfully be rendered by our target environments, we need to remove the delete a couple of pieces of configuration that were automatically created.</p>
<p>First, we need to delete the website <strong>record</strong>.</p>
<p>To delete the website record:</p>
<ol>
<li><p>Go to <a target="_blank" href="https://make.powerapps.com">make.powerapps.com</a> and make sure the right environment is selected in the top-right corner.</p>
</li>
<li><p>Select <strong>Apps</strong> from the side menu.</p>
</li>
<li><p>Select <strong>Portal Management</strong> from the apps list.</p>
</li>
<li><p>Select the checkbox to the left of the newly-created website record, usually named "[Website name] - [address]"</p>
</li>
<li><p>Choose <strong>Delete</strong> from the top menu.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683582778907/1a017fde-b4ce-4485-9a50-ca364cd1330d.png" alt="Website record selected with Delete option highlighted" class="image--center mx-auto" /></p>
<ol>
<li>Confirm deletion.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683582871371/489f5d0b-f86e-423d-b915-59ce7c0efe1c.png" alt="Confirm deletion screen" class="image--center mx-auto" /></p>
<p>Next, we need to delete the app associated with the newly-created Power Pages website.</p>
<p>To delete the app for the newly-created website:</p>
<ol>
<li><p>Go to <a target="_blank" href="https://make.powerapps.com">make.powerapps.com</a> and make sure the right environment is selected in the top-right corner.</p>
</li>
<li><p>Select <strong>Apps</strong> from the side menu.</p>
</li>
<li><p>Select the checkbox to the left of the newly-created website's app, which should have the same name as the website. Be sure <strong>NOT</strong> to select the <strong>Portal Management</strong> app.</p>
</li>
<li><p>Choose <strong>Delete</strong> from the top menu.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683584618802/4c175a31-93be-4d65-a65a-3688800cc48d.png" alt="Website app selected with Delete option highlighted" class="image--center mx-auto" /></p>
<ol>
<li>Confirm deletion.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683584726410/5852bb0f-16db-4c3d-83ee-28e503b60491.png" alt="Confirm deletion screen" class="image--center mx-auto" /></p>
<p>With the portal app and website record deleted, we're now ready to upload the website contents from our <strong>Dev</strong> environment. For this initial setup, we're going to upload the contents manually. Don't worry though, this is a one-time process; after this, we're going to configure an Azure DevOps pipeline to deploy the website content automatically.</p>
<h3 id="heading-manually-upload-website-content">Manually upload website content</h3>
<p>Now, in the terminal window of your local machine, navigate to the local copy of your project repo, like so:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> ~/Documents/powerplatformdemos
</code></pre>
<p>Next, we need to authenticate with the target environment. To do this, you'll first need the URL for your target environment, which can be found by going to: <a target="_blank" href="https://admin.powerplatform.microsoft.com/environments">Power Platform Admin Center &gt; Environments</a>, choosing the target environment, and then copying the <strong>Environment URL</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683587019953/b7c34655-da0d-435f-93f1-fe0882e98482.png" alt="Power Platform Admin Center environments list with Environment URL circled" class="image--center mx-auto" /></p>
<p>With that copied, go back to your terminal and run the following command:</p>
<pre><code class="lang-bash">pac auth create -u [Environment URL] -n [optional environment name]
</code></pre>
<p>This command will prompt you to authenticate into the target environment and, upon successful authentication, will create an authentication profile on your machine that can be used for future commands.</p>
<p>Now, we can run the following command to upload the website content from our <strong>Dev</strong> environment into our target environment:</p>
<pre><code class="lang-bash">pac paportal upload --path ./websites/[website-folder-name]
</code></pre>
<p>Once this command finishes running, we're ready for the last step of our one-time setup: recreating the website in each target environment.</p>
<h3 id="heading-recreating-the-website">Recreating the website</h3>
<p>Just like before, follow the steps to <a target="_blank" href="https://blog.richardcarrigan.dev/how-to-deploy-a-power-pages-website-using-azure-devops-pipelines#heading-create-a-new-website">Create a new website</a>. However, this time, make sure to select the checkbox <strong>Use data from existing website record</strong> and then choose the website record that came from your <strong>Dev</strong> environment.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683588512144/231f66ce-7afb-4720-8761-ff7a5efff3bb.png" alt="Power Pages website creation screen with &quot;Use data from existing website record&quot; and selected record circled." class="image--center mx-auto" /></p>
<p>Great! We're now <em>finally</em> ready to set up our Azure DevOps pipeline to deploy future versions of our site.</p>
<h2 id="heading-create-a-new-azure-devops-pipeline">Create a new Azure DevOps pipeline</h2>
<p>While it is possible to use the Power Platform CLI to upload our website content to our <strong>Test</strong> and <strong>Prod</strong> environments, it's not the best use of our time. Furthermore, if we went that route, we would need to document the entire process and <em>hope</em> that all of the developers on our team follow the same process. Instead, let's set up an Azure DevOps pipeline so that our website content automatically gets uploaded to the <strong>Test</strong> and <strong>Prod</strong> environments.</p>
<blockquote>
<p>Note: this pipeline requires the Power Platform Build Tools to be added to Azure DevOps, as well as a service connection to your target environment. See <a target="_blank" href="https://learn.microsoft.com/en-us/power-platform/alm/devops-build-tools#get-microsoft-power-platform-build-tools">Get Microsoft Power Platform Build Tools</a> for instructions on how to configure both.</p>
</blockquote>
<p>Within the <strong>Pipelines</strong> section of your Azure DevOps project, let's go to <strong>Pipelines</strong> and select <strong>Create Pipeline</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682370868144/2ece99e9-26b9-4d1b-bb31-3c5b17be81d0.png" alt="Screenshot of Azure DevOps Pipelines section with &quot;Create Pipeline&quot; button." class="image--center mx-auto" /></p>
<p>From here, choose the following options:</p>
<ul>
<li><p>Azure Repos Git</p>
</li>
<li><p>Repo name (i.e. <code>powerplatformdemos</code>)</p>
</li>
<li><p>Starter pipeline</p>
</li>
</ul>
<p>This will create a new <code>azure-pipelines.yml</code> file at the root of your project repo. With this file open in Azure DevOps, replace the default code with the following:</p>
<pre><code class="lang-yaml"><span class="hljs-comment"># only run pipeline for changes within the 'websites' folder, and only on the 'main' branch of the repo.</span>
<span class="hljs-attr">trigger:</span>
  <span class="hljs-attr">branches:</span>
    <span class="hljs-attr">include:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">main</span>
  <span class="hljs-attr">paths:</span>
    <span class="hljs-attr">include:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">websites/*</span>

<span class="hljs-comment"># use a Windows VM, as it is necessary for the Power Platform Tools</span>
<span class="hljs-attr">pool:</span>
  <span class="hljs-attr">vmImage:</span> <span class="hljs-string">windows-latest</span>

<span class="hljs-attr">steps:</span>
  <span class="hljs-comment"># checkout the repo</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">checkout:</span> <span class="hljs-string">self</span>

  <span class="hljs-comment"># install the Power Platform tools (required before running Power Platform tasks)</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformToolInstaller@2</span>
    <span class="hljs-attr">inputs:</span>
      <span class="hljs-attr">DefaultVersion:</span> <span class="hljs-literal">true</span>

  <span class="hljs-comment"># upload the website content to the test environment</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformUploadPaportal@2</span>
    <span class="hljs-attr">inputs:</span>
      <span class="hljs-attr">authenticationType:</span> <span class="hljs-string">'PowerPlatformSPN'</span>
      <span class="hljs-attr">PowerPlatformSPN:</span> [<span class="hljs-string">test-env-service-connection</span>]
      <span class="hljs-attr">UploadPath:</span> <span class="hljs-string">'./websites/[website-folder-name]'</span>

  <span class="hljs-comment"># upload the website content to the prod environment</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformUploadPaportal@2</span>
    <span class="hljs-attr">inputs:</span>
      <span class="hljs-attr">authenticationType:</span> <span class="hljs-string">'PowerPlatformSPN'</span>
      <span class="hljs-attr">PowerPlatformSPN:</span> [<span class="hljs-string">prod-env-service-connection</span>]
      <span class="hljs-attr">UploadPath:</span> <span class="hljs-string">'./websites/[website-folder-name]'</span>
</code></pre>
<p>Make sure to replace <code>[test-env-service-connection]</code>, <code>[prod-env-service-connection]</code>, and <code>[website-folder-name]</code> with their respective values from your unique configuration.</p>
<p>With our pipeline code added, let's <strong>Save and run</strong>. If you have branch security enabled, you may need to <strong>Create a new branch for this commit</strong> and then submit a pull request (PR). Otherwise, we can <strong>Commit directly to the main branch</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682372614843/b08df38f-8255-436d-a045-7eef670fb38d.png" alt="Azure DevOps pipeline with save and run flyout menu open." class="image--center mx-auto" /></p>
<p>If this is a new pipeline, you'll also need to grant your pipeline access to the service connections.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682372747005/3aa8159a-7567-46ec-942f-6e41dab67501.png" alt="Permission review menu for Azure DevOps pipeline." class="image--center mx-auto" /></p>
<p>Once you've granted access, your pipeline will now run, deploying any website changes from your <strong>Dev</strong> environment to your <strong>Test</strong> and <strong>Prod</strong> environments.</p>
<h2 id="heading-conclusion-next-steps">Conclusion - Next steps</h2>
<p>Great job! You've now configured a true CI/CD pipeline for deploying your Power Pages website content. From here, there are several improvements you'll want to make, such as:</p>
<ul>
<li><p>Adding UI tests to ensure that deployments don't cause breaking changes.</p>
</li>
<li><p>Protect secrets using <code>.gitignore</code> and Azure DevOps secure files.</p>
</li>
<li><p>Customize deployments for each environment through the use of deployment profiles.</p>
</li>
</ul>
<p>However, this is a <strong>HUGE</strong> improvement over just a single environment for your website, or even over manually uploading content from one environment to another.</p>
<p>Thanks for reading and, if you found this article useful, please consider sharing it across your network so others may be able to benefit from this information.</p>
<p>Take care!</p>
]]></content:encoded></item><item><title><![CDATA[Write a custom Dataverse plugin with C# and VS Code]]></title><description><![CDATA[Microsoft Dataverse plugins is a feature of the Power Platform that allows you to add custom event handlers, defined in C# code, that are triggered when…]]></description><link>https://richardcarrigan.hashnode.dev/write-a-custom-dataverse-plugin-with-csharp-and-vs-code</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/write-a-custom-dataverse-plugin-with-csharp-and-vs-code</guid><category><![CDATA[C#]]></category><category><![CDATA[.NET]]></category><category><![CDATA[Dataverse]]></category><category><![CDATA[PowerPlatform]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Tue, 02 May 2023 17:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/EaB4Ml7C7fE/upload/62454bbfe3ea67a184e255ba4e2fe387.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Microsoft Dataverse plugins is a feature of the Power Platform that allows you to add custom event handlers, defined in C# code, that are triggered when specific events occur within your business processes. There are other, no-code ways of handling events in Power Platform, such as Power Automate Flows and custom workflows, which should be explored first. However, if those options don't quite fit the business requirements, then writing a Dataverse plugin is a great option for extending the functionality of the Power Platform.</p>
<blockquote>
<p>Note: This tutorial is based largely on the "<a target="_blank" href="https://learn.microsoft.com/en-us/power-apps/developer/data-platform/tutorial-write-plug-in">Write and register a plug-in</a>" tutorial outlined in the <a target="_blank" href="https://learn.microsoft.com/en-us/power-apps/developer/data-platform/">Microsoft Dataverse developer guide</a> but has been adapted for Visual Studio Code.</p>
</blockquote>
<p>By the end of this tutorial, you will be able to create a new plugin from scratch, add event-driven custom business logic, and deploy it to your Power Platform environment.</p>
<h2 id="heading-get-the-tools">Get the tools</h2>
<p>Before we can create our first plugin, we need to make sure we have all the necessary tools, which are:</p>
<ul>
<li><p><a target="_blank" href="https://code.visualstudio.com/download">Visual Studio Code</a></p>
</li>
<li><p><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=microsoft-IsvExpTools.powerplatform-vscode">Power Platform Tools extension</a></p>
</li>
<li><p><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp">C# extension</a></p>
</li>
</ul>
<p>In addition to these tools, you'll also need to have a Power Platform environment as well as a model-driven app that includes the account and task tables. To create both of these, follow these tutorials:</p>
<ul>
<li><p><a target="_blank" href="https://blog.richardcarrigan.dev/how-to-create-a-power-platform-test-environment">How to create a Power Platform test environment</a></p>
</li>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/power-apps/maker/model-driven-apps/build-first-model-driven-app">Build your first model-driven app from scratch</a></p>
</li>
</ul>
<p>Once you have all of these tools installed and have an environment to deploy your plugin to, you're ready to get started.</p>
<h2 id="heading-create-the-plugin">Create the plugin</h2>
<p>Normally in Visual Studio, creating a new Dataverse plugin would involve the following steps:</p>
<ol>
<li><p>Create a new C# class library project, with an associated solution.</p>
</li>
<li><p>Add the <code>Microsoft.CrmSdk.CoreAssemblies</code> Nuget package.</p>
</li>
<li><p>Sign the assembly (creates the necessary .snk file).</p>
</li>
</ol>
<p>To perform these same steps in VS Code, the process is even more complicated, as you would have to install another tool to perform the assembly signing, as VS Code doesn't have this feature built-in as Visual Studio does.</p>
<p>Fortunately, since we are using the Power Platform Tools extensions for VS Code, we can simply open our integrated terminal (Ctrl/Cmd + ~) from within VS code and run the following commands and it will take care of everything:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Navigate to documents folder - change this to wherever you want the project folder</span>
<span class="hljs-built_in">cd</span> ~/Documents

<span class="hljs-comment"># Create the project folder to store the plugin code files</span>
mkdir myFirstPlugin

<span class="hljs-comment"># Navigate into the project folder</span>
<span class="hljs-built_in">cd</span> myFirstPlugin

<span class="hljs-comment"># Initialize a new plugin</span>
pac plugin init
<span class="hljs-comment"># Output: "Dataverse plugin class library with name 'myFirstPlugin' created successfully in current directory."</span>

<span class="hljs-comment"># Reload VS Code with the newly-created project folder open</span>
code myFirstPlugin -r
</code></pre>
<p>Running the <code>pac plugin init</code> command will create the following resources:</p>
<ul>
<li><p>A new project with the same name as the project folder (e.g. <code>myFirstPlugin.csproj</code>).</p>
</li>
<li><p><code>PluginBase.cs</code> file containing necessary boilerplate plugin code.</p>
</li>
<li><p><code>Plugin1.cs</code> file with minimal "best practices" configuration, ready for you to add your custom business logic.</p>
</li>
<li><p><code>.snk</code> file with the same name as the project folder, configured so that your plugin is recognized as being signed, which is required by Power Platform for deployment into an environment.</p>
</li>
<li><p>A <code>.vscode</code> folder and a <code>.gitignore</code> file with a default configuration, to help make plugin development easier and more consistent.</p>
</li>
</ul>
<h2 id="heading-add-custom-business-logic">Add custom business logic</h2>
<p>Now that we've created our first plugin, let's add the business logic so that it actually <em>does</em> something!</p>
<p>Let's rename the <code>Plugin1.cs</code> file (select the file name and press F2) to <code>FollowupPlugin.cs</code>. Now, within the <code>FollowupPlugin.cs</code> file, replace the existing code with this:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Microsoft.Xrm.Sdk;
<span class="hljs-keyword">using</span> System;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">myFirstPlugin</span>
{
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> Plugin development guide: https://docs.microsoft.com/powerapps/developer/common-data-service/plug-ins</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> Best practices and guidance: https://docs.microsoft.com/powerapps/developer/common-data-service/best-practices/business-logic/</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">FollowupPlugin</span> : <span class="hljs-title">PluginBase</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">FollowupPlugin</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> unsecureConfiguration, <span class="hljs-keyword">string</span> secureConfiguration</span>)
            : <span class="hljs-title">base</span>(<span class="hljs-params"><span class="hljs-keyword">typeof</span>(FollowupPlugin</span>))</span>
        {
            <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> Implement your custom configuration handling</span>
            <span class="hljs-comment">// https://docs.microsoft.com/powerapps/developer/common-data-service/register-plug-in#set-configuration-data</span>
        }

        <span class="hljs-comment">// Entry point for custom business logic execution</span>
        <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">ExecuteDataversePlugin</span>(<span class="hljs-params">ILocalPluginContext localPluginContext</span>)</span>
        {
            <span class="hljs-keyword">if</span> (localPluginContext == <span class="hljs-literal">null</span>)
            {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentNullException(<span class="hljs-keyword">nameof</span>(localPluginContext));
            }

            <span class="hljs-keyword">var</span> context = localPluginContext.PluginExecutionContext;

            <span class="hljs-comment">// Create a task activity to follow up with the account customer in 7 days.</span>
            Entity followup = <span class="hljs-keyword">new</span> Entity(<span class="hljs-string">"task"</span>);

            followup[<span class="hljs-string">"subject"</span>] = <span class="hljs-string">"Send e-mail to the new customer."</span>;
            followup[<span class="hljs-string">"description"</span>] =
                <span class="hljs-string">"Follow up with the customer. Check if there are any new issues that need resolution."</span>;
            followup[<span class="hljs-string">"scheduledstart"</span>] = DateTime.Now.AddDays(<span class="hljs-number">7</span>);
            followup[<span class="hljs-string">"scheduledend"</span>] = DateTime.Now.AddDays(<span class="hljs-number">7</span>);
            followup[<span class="hljs-string">"category"</span>] = context.PrimaryEntityName;

            <span class="hljs-comment">// Refer to the account in the task activity.</span>
            <span class="hljs-keyword">if</span> (context.OutputParameters.Contains(<span class="hljs-string">"id"</span>))
            {
                Guid regardingobjectid = <span class="hljs-keyword">new</span> Guid(context.OutputParameters[<span class="hljs-string">"id"</span>].ToString());
                <span class="hljs-keyword">string</span> regardingobjectidType = <span class="hljs-string">"account"</span>;

                followup[<span class="hljs-string">"regardingobjectid"</span>] = <span class="hljs-keyword">new</span> EntityReference(
                    regardingobjectidType,
                    regardingobjectid
                );
            }

            <span class="hljs-comment">// Create the task in Microsoft Dynamics CRM.</span>
            localPluginContext.PluginUserService.Create(followup);
        }
    }
}
</code></pre>
<p>This code will send an e-mail reminder to the creator of the account 7 days after creation, reminding them to follow up with the customer.</p>
<p>Before we prepare to deploy this plugin, let's make sure it builds properly. To do this, run <code>dotnet build</code> from the integrated terminal and make sure there are no errors.</p>
<h2 id="heading-register-the-plugin-using-plugin-registration-tool">Register the plugin using Plugin Registration Tool</h2>
<p>With plugins, instead of "deploying" them, you "register" them with the environment. To do this, we use a tool that comes with the Power Platform Tools extension for VS Code, called the Plugin Registration Tool, or PRT for short.</p>
<p>With your project still open in VS Code, open your integrated terminal and run the following command to open the Plugin Registration Tool interface:</p>
<pre><code class="lang-bash">pac tool prt
</code></pre>
<p>Once you run this command, the tool should open to a blank screen, like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682978198234/ed53e045-04fe-4d3d-9153-1514c88fff01.png" alt="Screenshot of the Plugin Registration Tool window (blank), with VS Code in the background." class="image--center mx-auto" /></p>
<p>Once this window opens, select <strong>+ CREATE NEW CONNECTION</strong>. This will prompt you to log in. From here, choose <strong>Office 365</strong>, check the box for <strong>Display list of available organizations</strong>, and then hit <strong>Login</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682978420122/b8ef6f6b-5568-4134-ad74-0814c980f9ee.png" alt="Plugin Registration Tool Login window with Office 365 and &quot;Display list of available organizations&quot; selected." class="image--center mx-auto" /></p>
<p>Once you've successfully authenticated, you should see a list of the available organizations for your account, like so:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682978540549/f4349947-1982-4e4f-af99-f1b8272edd73.png" alt="List of available organizations" class="image--center mx-auto" /></p>
<p>Select the Power Platform environment that you want to register this plugin with and then hit <strong>Login</strong> again. This process can take a bit, but once it's done, you should see a list of all registered plugins.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682978631595/472f05e2-ffad-4f34-9efa-fede6c353230.png" alt="List of registered plugins" class="image--center mx-auto" /></p>
<p>To register your newly-created plugin, select the dropdown arrow next to <strong>Register</strong> and choose <strong>Register new assembly</strong>. From here, browse and select the <code>.dll</code> file for your plugin (e.g. <code>~/Documents/myFirstPlugin/bin/Debug/net462/myFirstPlugin.dll</code>), leave the defaults selected, and hit <strong>Register Selected Plugins</strong>. If you did this correctly, you should see a message similar to the one below, which states "1 Assembly Registered" and "1 Plugin(s) Registered".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682979128302/f45f50cb-359c-4213-9b0b-a4bc6cdc055f.png" alt="Plugin registration result message" class="image--center mx-auto" /></p>
<h2 id="heading-connect-plugin-to-event">Connect plugin to event</h2>
<p>Now that we've registered our custom plugin with the Power Platform environment, you might think we're done. However, if we stopped here, the event would never be triggered, as it's not connected to a specific event. To do that, we need to "Register a new step". Still within the Plugin Registration Tool, right-click on your plugin (e.g. "(Assembly) myFirstPlugin") and select <strong>Register New Step</strong>. You can also do this by selecting the plugin and then choosing <strong>Register New Step</strong> from the <strong>Register</strong> dropdown.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682979466001/ded06d50-5a58-424c-a329-b8fb421e086d.png" alt="Plugin Registration Tool with &quot;Register New Step&quot; option circled in red." class="image--center mx-auto" /></p>
<p>In the <strong>Register New Step</strong> form, the <strong>Message</strong> will be "Create", the <strong>Primary Entity</strong> should be "account", the <strong>Event Pipeline Stage of Execution</strong> should be "PostOperation", and the <strong>Execution Mode</strong> should be "Asynchronous". This means that our custom plugin will be triggered after (PostOperation) a new account has been created, and will run asynchronously. Leave the rest of the fields as their default values and hit <strong>Register New Step</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682979736893/e2cfbc23-f7ba-47c8-9ae2-54e603df8592.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Congratulations! You have now created a custom plugin using Visual Studio Code that sends an email to a user 7 days after they create a new account (contact) record, reminding them to follow up with that contact. If you want to test the new plugin, simply create a new account record and then go to <strong>Related &gt; Activites</strong> (Activities is where any email or phone call records associated with the account are stored).</p>
<p>Now that you know how to create and deploy custom plugins, explore the .NET Organization Service SDK to see all the ways you can interact with your entities: <a target="_blank" href="https://learn.microsoft.com/en-us/power-apps/developer/data-platform/org-service/overview">Use the Organization service - Power Apps | Microsoft Learn</a>.</p>
<p>Thanks for reading and, if you found this article useful, please consider sharing it across your network so others may be able to benefit from this information.</p>
<p>Take care!</p>
]]></content:encoded></item><item><title><![CDATA[Deploy Power Pages secrets with Azure DevOps and deployment profiles]]></title><description><![CDATA[Microsoft provides excellent resources for learning, using, and building on top of its products. Usually, you can search for how to do something within a…]]></description><link>https://richardcarrigan.hashnode.dev/deploy-power-pages-secrets-with-azure-devops-and-deployment-profiles</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/deploy-power-pages-secrets-with-azure-devops-and-deployment-profiles</guid><category><![CDATA[Azure Pipelines]]></category><category><![CDATA[azure-devops]]></category><category><![CDATA[PowerPlatform]]></category><category><![CDATA[PowerPages]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Tue, 25 Apr 2023 17:00:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/uuhD96VBp4k/upload/3447f34b2685b0d8259fd11cfd381168.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Microsoft provides excellent resources for learning, using, and building on top of its products. Usually, you can search for how to do something within a Microsoft product or service and you'll get a handful of Microsoft Learn resources that will walk you step-by-step through the exact configuration needed. Unfortunately, however, these resources can sometimes have gaps that may lead to unexpected results. This is what happened in my case, so I've written this guide as a cautionary tale so that you can avoid the same pitfalls I encountered, while also gaining a deeper understanding of how Power Pages websites are updated when changes are deployed.</p>
<blockquote>
<p>Note: this article builds off of my previous article on <a target="_blank" href="https://blog.richardcarrigan.dev/using-source-control-with-azure-devops-and-power-pages-websites">Using source control with Azure DevOps and Power Pages websites</a>, so you should check that out before continuing with this article if you haven't already.</p>
</blockquote>
<h2 id="heading-secrets-what-secrets">Secrets? What secrets?</h2>
<p>While it may not be immediately apparent when working with a Power Pages website, many of the site settings are sensitive values that should not be checked into source control and should be stored securely, just like your passwords. The common site settings, along with their site setting <code>Name</code>s, that need to be handled carefully are:</p>
<ul>
<li><p>Facebook App Secret (<code>Authentication/OpenAuth/Facebook/AppSecret</code>)</p>
</li>
<li><p>LinkedIn Consumer Secret (<code>Authentication/OpenAuth/LinkedIn/ConsumerSecret</code>)</p>
</li>
<li><p>Microsoft Client Secret (<code>Authentication/OpenAuth/Microsoft/ClientSecret</code>)</p>
</li>
<li><p>Twitter Consumer Secret (<code>Authentication/OpenAuth/Twitter/ConsumerSecret</code>)</p>
</li>
<li><p>Azure Blob Storage Connection String (<code>WebFiles/CloudStorageAccount</code>)</p>
</li>
<li><p>Any other secrets used to access third-party APIs</p>
</li>
</ul>
<p>To view these and all other site settings, go into your <strong>Portal Management</strong> app and select <strong>Site Settings</strong> from the sidebar menu.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682367708662/ef20b076-14f1-4127-80e4-d52762d1806a.png" alt="Screenshot of Site Settings with Microsoft client secret circled." class="image--center mx-auto" /></p>
<h2 id="heading-how-do-these-secrets-get-exposed">How do these secrets get exposed?</h2>
<p>If your website is only being stored within one Power Platform environment, which I would strongly discourage, or if you are manually uploading your website content from one environment to another, then there is little to no risk of these secrets being exposed unless someone gains access to your computer or the Power Platform environment directly. However, if you have configured a DevOps deployment pipeline, or at least source control (i.e. Git), then there is a <code>sitesetting.yml</code> file containing all of these site settings along with their values being checked into your repo right now!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682368496004/2e9c39dc-4e8e-4189-affd-4bd9b7b42bda.png" alt="Power Pages website file structure with sitesetting.yml file circled in red." class="image--center mx-auto" /></p>
<h2 id="heading-wonderful-now-what">Wonderful 😒. Now what?</h2>
<p>Now that you understand what sensitive values are being stored, where they're located in your files, and how they can end up being exposed, let's walk through the process for excluding them from source control while preserving the ability to modify the site settings across multiple Power Platform environments. To accomplish this, we'll need to perform the following steps:</p>
<ol>
<li><p>Exclude site settings from source control</p>
</li>
<li><p>Add <code>sitesetting.yml</code> to the Azure DevOps pipeline</p>
</li>
<li><p>Create a new Azure DevOps pipeline</p>
</li>
<li><p>Add sensitive site settings as pipeline variables</p>
</li>
<li><p>Configure deployment profiles</p>
</li>
</ol>
<h3 id="heading-exclude-site-settings-from-source-control">Exclude site settings from source control</h3>
<p>Within the root of your Power Platform repo (i.e. <code>~/Documents/Power_Platform_DevOps</code> ), open the <code>.gitignore</code> file (or create one if it doesn't already exist) and add the following lines:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Power Pages site settings (wildcard catches multiple websites' settings)</span>
websites/**/sitesetting.yml

<span class="hljs-comment"># While we're here, let's also add the environment-specific manifest file</span>
websites/**/.portalconfig/*-manifest.yml
<span class="hljs-comment"># Reference: https://learn.microsoft.com/power-pages/configure/power-platform-cli#environment-manifest-file-org-url-manifestyml</span>
</code></pre>
<p>With those lines added, save the file and you should see that the <code>sitesetting.yml</code> file (along with the environment-specific manifest file) are now being ignored by Git. At this point, you can now safely check your repo into source control without worrying about exposed secrets. However, this also means that the target environments won't receive any updates to these values, nor will you be able to manage each environment's settings in code. To do this, we'll use Azure DevOps pipeline secure files and variables.</p>
<h3 id="heading-add-sitesettingyml-to-the-azure-devops-pipeline">Add <code>sitesetting.yml</code> to the Azure DevOps pipeline</h3>
<p>It is necessary to still deploy the <code>sitesetting.yml</code> file along with your other Power Pages website content files because otherwise, Power Pages will ignore any site setting changes you try to make. So to do this, we will leverage a feature within Azure DevOps called <strong>secure files</strong>.</p>
<p>Within your Azure DevOps project (i.e. <code>https://dev.azure.com/powerplatformdevops2023/Power_Platform_DevOps</code>), navigate to <strong>Pipelines &gt; Library &gt; Secure files</strong> and select <strong>+ Secure file</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682369979862/f17183fc-3138-4ab0-9058-3a6b048c3023.png" alt="Azure DevOps pipelines library with &quot;+ Secure file&quot; circled in two places." class="image--center mx-auto" /></p>
<p>From here, select and upload the <code>sitesetting.yml</code> file from your local repo.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682370136661/9c763c2f-46cc-4df0-ac13-985ecf509d4f.png" alt="Azure DevOps pipeline library with uploaded sitesetting.yml file circled." class="image--center mx-auto" /></p>
<p>Uploading this file into the pipeline library doesn't automatically add it to your files during deployment, so we'll need to add this as a task in our deployment pipeline later on.</p>
<h3 id="heading-create-a-new-azure-devops-pipeline">Create a new Azure DevOps pipeline</h3>
<p>Now that we have our <code>sitesetting.yml</code> file ready to deploy along with the rest of our website content files, let's create the Azure DevOps deployment pipeline.</p>
<blockquote>
<p>Note: if you don't already have multiple Power Platform environments, you can still follow along by configuring the deployment pipeline to deploy back to your source environment. Since that's where the changes are coming from, there shouldn't be any issue.</p>
</blockquote>
<p>Still within the <strong>Pipelines</strong> section of your Azure DevOps project, let's go to <strong>Pipelines</strong> and select <strong>Create Pipeline</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682370868144/2ece99e9-26b9-4d1b-bb31-3c5b17be81d0.png" alt="Screenshot of Azure DevOps Pipelines section with &quot;Create Pipeline&quot; button." class="image--center mx-auto" /></p>
<p>From here, choose the following options:</p>
<ul>
<li><p>Azure Repos Git</p>
</li>
<li><p>Repo name (i.e. <code>Power_Platform_DevOps</code>)</p>
</li>
<li><p>Starter pipeline</p>
</li>
</ul>
<p>This should create a new <code>azure-pipelines.yml</code> file at the root of your project repo. With this file open in Azure DevOps, replace the default code with the following:</p>
<pre><code class="lang-yaml"><span class="hljs-comment"># only run pipeline for changes within the 'websites' folder, and only on the 'main' branch of the repo.</span>
<span class="hljs-attr">trigger:</span>
  <span class="hljs-attr">branches:</span>
    <span class="hljs-attr">include:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">main</span>
  <span class="hljs-attr">paths:</span>
    <span class="hljs-attr">include:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">websites/*</span>

<span class="hljs-comment"># use a Windows VM, as it is necessary for the Power Platform Tools</span>
<span class="hljs-attr">pool:</span>
  <span class="hljs-attr">vmImage:</span> <span class="hljs-string">windows-latest</span>

<span class="hljs-attr">steps:</span>
  <span class="hljs-comment"># checkout the repo</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">checkout:</span> <span class="hljs-string">self</span>

  <span class="hljs-comment"># install the Power Platform tools (required before running Power Platform tasks)</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformToolInstaller@2</span>
    <span class="hljs-attr">inputs:</span>
      <span class="hljs-attr">DefaultVersion:</span> <span class="hljs-literal">true</span>

  <span class="hljs-comment"># download the secure 'sitesetting.yml' file into the pipeline's local files (disposed of after the run)</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">DownloadSecureFile@1</span>
    <span class="hljs-attr">name:</span> <span class="hljs-string">siteSettings</span>
    <span class="hljs-attr">displayName:</span> <span class="hljs-string">'Download sitesetting.yml, accessible through $(siteSettings.secureFilePath)'</span>
    <span class="hljs-attr">inputs:</span>
      <span class="hljs-attr">secureFile:</span> <span class="hljs-string">'sitesetting.yml'</span>

  <span class="hljs-comment"># copy the downloaded file into it's usual location within the Power Pages website content file structure</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">CopyFiles@2</span>
    <span class="hljs-attr">inputs:</span>
      <span class="hljs-attr">SourceFolder:</span> <span class="hljs-string">'$(Agent.TempDirectory)'</span>
      <span class="hljs-attr">Contents:</span> <span class="hljs-string">sitesetting.yml</span>
      <span class="hljs-attr">TargetFolder:</span> <span class="hljs-string">'$(Build.Repository.LocalPath)/websites/custom-portal'</span>
      <span class="hljs-attr">OverWrite:</span> <span class="hljs-literal">true</span>
      <span class="hljs-attr">flattenFolders:</span> <span class="hljs-literal">true</span>

  <span class="hljs-comment"># upload the website content to the target environment</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformUploadPaportal@2</span>
    <span class="hljs-attr">inputs:</span>
      <span class="hljs-attr">authenticationType:</span> <span class="hljs-string">'PowerPlatformSPN'</span>
      <span class="hljs-attr">PowerPlatformSPN:</span> <span class="hljs-string">'prodsite'</span>
      <span class="hljs-attr">UploadPath:</span> <span class="hljs-string">'./websites/custom-portal'</span>
      <span class="hljs-attr">DeploymentProfile:</span> <span class="hljs-string">'prod'</span>
</code></pre>
<blockquote>
<p>Note: this pipeline requires the Power Platform Build Tools to be added to Azure DevOps, as well as a service connection to your target environment. See <a target="_blank" href="https://learn.microsoft.com/en-us/power-platform/alm/devops-build-tools#get-microsoft-power-platform-build-tools">Get Microsoft Power Platform Build Tools</a> for instructions on how to configure both.</p>
</blockquote>
<p>With our pipeline code added, let's <strong>Save and run</strong>. If you have branch security enabled, you may need to <strong>Create a new branch for this commit</strong> and then submit a pull request (PR). Otherwise, we can <strong>Commit directly to the main branch</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682372614843/b08df38f-8255-436d-a045-7eef670fb38d.png" alt="Azure DevOps pipeline with save and run flyout menu open." class="image--center mx-auto" /></p>
<p>If this is a new pipeline, you'll also need to grant access to the secure file and the service connection to the pipeline.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682372747005/3aa8159a-7567-46ec-942f-6e41dab67501.png" alt="Permission review menu for Azure DevOps pipeline." class="image--center mx-auto" /></p>
<p>Once you've granted access, your pipeline will now run, deploying any website changes from your source environment to your target environment, including any site settings in the <code>sitesetting.yml</code> file. However, with our current setup, we would have to upload a new <code>sitesetting.yml</code> file before every deployment if we need to make any changes to our site settings. Let's fix that in the next couple of steps.</p>
<h3 id="heading-add-sensitive-site-settings-as-pipeline-variables">Add sensitive site settings as pipeline variables</h3>
<p>Now that we have our pipeline set up, let's add some environment-specific variables that we can then use in the next step to adjust our site settings to match each environment's configuration. This is necessary for multiple reasons, such as using a different Microsoft Azure app registration ID and secret, or a different Azure Blob storage account for each environment.</p>
<p>Still within our pipeline, select <strong>Edit</strong> and then select <strong>Variables &gt; New variable</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682373301510/1220b9d2-3448-4c20-8f55-7ef0035fb858.png" alt="Azure DevOps pipeline with Edit button circled." class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682373382351/f9f60157-f00e-4ff8-9e56-aa3b00d1e65c.png" alt="Edit pipeline screen with Variables button circled." class="image--center mx-auto" /></p>
<p>Let's take our Microsoft client ID, which can be copied from the <strong>Site Settings</strong> in the Portal Management app or from within the <code>sitesetting.yml</code> file of our repo, and save it in a variable named "ProdMicrosoftClientId", like so:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682373568090/806223fc-c7d0-43a0-bf25-2a2e3af55164.png" alt="New variable flyout menu with ProdMicrosoftClientId variable info added." class="image--center mx-auto" /></p>
<p>Make sure to choose <strong>Keep this value secret</strong> for added security, as this will prevent anyone else with access to the pipeline from seeing the value. Once the variable has been added, be sure to hit <strong>Save</strong>.</p>
<p>With that saved, let's repeat the process for the Microsoft client secret, which we'll store as "ProdMicrosoftClientSecret", like so:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682373747865/65db1550-e049-48c4-b7c9-b4bbaee22387.png" alt="New variable flyout menu with ProdMicrosoftClientSecret variable info added." class="image--center mx-auto" /></p>
<p>Now we have the variables saved into the pipeline, but in order for us to access them, we need to update our <code>azure-pipelines.yml</code> file and create deployment profiles, which we'll do in the next step.</p>
<h3 id="heading-configure-deployment-profiles">Configure deployment profiles</h3>
<p>To deploy environment-specific changes to our Power Pages website, not just site settings, we need to create <strong>deployment profiles</strong>. To do this, let's go back to our code editor.</p>
<p>Before we make any changes, make sure to run <code>git pull origin [branch-name]</code> to update your local repo with the new <code>azure-pipelines.yml</code> file that we created inside Azure DevOps.</p>
<p>Next, within the directory for our website (i.e. <code>~/Documents/Power_Platform_DevOps/websites/custom-portal</code>), create a new folder named <code>deployment-profiles</code>. It must be named that, as Power Pages will look for that folder once we tell it to use a deployment profile. Within that folder, let's create a file named <code>prod.deployment.yml</code> containing the following code:</p>
<pre><code class="lang-yaml"><span class="hljs-comment"># make sure to replace square brackets with actual values (remove square brackets)</span>
<span class="hljs-attr">adx_sitesetting:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">adx_sitesettingid:</span> [<span class="hljs-string">found</span> <span class="hljs-string">in</span> <span class="hljs-string">'sitesetting.yml'</span>]
    <span class="hljs-attr">adx_value:</span> <span class="hljs-string">${OS.PROD_MICROSOFT_CLIENT_ID}</span>
    <span class="hljs-attr">adx_name:</span> <span class="hljs-string">Authentication/OpenAuth/Microsoft/ClientId</span>
    <span class="hljs-attr">importsequencenumber:</span> <span class="hljs-number">5</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">adx_sitesettingid:</span> [<span class="hljs-string">found</span> <span class="hljs-string">in</span> <span class="hljs-string">'sitesetting.yml'</span>]
    <span class="hljs-attr">adx_value:</span> <span class="hljs-string">${OS.PROD_MICROSOFT_CLIENT_SECRET}</span>
    <span class="hljs-attr">adx_name:</span> <span class="hljs-string">Authentication/OpenAuth/Microsoft/ClientSecret</span>
    <span class="hljs-attr">importsequencenumber:</span> <span class="hljs-number">5</span>
</code></pre>
<blockquote>
<h3 id="heading-why-osprodmicrosoftclientid-instead-of-prodmicrosoftclientid">Why <code>OS.PROD_MICROSOFT_CLIENT_ID</code> instead of <code>ProdMicrosoftClientId</code>?</h3>
<p>Since we are within a Power Pages deployment profile, not the Azure DevOps pipeline file, we are accessing the operating system's environment variables, not the pipeline environment variables. You can read more about the differences <a target="_blank" href="https://learn.microsoft.com/en-us/power-pages/configure/power-platform-cli#use-deployment-profile">here</a> and <a target="_blank" href="https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&amp;tabs=yaml%2Cbatch#environment-variables">here</a>.</p>
</blockquote>
<p>Now that we have our Power Pages deployment profile configured for prod, let's update the <code>PowerPlatformUploadPortal@2</code> task within our <code>azure-pipelines.yml</code> file to include the environment variables, like so:</p>
<pre><code class="lang-yaml">  <span class="hljs-comment"># upload the website content to the target environment</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">PowerPlatformUploadPaportal@2</span>
    <span class="hljs-attr">inputs:</span>
      <span class="hljs-attr">authenticationType:</span> <span class="hljs-string">'PowerPlatformSPN'</span>
      <span class="hljs-attr">PowerPlatformSPN:</span> <span class="hljs-string">'prodsite'</span>
      <span class="hljs-attr">UploadPath:</span> <span class="hljs-string">'./websites/custom-portal'</span>
      <span class="hljs-attr">DeploymentProfile:</span> <span class="hljs-string">'prod'</span>
    <span class="hljs-attr">env:</span>
      <span class="hljs-attr">PROD_MICROSOFT_CLIENT_ID:</span> <span class="hljs-string">$(ProdMicrosoftClientId)</span>
      <span class="hljs-attr">PROD_MICROSOFT_CLIENT_SECRET:</span> <span class="hljs-string">$(ProdMicrosoftClientSecret)</span>
</code></pre>
<p>This change allows us to access the Azure DevOps pipeline environment variables from within our deployment profile.</p>
<p>With that change, we can now run the following commands to send our changes to Azure DevOps, which will automatically kick off the deployment pipeline!</p>
<pre><code class="lang-bash">git add .
git commit -m <span class="hljs-string">"Deploy site settings through deployment profiles"</span>
git push origin main
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Whew, that was a lot of work! The good news, however, is that now you can be confident in the fact that you have a fully-configured deployment pipeline for deploying your Power Pages website to other environments without exposing any secrets, while still maintaining the ability to make environment-specific changes as needed.</p>
<p>Thanks for reading and, if you found this article useful, please consider sharing it across your network so others may be able to benefit from this information.</p>
<p>Take care!</p>
]]></content:encoded></item><item><title><![CDATA[Configuring Microsoft authentication for a Microsoft Power Pages website]]></title><description><![CDATA[When you create a new Power Pages website with a Microsoft Power Platform environment, both Local sign in and Azure Active Directory are enabled, and the…]]></description><link>https://richardcarrigan.hashnode.dev/configuring-microsoft-authentication-for-a-microsoft-power-pages-website</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/configuring-microsoft-authentication-for-a-microsoft-power-pages-website</guid><category><![CDATA[PowerPages]]></category><category><![CDATA[Azure]]></category><category><![CDATA[authentication]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Tue, 18 Apr 2023 17:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/RMIsZlv8qv4/upload/dac00505b7383cb00909543ae3a8bd68.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When you create a new Power Pages website with a Microsoft Power Platform environment, both <strong>Local sign in</strong> and <strong>Azure Active Directory</strong> are enabled, and the rest (Azure Active Directory B2C, Facebook, LinkedIn, Google, Twitter, and Microsoft) are not yet configured. To see this for yourself, follow these steps:</p>
<ol>
<li><p>Go to <a target="_blank" href="http://make.powerapps.com">make.powerapps.com</a> and log in if prompted.</p>
</li>
<li><p>Check the environment listed in the top-right corner and change it if necessary.</p>
</li>
<li><p>Scroll down until you see <strong>Your apps</strong>.</p>
</li>
<li><p>To the right of your Power Pages website, hit the ellipsis (...) and select ✏ <strong>Edit</strong>.</p>
</li>
<li><p>If prompted, choose <strong>Try Power Pages</strong>.</p>
</li>
<li><p>Once the Power Pages editor opens, choose <strong>Set up</strong> from the side menu.</p>
</li>
<li><p>Within the <strong>Set up</strong> menu, choose <strong>Identity providers</strong>.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681486659337/67766a6d-167e-4702-93a6-05993b5708df.png" alt="List of identity providers for example Power Pages website, showing Local sign in and Azure Active Directory enabled, and all others unconfigured." class="image--center mx-auto" /></p>
<p>Similarly, if you view the sign-in page of your Power Pages website at your custom domain name or [your-power-pages-website].powerappsportals.com/signin, you'll see that your login options are local log in (called <strong>Local SignIn</strong>) on the left and Azure Active Directory (called <strong>Azure AD</strong>) on the right.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681488137480/f4aa7252-96d3-44ed-9c6b-6ca351e9cfc4.png" alt="Power Pages website sign-in screen, showing Local SignIn on the left and Azure AD on the right." class="image--center mx-auto" /></p>
<p>In this tutorial, we're going to configure our Power Pages website to use the <strong>Microsoft</strong> authentication method, including exploring the various authentication account type options.</p>
<h3 id="heading-configure-the-microsoft-identity-provider">Configure the Microsoft identity provider</h3>
<p>From the identity providers list, to the right of the <strong>Microsoft</strong> provider, select ⚙ <strong>Configure</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681489592322/8545fd2d-4718-4203-a98a-d0a3835e3456.png" alt="List of identity providers with the Configure option for Microsoft circled." class="image--center mx-auto" /></p>
<p>On the <strong>Configure identity provider</strong> flyout menu, you should leave the defaults selected for <strong>Select login provider</strong> and <strong>Protocol</strong>, but feel free to change the <strong>Provider name</strong> to something that will make sense to users of your website. Then hit <strong>Next</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681489769656/14eea5c7-e046-46fc-ba88-4d77498ddde8.png" alt="Select provider step of Configure identity provider flyout menu." class="image--center mx-auto" /></p>
<p>Next, we need to create a new Microsoft application registration for our website. The application registration is how we tell Microsoft which domain(s) are allowed to use this authentication method, which types of accounts are authorized, and other login process configuration details.</p>
<p>On the <strong>Configure Microsoft settings</strong> step of the <strong>Configure identity provider</strong> flyout menu, hit the link to <strong>Open Microsoft.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681490846030/11b169e7-793e-4056-af44-cd736b88b37e.png" alt="Configure Microsoft settings step of Configure identity provider flyout menu, with Open Microsoft circled." class="image--center mx-auto" /></p>
<p>If prompted, log in using the same account as you used when logging into Power Apps.</p>
<blockquote>
<h3 id="heading-do-you-need-a-new-app-registration">Do you need a new app registration?</h3>
<p>In most cases, despite the instructions from Power Pages, you don't actually need to create a new app registration. This is because Power Pages actually creates a new app registration for you when you create a new website.</p>
</blockquote>
<h3 id="heading-configure-the-microsft-azure-app-registration">Configure the Microsft Azure app registration</h3>
<p>Now that you're looking at the app registrations for your organization, you should see one under <strong>Owned applications</strong> with the name <strong>"Portals-[your power pages website]"</strong>. This is the app registration that was created by default. To confirm this, let's find compare the <strong>Application (client) ID</strong> listed next to it against the one mentioned in Power Pages.</p>
<p>To find the application ID through Power Pages:</p>
<ol>
<li><p>Go back to the previous browser tab with the Power Pages site editor (where you started configuring the Microsoft identity provider) and close the <strong>Configure identity provider</strong> flyout menu.</p>
</li>
<li><p>In the <strong>Set up</strong> menu, go to the <strong>Site details</strong>.</p>
</li>
<li><p>In the <strong>Site details</strong> card, you should see the <strong>Application ID</strong> listed at the bottom-right.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681493998321/ec4ea03e-ae34-4f6d-b186-74900251a471.png" alt="Power Pages site details, with the Application ID circled." class="image--center mx-auto" /></p>
<p>Now that you've found the <strong>Application ID</strong> associated with the Power Pages website, go back to the Azure app registrations tab, and you'll see that this value matches the <strong>Application (client) ID</strong> for the app registration.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681494144063/063bf8b9-7c38-4ca3-9d35-f03a7a8b99b2.png" alt="Azure app registrations list, with the Application (client) ID circled." class="image--center mx-auto" /></p>
<p>Great! We're now confident that this is the app registration associated with our Power Pages website, so let's select it and start making the necessary configuration changes. First, let's go back into the Power Pages website editor tab, go back to <strong>Identity providers</strong>, hit ⚙ <strong>Configure</strong> next to the Microsoft provider again, hit <strong>Next</strong>, and then copy the <strong>Reply URL</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681494658073/1018ffe5-5d0a-478d-bc8d-c7700f90a118.png" alt="Configure Microsoft settings step of Configure identity provider flyout menu, with Reply URL circled." class="image--center mx-auto" /></p>
<p>With the <strong>Reply URL</strong> in hand, go back to the Azure app registrations tab, select the app registration associated with your Power Pages website, and then go to <strong>Authentication</strong>. In the <strong>Authentication</strong> screen, select <strong>Add URI</strong>, paste the <strong>Reply URL</strong> into the space provided, and then hit <strong>Save</strong> at the bottom of the screen.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681494695082/cee52e69-93ea-4790-a681-bfb23542edfc.png" alt="Azure app registration authentication screen, with Redirect URI and Save button circled." class="image--center mx-auto" /></p>
<p>Outstanding! Now we've "told" our Azure app registration that Microsoft authentication requests from our Power Pages website are allowed. Next, we need to create a new <strong>secret</strong> so that the authentication process will be secure.</p>
<p>To create a new client secret within Azure app registration:</p>
<ol>
<li><p>Go to the <strong>Certificates &amp; secrets</strong> screen and select the <strong>Client secrets</strong> tab.</p>
</li>
<li><p>Hit <strong>+ New client secret</strong>.</p>
</li>
<li><p>Add a <strong>Description</strong> so everyone knows where this secret is being used (e.g. "Power Pages Microsoft authentication") and then hit <strong>Add</strong>.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681495290761/5d0454c7-e3db-40af-b2a4-aca3c6f17113.png" alt="Azure app registration Certificates &amp; secrets screen with Client secrets, + New client secret, secret Description, and Add button circled." class="image--center mx-auto" /></p>
<p>Once the new secret has been created, make sure to copy the <strong>Value</strong>, as it will only be displayed this one time. If you fail to copy it or lose it later, you'll need to create a new one.</p>
<p>With the client secret <strong>Value</strong> copied, let's go back to our Power Pages editor tab and paste it into the <strong>Client secret</strong> field. We also need the <strong>Client ID</strong>, so let's go get that next.</p>
<p>To get the client ID from Azure app registrations, simply go to the <strong>Overview</strong> screen and copy the <strong>Application (client) ID</strong> value.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681495663598/971d5f49-b145-47a0-b367-6ebb31dc955d.png" alt="Azure app registration Overview screen with Applicant (client) ID circled." class="image--center mx-auto" /></p>
<p>Now go back to the Power Pages editor and paste this into the <strong>Client ID</strong> field.</p>
<h3 id="heading-optional-change-audience-type">(Optional) Change audience type</h3>
<p>Depending on the intended audience, or user type, for your Power Pages website, you may need to change the audience type within the Azure app registration so that the intended users can log in as expected. By default, only users within your organization are allowed to authenticate with this method, but you can change this to allow any work/school accounts, or any Microsoft account (work/school or personal). If the Power Pages website is a company intranet, for example, you would want to leave it set to the default. However, if you're building a B2B website, then you'll probably want to allow all work/school accounts. Furthermore, if you're building a public-facing website, then you'll also want to allow personal accounts.</p>
<p>To change the audience type to allow other organization accounts, you can simply choose <strong>Accounts in any organizational directory (Any Azure AD directory - Multitenant)</strong> on the <strong>Authentication</strong> screen, like so:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681496664391/52918d1b-ddc8-4cd8-82f1-c8615d55e78b.png" alt="Azure app registration Authentication screen with &quot;Accounts in any organizational directory (Any Azure AD directory - Multitenant)&quot; circled." class="image--center mx-auto" /></p>
<p>However, as you may have already read in the on-screen warning message, it's not as simple for enabling personal Microsoft accounts. Instead, we need to open the <strong>Manifest</strong> from the side menu, and make the following changes:</p>
<ul>
<li><p>Change <strong>accessTokenAcceptedVersion</strong> from <strong>null</strong> to <strong>2</strong>.</p>
</li>
<li><p>Change <strong>signInAudience</strong> from <strong>AzureADMyOrg</strong> to <strong>AzureADandPersonalMicrosoftAccount</strong>.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681496947639/b9dffae9-0e72-407a-9edd-b1910a682a45.png" alt="Azure app registration manifest with accessTokenAcceptedVersion circled." class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681496994933/5ae0059a-c817-4125-94d6-c5e24a920654.png" alt="Azure app registration manifest with signInAudience circled." class="image--center mx-auto" /></p>
<p>Once you're done making the necessary changes, make sure to hit <strong>Save</strong>.</p>
<h3 id="heading-complete-the-configuration">Complete the configuration</h3>
<p>Now that we have all of the necessary configuration details filled in, you can optionally go through and fill in the <strong>Additional settings</strong> if you have specific requirements for those, and then hit <strong>Confirm</strong> and then <strong>Close</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681495879084/5845a41b-1305-42f1-8f07-0c88cc365b22.png" alt="Configure Microsoft settings step of Configure identity provider flyout menu with Client ID and Client secret filled in, and Confirm button circled." class="image--center mx-auto" /></p>
<h3 id="heading-wrap-up">Wrap up</h3>
<p>You did it! You've successfully configured Microsoft authentication for your Power Pages website. To verify this and test it out, let's go back to the sign-in page of your Power Pages website at your custom domain name or [your-power-pages-website].powerappsportals.com/signin and you'll now see a <strong>Microsoft</strong> option next to <strong>Azure AD</strong>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681498239958/5f75db0b-0471-4a37-86ce-defa4aea3ff3.png" alt="Power Pages website sign in screen with Microsoft option circled." class="image--center mx-auto" /></p>
<p>If you click on this, you'll now have the option to sign in with your Microsoft account (personal or work/school, depending on the audience type configured).</p>
<p>Thanks for reading and, if you found this article useful, please consider sharing it across your network so others may be able to benefit from this information.</p>
<p>Take care!</p>
]]></content:encoded></item><item><title><![CDATA[Using source control with Azure DevOps and Power Pages websites]]></title><description><![CDATA[If you're used to working with "full-code" websites or applications, you may be wondering how you can add a Power Pages website to source control (Git) to…]]></description><link>https://richardcarrigan.hashnode.dev/using-source-control-with-azure-devops-and-power-pages-websites</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/using-source-control-with-azure-devops-and-power-pages-websites</guid><category><![CDATA[azure-devops]]></category><category><![CDATA[Git]]></category><category><![CDATA[source control]]></category><category><![CDATA[PowerPlatform]]></category><category><![CDATA[PowerPages]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Tue, 11 Apr 2023 17:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/5RjdYvDRNpA/upload/59d057ef9aaaa0fc545e0341e67bec19.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you're used to working with "full-code" websites or applications, you may be wondering how you can add a Power Pages website to source control (Git) to track changes. Or, maybe you are using Azure DevOps to track work on the website and would like to automatically close work items when you finish making the changes to the website. Or, maybe you have heard about Power Platform ALM but are having trouble trying to figure out how to set it up for your Power Pages website.</p>
<p>Whatever the case may be, I'm here to help. In this tutorial, I'll walk you through every step needed to start using source control to track changes in your Power Pages website, using Azure DevOps. So let's get started!</p>
<h2 id="heading-azure-devops-setup">Azure DevOps setup</h2>
<p>First things first, if we want to start working with Azure DevOps, we'll need an account. So go to <a target="_blank" href="https://dev.azure.com">dev.azure.com</a> and, if you already have an Azure DevOps account, log into that. Otherwise, click <strong>Start free</strong> or <strong>Start free with GitHub</strong>, whichever you prefer.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679504224473/c763d79a-68b2-402f-a8c8-381fde835462.png" alt="Azure DevOps landing page" class="image--center mx-auto" /></p>
<p>If this is a new Azure DevOps account, you'll be prompted to create a new project. If you're logging into an existing account, you'll need to select <strong>+ New project</strong> in the top-right corner. Once you've reached the new project wizard, simply give your new project a name and hit <strong>+ Create project</strong>. This project will be used to store all of our Power Platform environment files, so the name should reflect that. You may be given the options for version control and agile process, but the defaults are usually fine unless you know you'll need something else.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679507556824/b1754fc9-36ba-4372-89d4-a28dec964091.png" alt="Azure DevOps create project screen" class="image--center mx-auto" /></p>
<blockquote>
<p>Note: by default in a new Azure DevOps account, all new projects are <strong>Private</strong>. You can change this by going to <strong>Organization settings &gt; Policies (under Security) &gt; Allow public projects</strong>.</p>
</blockquote>
<p>Now that we have a new Azure DevOps project, we need to create a <strong>Repo</strong> (or repository) to store our Power Pages website contents. To do this, select <strong>Repos</strong> on the sidebar and then choose <strong>Initialize</strong> under the heading <strong>Initialize main branch with a README or gitignore</strong>. We'll want to have the README file, but we don't need a gitignore file for now, so the defaults are fine.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679507604016/568e7087-c58a-4bc0-bc4f-d93544e13a84.png" alt="Newly-created Azure DevOps Repo" class="image--center mx-auto" /></p>
<h2 id="heading-clone-the-project-repo-to-our-local-machine">Clone the project repo to our local machine</h2>
<p>Alright, so we have our Azure DevOps project set up. Next, we need to connect a folder on our local machine to the new project. To do that, select <strong>Clone</strong> in the top-right and then copy the HTTPS URL provided. Alternatively, if you know what you're doing, you could also use SSH or the <strong>Clone in VS Code</strong> option if you already have that installed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679507486679/0ab2d0f9-0dfe-4cbb-b01d-61770f96831b.png" alt="Clon Repository flyout menu on Azure DevOps" class="image--center mx-auto" /></p>
<blockquote>
<p>Note: the following steps assume that you already have Git installed. If that is not the case, follow <a target="_blank" href="https://git-scm.com/book/en/v2/Getting-Started-Installing-Git">these instructions</a> before continuing.</p>
</blockquote>
<p>Back on your local machine, open a new terminal window (Git Bash, Windows Terminal, etc.) and navigate to the directory where you want your Power Pages website files stored (i.e. Documents folder) and then use <code>git clone</code> to copy your newly-created repo into this directory. For example:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> ~/Documents
git <span class="hljs-built_in">clone</span> https://powerplatformdevops2023@dev.azure.com/powerplatformdevops2023/Power%20Platform%20DevOps/_git/Power_Platform_DevOps
</code></pre>
<p>Once the cloning process finishes, you'll have a directory named the same as your Azure DevOps project, <strong>Power_Platform_DevOps</strong>.</p>
<p>Ok, so now we have a directory on our local machine containing a README file. What now? Thank you for asking 😀! Next, we need to download the Power Pages website files into this new directory, and then upload those files to our newly-created Azure DevOps repo.</p>
<p>But first, let's use the following commands to create a <strong>websites</strong> directory to store these files in. This will make it easier for us to distinguish between the files need for our Power Pages website and other files that are part of our Power Platform environment, such as Power Platform solutions.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> Power_Platform_DevOps
mkdir websites
</code></pre>
<h2 id="heading-download-power-pages-website-files">Download Power Pages website files</h2>
<blockquote>
<p>Note: as of March 2023, the <strong>Microsoft Power Platform CLI</strong>, which is necessary for downloading Power Pages website files, is only available through PowerShell. If you don't have it already, you can follow the instructions on Microsoft Learn for how to <a target="_blank" href="https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.3"><strong>Install PowerShell on Windows, Linux, and macOS</strong></a><strong>.</strong></p>
</blockquote>
<p>To download the files for our Power Pages website, we'll need to go through the following steps:</p>
<ol>
<li><p>Install the Microsoft Power Platform CLI tool.</p>
</li>
<li><p>Authenticate to our Power Platform environment.</p>
</li>
<li><p>Get the ID for our website.</p>
</li>
<li><p>Download the files.</p>
</li>
</ol>
<h3 id="heading-install-the-microsoft-power-platform-cli-tool">Install the Microsoft Power Platform CLI tool</h3>
<p>If you have Visual Studio Code installed, which I highly recommend if you're working with the Power Platform locally, you can <a target="_blank" href="https://learn.microsoft.com/en-us/power-platform/developer/cli/introduction#install-using-power-platform-tools-for-visual-studio-code">Install using Power Platform Tools for Visual Studio Code</a>. Otherwise, you'll want to follow the instructions to <a target="_blank" href="https://learn.microsoft.com/en-us/power-platform/developer/cli/introduction#install-power-platform-cli-for-windows">Install Power Platform CLI for Windows</a>.</p>
<h3 id="heading-authenticate-to-our-power-platform-environment">Authenticate to our Power Platform environment</h3>
<p>Once you have the Microsoft Power Platform CLI tool installed, enter the following command into PowerShell:</p>
<pre><code class="lang-bash">pac auth create -u [Dataverse URL]
</code></pre>
<blockquote>
<p>Note: to find your <strong>Dataverse URL</strong>, go to the <a target="_blank" href="https://admin.powerplatform.microsoft.com/environments">Environments list on the Power Platform Admin Center</a> and select the environment you're working with. The <strong>Environment URL</strong> is the one you need, and it is listed in the top-left of the <strong>Details</strong> section.</p>
</blockquote>
<p>This command will create a new authentication profile associating your Microsoft account with the Power Platform environment, so you don't have to re-authenticate every time you need to interact with it.</p>
<h3 id="heading-get-the-id-for-our-website">Get the ID for our website</h3>
<p>Now that we've authenticated, we'll need to get the <strong>ID</strong> for our Power Pages website, as the <strong>download</strong> command will need it. We can do this by listing all of the websites using the following command:</p>
<pre><code class="lang-bash">pac paportal list
</code></pre>
<blockquote>
<p>Why <code>paportal</code>? This is because Power Pages was previously referred to as Power Apps Portals and subsequently, some of the documentation and CLI commands still refer to it as such.</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679510489520/43150f87-4247-4c00-8ef2-6544fbab95c3.png" alt class="image--center mx-auto" /></p>
<p>You should get an output similar to the above image, listing all of the websites in this Power Platform environment, with a column for the <strong>Website Id</strong>. Copy this field as we'll need it for the next command.</p>
<h3 id="heading-download-the-files">Download the files</h3>
<p>Alright, we're finally ready to download the files. Using the path to your <strong>websites</strong> folder and the <strong>Website Id</strong> you collected in the last step, run the following command:</p>
<pre><code class="lang-bash">pac paportal download --path [PATH] -id [Website Id]
</code></pre>
<p>If done correctly, you should see a message similar to "[your website name] download succeeded in 15.4692731 secs". If you encountered an error, double-check the command syntax (notice that <code>--path</code> has two dashes whereas <code>-id</code> only has one) and make sure you've provided the correct path and website ID.</p>
<h2 id="heading-upload-portal-contents-to-ado-repo">Upload portal contents to ADO repo</h2>
<p>Now that we have all of our website files added to the <strong>websites</strong> folder of our local repo, we're ready to commit the changes and push them back up to our Azure DevOps project. To do this, run the following commands from within the repo (not the <strong>websites</strong> folder):</p>
<pre><code class="lang-bash">git add .
git commit -m <span class="hljs-string">"Start tracking website files in source control"</span>
git push origin main
</code></pre>
<blockquote>
<p>Note: if you encounter an error saying "Filename too long" when trying to add the files, you will need to open your terminal as an administrator and run <code>git config --system core.longpaths true</code>.</p>
</blockquote>
<p>Once these commands finish executing, you can refresh your project in Azure DevOps and you'll now see all of your website files.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679512122879/4a47adb8-0247-43ea-b33f-410a0924ce0b.png" alt="Screen showing Azure DevOps Repo with website files circled in red" class="image--center mx-auto" /></p>
<p>Hooray! You are now using source control to track changes to your Power Pages website. Now you can make changes either online or locally, and then upload those changes to Azure DevOps.</p>
<h2 id="heading-this-is-great-but-whats-the-point">This is great, but what's the point?</h2>
<p>Source control is just the first step towards a full DevOps workflow. In a future article, I'll show you how to configure a DevOps pipeline to deploy your changes from the Power Platform development environment to another environment for testing or to a production environment for live use.</p>
<p>Thanks for reading and, if you found this article useful, please consider sharing it across your network so others may be able to benefit from this information.</p>
<p>Take care!</p>
]]></content:encoded></item><item><title><![CDATA[How to create a new Power Pages website]]></title><description><![CDATA[Power Pages are the newest addition to the Power Platform family, but it existed before its official release, just under the name Power Apps Portals. There…]]></description><link>https://richardcarrigan.hashnode.dev/how-to-create-a-new-power-pages-website</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/how-to-create-a-new-power-pages-website</guid><category><![CDATA[PowerPlatform]]></category><category><![CDATA[PowerPages]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Tue, 04 Apr 2023 17:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/zNRITe8NPqY/upload/63cbebe2fc14736a33b6cb36737d6e89.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Power Pages are the newest addition to the Power Platform family, but it existed before its official release, just under the name Power Apps Portals. There are dramatic technical differences between the two, but they both allow you to create public-facing websites within your Power Platform environment. The benefit to this is that you get the features of a Content Management System (CMS) like WordPress, Drupal, or Sanity; connected directly with the Dataverse database you're already using for automated workflows (Power Automate), internal apps (Power Apps), and possibly even a CRM application (Dynamics 365). This integration with the Dataverse allows for improved data governance, privacy, and compliance - all while still allowing you to create engaging user experiences for your users.</p>
<blockquote>
<p>Note: to create a Power Pages website, you'll need a Power Platform environment. If you don't already have one, follow my guide on <a target="_blank" href="https://blog.richardcarrigan.dev/how-to-create-a-power-platform-test-environment"><strong>How to create a Power Platform test environment</strong></a> first.</p>
</blockquote>
<p>To get started, go to <a target="_blank" href="https://make.powerapps.com">make.powerapps.com</a> and log in using an account with the ability to create new Power Pages websites in your target environment. This is generally the System Administrator role, but other roles such as the Microsoft 365 Global Administrator may also have the necessary permissions. The easiest way to check this is to just log in and try to create one.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679500894263/7621d4c1-a343-4a33-820c-12b426eeff4e.png" alt="Power Apps landing page" class="image--center mx-auto" /></p>
<p>Once you've successfully logged in, double-check that the environment listed in the top-right corner is the one you want to create the new website in. If it's not, select it and then select the correct environment.</p>
<p>Now we're ready to create our new Power Pages website. Under <strong>Build business apps, fast</strong>, choose <strong>Blank app</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679500945402/2841b1e6-5599-4b41-aa8b-993870beeb5e.png" alt="Create a new Power App screen" class="image--center mx-auto" /></p>
<p>Under the heading <strong>Power Pages website</strong>, hit <strong>Create</strong>. Give your new website a <strong>Name</strong>, choose a globally-unique <strong>Address</strong>, and choose the site's <strong>Language</strong>. If you have previously created a Power Pages website and then deleted it, you can check the <strong>Use data from existing website record</strong> to recreate it. Otherwise, leave that box unchecked and hit <strong>Create</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679501000080/a70849d9-f6c0-4131-97af-a989458d763d.png" alt="New Power Pages website creation form" class="image--center mx-auto" /></p>
<p>That's it...almost. You've finished telling Power Apps how to configure your site, but the actual creation process can take quite a long time. You'll receive a notification on the page once the site has been successfully created and you will also receive an email notification sent to the account that you logged in with.</p>
<p>Congratulations, you've successfully created a new Power Pages website, ready to load with all your great content or simply as a sandbox for trying out new ideas!</p>
<p>Thanks for reading and, if you found this article useful, please consider sharing it across your network so others may be able to benefit from this information.</p>
<p>Take care!</p>
]]></content:encoded></item><item><title><![CDATA[How to create a Power Platform test environment]]></title><description><![CDATA[Are you looking to create a dev or test environment so you can build awesome Power Platform solutions before deploying them to production? Or maybe you…]]></description><link>https://richardcarrigan.hashnode.dev/how-to-create-a-power-platform-test-environment</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/how-to-create-a-power-platform-test-environment</guid><category><![CDATA[PowerPlatform]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Tue, 28 Mar 2023 17:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/LAaSoL0LrYs/upload/32563d530b73245f0a9b3b50d93643d9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Are you looking to create a dev or test environment so you can build awesome Power Platform solutions before deploying them to production? Or maybe you just want a place to work while you learn all about the Power Platform. Whatever your use case may be, you've come to the right place.</p>
<p>In this walkthrough, we'll set up a new Power Platform environment, complete with a Dataverse database, and even some test data so you have something to work with.</p>
<blockquote>
<p>Note: this walkthrough assumes that you already have a Microsoft 365 (M365) subscription, which is a pre-requisite for creating a Power Platform environment. If you don't have one yet, go check out my guide on <a target="_blank" href="https://blog.richardcarrigan.dev/how-to-create-a-microsoft-365-test-environment">How to create a Microsoft 365 test environment</a>, and then come back here.</p>
<p>Don't worry, I'll still be here 😉</p>
</blockquote>
<p>To get started, let's go to the <a target="_blank" href="https://admin.powerplatform.microsoft.com">Power Platform Admin Center</a> and log in. Make sure to log in using an account that has one of the following admin roles: Dynamics 365 admin, Global admin, or Microsoft Power Platform admin. These are the only roles authorized to create new environments, so there's no way around it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679444797423/9599ea40-761a-41c6-8b77-38905f9d9e3c.png" alt="Power Platform admin center sign in screen" class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679444953142/264d0b1e-a56a-4a71-a1cd-6c3d72b451cc.png" alt="Power Platform admin center landing page" class="image--center mx-auto" /></p>
<p>Once you've logged in, go to <strong>Environments</strong> on the side menu and then hit <strong>+ New</strong> in the top menu.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679445079056/1bc2932f-fc01-4be5-971b-1cf3eca9b79e.png" alt="Power Platform admin center dashboard with Environments and + New circled" class="image--center mx-auto" /></p>
<p>Next, we need to tell Power Platform how to configure our environment. On the <strong>New environment</strong> flyout menu, give your new environment a locally-unique (unique within this M365 environment) name. Now choose a <strong>Region</strong> for the environment, and therefore the data, to be stored; I recommend sticking with the default unless you have certain data residency restrictions. For the <strong>Type</strong>, you'll want to select <strong>Developer</strong> for learning/testing purposes, or <strong>Sandbox</strong> for an experience that most closely resembles a production environment. Next, you can optionally add a <strong>Purpose</strong> for this environment.</p>
<blockquote>
<p>Note: if you followed my guide on <a target="_blank" href="https://blog.richardcarrigan.dev/how-to-create-a-microsoft-365-test-environment">How to create a Microsoft 365 test environment</a>, then you'll want to choose <strong>Developer</strong>, as all other options require 1GB of storage capacity, which isn't available in an M365 sandbox environment.</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679446664773/b83a7bc2-7088-4cee-9ad7-bd8ee408f1ea.png" alt="Developer environment setup screen" class="image--center mx-auto" /></p>
<p>If you chose to create a <strong>Sandbox</strong> environment, I'd recommend choosing <strong>Yes</strong> for the <strong>Create a database for this environment?</strong> option, unless you know for certain that you will not need a Dataverse database. This is a classic case of "better to have it and not need it than to need it and not have it". As for the <strong>Pay-as-you-go with Azure</strong> option, this is so you can link the environment to an existing Azure subscription for billing. Since this is a sandbox environment that won't incur costs, you can leave this set to <strong>No</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679445768692/256234d1-2271-4eb4-9576-163f2ad73f30.png" alt="Sandbox environment setup screen" class="image--center mx-auto" /></p>
<p>Hit <strong>Save</strong> (for <strong>Developer</strong> environments) or <strong>Next</strong> (for <strong>Sandbox</strong> environments)<strong>.</strong></p>
<p>If you chose <strong>Sandbox</strong>, you'll need to select a <strong>Language</strong>, <strong>Currency</strong>, and choose whether or not to <strong>Deploy sample apps and data</strong>. Once you've made your choices, hit <strong>Save</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679446687601/e36438fa-514c-4c3b-8d9d-c66d5fcaa9b4.png" alt="Add database screen" class="image--center mx-auto" /></p>
<p>That's it! If you've followed all of the steps above, then you should now have a new Power Platform environment ready for all the awesome stuff you're going to build. If you encountered any problems, let me know so I can improve this guide so other people don't run into the same issues.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679446728320/1aa86563-5ac9-4666-a137-e0d46eac7252.png" alt="Environments screen showing success" class="image--center mx-auto" /></p>
<p>Thanks for reading and, if you found this article useful, please consider sharing it across your network so others may be able to benefit from this information.</p>
<p>Take care!</p>
]]></content:encoded></item><item><title><![CDATA[How to create a Microsoft 365 test environment]]></title><description><![CDATA[Whether you want a sandbox to learn and explore Microsoft 365 (M365), or you need a Microsoft 365 environment as a pre-requisite for something else, such…]]></description><link>https://richardcarrigan.hashnode.dev/how-to-create-a-microsoft-365-test-environment</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/how-to-create-a-microsoft-365-test-environment</guid><category><![CDATA[m365]]></category><category><![CDATA[Microsoft365]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Tue, 21 Mar 2023 23:36:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/xG02JzIBf7o/upload/3515dbbe6b72b4c17be19ee8b850276d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Whether you want a sandbox to learn and explore Microsoft 365 (M365), or you need a Microsoft 365 environment as a pre-requisite for something else, such as a Power Platform environment, this guide will walk through the process of setting one up from scratch.</p>
<p>First, go to <a target="_blank" href="https://my.visualstudio.com">https://my.visualstudio.com</a>. If you already have a personal Microsoft account, log in with that. Otherwise, you'll need to create a new one.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679438902193/166b37be-49b4-47bc-96a7-48902a423e52.png" alt="Visual Studio Dev Essentials sign in page" class="image--center mx-auto" /></p>
<p>Once you've successfully logged in, you should automatically be taken to the <strong>Benefits</strong> tab. If not, then select it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679439182635/10286259-2260-4e33-b7b3-fb6460b56342.png" alt="Visual Studio Dev Essentials landing page with Microsoft 365 Developer subscription circled" class="image--center mx-auto" /></p>
<p>There are many options listed under <strong>Benefits included in my subscription</strong>, but the one we want is <strong>Microsoft 365 Developer subscription (E5)</strong>. Find that and select <strong>Get started</strong>.</p>
<p>Now we're ready to go through the setup wizard to create our new M365 sandbox!</p>
<p>For starters, let's decide whether we need an <strong>Instant sandbox</strong> or a <strong>Configurable sandbox</strong>. Unless you've already created an M365 subscription before and know that you need certain customizations, I'd recommend starting with the <strong>Instant sandbox</strong>. Don't worry, you'll still have the ability to make changes after it's created.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679439945355/3283ac0f-7e4f-44ad-b9a1-fee6b204f323.png" alt="Set up your Microsoft 365 E5 sandbox screen" class="image--center mx-auto" /></p>
<p>Next, you'll need to choose a <strong>Country/region for your data center</strong>. Unless you have a certain data residency requirement, I'd just stick with the default value. After you've chosen the data location, you'll need to create an <strong>Admin username</strong> and <strong>Admin password</strong>. Keep in mind, this will be used to manage the M365 subscription, so it may be helpful to make it different from your Microsoft account info so you can be reminded which context you're in. Maybe something like "**[yourname]**m365admin". Once you've set the admin username and password, you'll need to choose whether the 16 fictitious users should use a different password from the admin or not. Once you've made your choice, hit <strong>Continue</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679440390431/72a0b893-d58e-40c0-b81d-db59c2ea40fd.png" alt="Set up your Microsoft 365 E5 instant sandbox screen" class="image--center mx-auto" /></p>
<p>Now that we have our initial configuration all set, all that's left is to confirm our identity to Microsoft. To do that, add your phone number and hit <strong>Send Code</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679440558439/6642a695-40ce-420d-aa4c-0a9d1f5f2204.png" alt="Add phone number for security screen" class="image--center mx-auto" /></p>
<p>Complete the verification and you're done!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679440892378/fc68749b-ba7e-4e0c-bfde-ad980eb5da53.png" alt="Screen showing the newly-created Microsoft 365 subscription" class="image--center mx-auto" /></p>
<p>Congratulations, you made it. In this walkthrough, you were able to create a Microsoft 365 sandbox environment that can be used for the next 90 days to experiment with concepts you're learning, create test resources for a proof-of-concept, or whatever else you may need it for.</p>
<p>Thanks for reading and, if you found this article useful, please consider sharing it across your network so others may be able to benefit from this information.</p>
<p>Take care!</p>
]]></content:encoded></item><item><title><![CDATA[How to connect (and stay connected) to Azure SQL Database using managed identities in Node.js - Part 2: Testing connection & handling token expiration]]></title><description><![CDATA[In How to connect (and stay connected) to Azure SQL Database using managed identities in Node.js - Part 1: Initial Setup, I walked through how you can…]]></description><link>https://richardcarrigan.hashnode.dev/azure-sql-node-managed-id-part2</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/azure-sql-node-managed-id-part2</guid><category><![CDATA[Azure]]></category><category><![CDATA[SQL]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Fri, 27 May 2022 22:40:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1653684239959/5vZrY2j1H.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-quick-recap">Quick recap</h2>
<p>In <a target="_blank" href="https://blog.richardcarrigan.dev/azure-sql-node-managed-id-part1">How to connect (and stay connected) to Azure SQL Database using managed identities in Node.js - Part 1: Initial Setup</a>, I walked through how you can configure your Node.js web app to authenticate and connect to an Azure SQL database using managed identities...but we're not done yet. If you're like I was the first time I set this up, you probably still have some unanswered questions, such as:</p>
<ul>
<li>Do we have to reconnect to the database with every request? </li>
<li>How do we query the database using this new connection? </li>
<li>Does the access token last forever, or does it expire eventually?</li>
<li>If it expires, what is the process for handling that?</li>
</ul>
<p>So in Part 2, we're going to go through and address each of these concerns...and more. Let's get started!</p>
<blockquote>
<p>Note: If you've landed on this article without first reading part 1, I highly encourage you to go back and read that first, as the concepts and walkthroughs pick up and build on where part 1 left off.</p>
</blockquote>
<h2 id="heading-do-we-have-to-reconnect-to-the-database-with-every-request">Do we have to reconnect to the database with every request?</h2>
<p>No. Thanks to some really smart people, we're able to take advantage of a feature called "connection pooling". Connection pooling is a feature that allows our app to create a set of long-living connections to the database, and to simply reuse them over and over, rather than opening and closing connections to the database for every request. You can read more about <a target="_blank" href="https://tediousjs.github.io/node-mssql/#connection-pools">connection pooling in the node-mssql docs</a>.</p>
<p>To utilize this feature in our Node.js app, the only change we need to make is to store the SQL connection in the Express <code>app.locals</code> object so we can access it throughout our app. Within your entry point, <code>index.js</code> in my example, replace:</p>
<pre><code>await <span class="hljs-keyword">sql</span>.<span class="hljs-keyword">connect</span>(config);
</code></pre><p>with:</p>
<pre><code>app.locals.db <span class="hljs-operator">=</span> await sql.connect(config);
</code></pre><p>With our connection now saved and accessible throughout our app, we can now access the connection within any Express route through <code>req.app.locals.db</code>, like so:</p>
<pre><code>const pool <span class="hljs-operator">=</span> req.app.locals.db;
</code></pre><p>Now we're ready to create our first query.</p>
<h2 id="heading-how-do-we-query-the-database-using-this-new-connection">How do we query the database using this new connection?</h2>
<p>To create a simple query so we can test the database connection, let's add the following route right before <code>app.listen</code>:</p>
<pre><code>app.get(<span class="hljs-string">'/products'</span>, async (req, res) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  const pool <span class="hljs-operator">=</span> req.app.locals.db;

  <span class="hljs-keyword">try</span> {
    const queryResult <span class="hljs-operator">=</span> await pool.query(<span class="hljs-string">'SELECT * FROM SalesLT.Product'</span>);
    res.<span class="hljs-built_in">send</span>(queryResult.recordset);
  } <span class="hljs-keyword">catch</span> (err) {
    console.log(err);
    res.status(<span class="hljs-number">500</span>).<span class="hljs-built_in">send</span>(<span class="hljs-string">'Uh oh, something went wrong'</span>);
  }
});
</code></pre><p>This route is called whenever a client sends an HTTP GET request to the <code>/products</code> route (e.g. <code>http://localhost:7000/products</code> during local development) and executes a simple query that retrieves all fields for all records from the <code>SalesLT.Product</code> table within the database using the <code>query()</code> method provided by our connection pool instance. It then sends the <code>recordset</code> array, which contains an object representing each record, back to the client.</p>
<p>Because we're querying the database over the network, we have to make the callback function <code>async</code> and then <code>await</code> the result of the query.</p>
<p>Also, because there's always the possibility that our query could fail (network connection drops, service outages, etc.), we're wrapping the entire operation with a <code>try...catch</code> block and sending a 500 status code and error message back to the client if an error occurs.</p>
<blockquote>
<p>Note: as a best practice, never send the error directly to the client, as bad actors testing your API could use this information to learn more about the structure of your API and/or database, such as table names, field names, required vs optional fields, etc.</p>
</blockquote>
<p>After adding this new route, start your server using <code>npm start</code> or <code>npm run dev</code> depending on your setup, and then navigate to the <code>/products</code> route in your browser, or send a GET request through a service like Postman. If all was successful, you should now see the full products array in the response.</p>
<blockquote>
<p>Note: If you run into error messages like <code>Cannot read properties of undefined (reading 'query')</code>, check that you've saved the connection to <code>app.locals.db</code>, but are accessing it in your route using <code>req.app.locals.db</code>. Many other examples online show that you can access <code>app.locals</code> directly, but I have found that to not be the case.</p>
</blockquote>
<h2 id="heading-does-the-access-token-last-forever-or-does-it-expire-eventually">Does the access token last forever, or does it expire eventually?</h2>
<p>Ok, so maybe you weren't actually wondering this. I know I wasn't when I first configured this, but when it did expire and I had to troubleshoot the issue, I definitely wished I had asked this question beforehand. Truth be told, this exact issue was a driving force for me to write this series of articles, so that hopefully I can save you from the pain I went through.</p>
<p>At the time of this writing, Microsoft states in their Access tokens and refresh tokens documentation, that the token expires after 1 hour. However, in testing this by logging the <code>app.locals.tokenObj.expiresOnTimestamp</code> property on server startup, I've verified that the access token issued by the <code>@azure/identity</code> package's <code>DefaultAzureCredential</code> <code>getToken()</code> method actually lasts for 24 hours.</p>
<h2 id="heading-if-it-expires-what-is-the-process-for-handling-that">If it expires, what is the process for handling that?</h2>
<p>So, if the access token only lasts 24 hours, does that mean we'll have to restart our server every 23.5 hours to get a new token? Definitely not. Instead, we need to perform the following steps before processing each incoming request:</p>
<ol>
<li>Check to see if the token has expired. If expired...</li>
<li>Close the SQL connection</li>
<li>Obtain a new token</li>
<li>Establish a new SQL connection using the new token</li>
</ol>
<p>I know that sounds like a lot of work, and to an extent it is, but the end result of a stable connection is well worth it.</p>
<h3 id="heading-check-token-expiration-status">Check token expiration status</h3>
<p>Within our new <code>/products</code> route, add the following <code>if</code> statement at the beginning of the <code>try...catch</code> block:</p>
<pre><code><span class="hljs-selector-tag">if</span> (<span class="hljs-selector-tag">req</span><span class="hljs-selector-class">.app</span><span class="hljs-selector-class">.locals</span><span class="hljs-selector-class">.tokenObj</span><span class="hljs-selector-class">.expiresOnTimestamp</span> &lt; <span class="hljs-selector-tag">Date</span><span class="hljs-selector-class">.now</span>()) {
}
</code></pre><p>This uses the built-in <code>expiresOnTimestamp</code> property of the access token object and checks to see if it's less than (aka earlier than) the current timestamp.</p>
<blockquote>
<p>Shout out to <a target="_blank" href="https://github.com/KarishmaGhiya">@KarishmaGhiya</a> for helping me with this part!</p>
</blockquote>
<h3 id="heading-close-the-sql-connection">Close the SQL connection</h3>
<p>Within the above <code>if</code> statement, add the following line:</p>
<pre><code>await <span class="hljs-keyword">sql</span>.<span class="hljs-keyword">close</span>();
</code></pre><p>Just like that, we've closed the connection to the database!</p>
<blockquote>
<p>Note: be sure to close the database connection (<code>sql</code> variable), not the connection pool (<code>req.app.locals.db</code>), as closing the connection pool will not throw any errors, but also will not refresh the connection as expected.</p>
</blockquote>
<h3 id="heading-obtain-a-new-token-andamp-establish-a-new-sql-connection">Obtain a new token &amp; establish a new SQL connection</h3>
<p>Copy the following code from the <code>app.listen</code> method:</p>
<pre><code>app.locals.tokenObj <span class="hljs-operator">=</span> await app.locals.credential.getToken(
  <span class="hljs-string">'https://database.windows.net/.default'</span>
);

const config <span class="hljs-operator">=</span> {
  authentication: {
    <span class="hljs-keyword">type</span>: <span class="hljs-string">'azure-active-directory-access-token'</span>,
    options: {
      token: app.locals.tokenObj.token
    }
  },
  server: process.env.DB_SERVER,
  database: process.env.DB_NAME
};

app.locals.db <span class="hljs-operator">=</span> await sql.connect(config);
</code></pre><p>Within the <code>try</code> block, after closing the SQL connection, paste in the copied code. Make  sure to change all instances of <code>app.locals</code> to <code>req.app.locals</code>!</p>
<blockquote>
<p>Note: As a DRY optimization, you can also move this code into its own function, such as <code>connectDBAsync()</code>, and then call it from both <code>app.listen</code> and all routes.</p>
</blockquote>
<p>Your complete index.js should now look like this:</p>
<pre><code>const express <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
const { DefaultAzureCredential } <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'@azure/identity'</span>);
const sql <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'mssql'</span>);

const app <span class="hljs-operator">=</span> express();

app.locals.credential <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> DefaultAzureCredential();

app.get(<span class="hljs-string">'/products'</span>, async (req, res) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  const pool <span class="hljs-operator">=</span> req.app.locals.db;

  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">if</span> (req.app.locals.tokenObj.expiresOnTimestamp <span class="hljs-operator">&lt;</span> Date.now()) {
      await sql.close();
      req.app.locals.tokenObj <span class="hljs-operator">=</span> await req.app.locals.credential.getToken(
        <span class="hljs-string">'https://database.windows.net/.default'</span>
      );

      const config <span class="hljs-operator">=</span> {
        authentication: {
          <span class="hljs-keyword">type</span>: <span class="hljs-string">'azure-active-directory-access-token'</span>,
          options: {
            token: req.app.locals.tokenObj.token
          }
        },
        server: process.env.DB_SERVER,
        database: process.env.DB_NAME
      };

      req.app.locals.db <span class="hljs-operator">=</span> await sql.connect(config);
    }
    const queryResult <span class="hljs-operator">=</span> await pool.query(<span class="hljs-string">'SELECT * FROM SalesLT.Product'</span>);
    res.<span class="hljs-built_in">send</span>(queryResult.recordset);
  } <span class="hljs-keyword">catch</span> (err) {
    console.log(err);
    res.status(<span class="hljs-number">500</span>).<span class="hljs-built_in">send</span>(<span class="hljs-string">'Uh oh, something went wrong'</span>);
  }
});

app.listen(process.env.PORT, async () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  app.locals.tokenObj <span class="hljs-operator">=</span> await app.locals.credential.getToken(
    <span class="hljs-string">'https://database.windows.net/.default'</span>
  );

  const config <span class="hljs-operator">=</span> {
    authentication: {
      <span class="hljs-keyword">type</span>: <span class="hljs-string">'azure-active-directory-access-token'</span>,
      options: {
        token: app.locals.tokenObj.token
      }
    },
    server: process.env.DB_SERVER,
    database: process.env.DB_NAME
  };

  app.locals.db <span class="hljs-operator">=</span> await sql.connect(config);
  console.log(`Listening on ${process.env.PORT}`);
});
</code></pre><h2 id="heading-recent-update">Recent Update</h2>
<p>Shortly after writing Part 1, I learned that <code>mssql</code> now supports use of the <code>azure-active-directory-default</code> authentication type. Thank you to <a target="_blank" href="https://github.com/MichaelSun90">@MichealSun90</a>, <a target="_blank" href="https://github.com/mShan0">@mShan0</a>, and <a target="_blank" href="https://github.com/dhensby">@dhensby</a> for making this happen! Support for this authentication type means that the entire process of creating, checking, and refreshing tokens is no longer necessary. You can now directly use your <code>DefaultAzureCredential</code> instance and it #justworks!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So that's it! If you've been following along, you should now have a fully functional Node.js API that authenticates to your Azure SQL database using managed identities, and maintains that connection by checking and refreshing tokens as needed.</p>
<p>If you found this two-part series helpful, please consider liking and/or sharing it, so other people can benefit too!</p>
<p>If you ran into any issues while following along, or if you're experiencing an issue related to this, feel free to drop a comment and I'll do my best to answer it, or at least help you find the right resources so you can quickly resolve your issue and get back up and running!</p>
<p>Till next time!</p>
]]></content:encoded></item><item><title><![CDATA[How to connect (and stay connected) to Azure SQL Database using managed identities in Node.js - Part 1: Initial Setup]]></title><description><![CDATA[Traditionally, connecting to a SQL database within a Node.js app was fairly straightforward: This method has worked for a long, long time and is great, but…]]></description><link>https://richardcarrigan.hashnode.dev/azure-sql-node-managed-id-part1</link><guid isPermaLink="true">https://richardcarrigan.hashnode.dev/azure-sql-node-managed-id-part1</guid><category><![CDATA[Azure]]></category><category><![CDATA[SQL]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Richard Carrigan]]></dc:creator><pubDate>Thu, 19 May 2022 22:27:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1653675519622/RaK6Ep37B.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Traditionally, connecting to a SQL database within a Node.js app was fairly straightforward:</p>
<ol>
<li>Create new SQL database</li>
<li>Set new admin credentials (never keep defaults)</li>
<li>Add SQL server admin credentials to .env</li>
<li>Use admin credentials to connect to SQL database on server startup</li>
<li>Go on vacation!</li>
</ol>
<p>This method has worked for a long, long time and is great, but there are some drawbacks. </p>
<p>First off, anyone working with your SQL database programmatically, either through your Node.js app or otherwise, would need those credentials. This is a huge security concern because then it becomes difficult to change those credentials frequently without breaking any apps or scripts that use them.</p>
<p>Secondly, allowing apps to use the SQL server admin credentials grants that app FULL permissions to the SQL server, which means any developer on your team could <code>drop</code> the production database inadvertently. Now you could create alternate users within your SQL server and grant those users reduced permissions, but if you're hosting your resources on Azure, there's a better way: managed identities.</p>
<h2 id="heading-what-are-managed-identities">What are managed identities?</h2>
<p>Managed identities are like user accounts, but for apps. Just like users within your organization (assuming you're using Azure Active Directory for user management), you can add "service principals" to Azure Active Directory and then assign permissions to them via Role-Based Access Controls (RBAC). These "service principals" can come in many forms, but the one we want to focus on right now is the Managed Identity.</p>
<h2 id="heading-how-do-i-create-a-managed-identity-for-my-app">How do I create a managed identity for my app?</h2>
<p>If you've already deployed, or are planning to deploy, your app to an Azure resource (Function App, App Service Web App, etc.), then you can just turn on the functionality. Refer to <a target="_blank" href="https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/managed-identities-status">Azure services that can use managed identities to access other services</a> for a list of Azure resources that support managed identities. </p>
<p>To create a managed identity for your app:</p>
<ol>
<li>Within the <a target="_blank" href="portal.azure.com">Azure portal</a>, navigate to your app resource</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652990379057/vf-gCwSRN.png" alt="image.png" /></p>
<ol>
<li>On the left sidebar menu, under Settings, click on 'Identity'</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652990553636/8AdIl546S.png" alt="image.png" /></p>
<ol>
<li>Turn 'Status' to 'On', hit 'Save', and then select 'Yes' to confirm that you want to enable the system assigned managed identity</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652990716310/UsNR2RkSZ.png" alt="image.png" /></p>
<blockquote>
<p>Note: System assigned managed identities are recommended as they follow the same lifecycle as the Azure resource, but you can alternatively create a User assigned managed identity if you want it to be separate.</p>
</blockquote>
<h2 id="heading-ive-created-my-managed-identitynow-what">I've created my managed identity...now what?</h2>
<p>Now that you have a managed identity created for your app, you'll need to grant the managed identity access to the Azure SQL database.</p>
<p>First, make sure that Azure Active Directory authentication has been enabled on the SQL server. To verify this:</p>
<ol>
<li>Within the Azure portal, navigate to the SQL server (not the database), and click on either 'Azure Active Directory in the left sidebar menu, or 'Active Directory admin' in the features section</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652991867761/yyOueJwMg.png" alt="image.png" /></p>
<ol>
<li>Click 'Set admin', search for and select an Azure Active Directory user, and hit 'Save'</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652992171199/eneQ9_bJt.png" alt="image.png" /></p>
<p>Once Azure Active Directory authentication has been set up, you'll need to add the managed identity as a user in the database and assign it the roles it will need so it can perform the operations it is meant to perform</p>
<p>To add the managed identity into the database:</p>
<ol>
<li><p>Log into the Azure portal using the Azure Active Directory credentials, if not already</p>
</li>
<li><p>Navigate to the SQL database and click 'Query editor (preview)' from the left sidebar menu, and then click on 'Continue as [AAD user here]...' under 'Active Directory authentication</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652992809414/yS_BoNghX.png" alt="image.png" /></p>
<blockquote>
<p>Note: At this point, it may be necessary to create a new firewall rule to allow your IP address range access to the SQL server</p>
</blockquote>
<ol>
<li>Within the query screen that opens, create the managed identity as a user in the database and indicate that the user information is being provided by Azure Active Directory by running the following SQL command:</li>
</ol>
<pre><code><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">USER</span> [managedidwebapp] <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">EXTERNAL</span> PROVIDER
</code></pre><blockquote>
<p>Make sure to replace <code>managedidwebapp</code> with the name of your Azure app resource</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652993172535/23Mp6JqHb.png" alt="image.png" /></p>
<ol>
<li>Grant the managed identity the database-level roles it needs, such as <code>db_datareader</code> and <code>db_datawriter</code> by running the following SQL commands:</li>
</ol>
<pre><code><span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">ROLE</span> db_datareader <span class="hljs-keyword">ADD</span> <span class="hljs-keyword">MEMBER</span> [managedidwebapp]
<span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">ROLE</span> db_datawriter <span class="hljs-keyword">ADD</span> <span class="hljs-keyword">MEMBER</span> [managedidwebapp]
</code></pre><blockquote>
<p>Make sure to replace <code>managedidwebapp</code> with the name of your Azure app resource that you added in the previous step</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652993409324/UFloge5BH.png" alt="image.png" /></p>
<h2 id="heading-using-managed-identity-in-nodejs-app">Using managed identity in Node.js app</h2>
<p>You've now successfully created a managed identity for your app, added the managed identity as a database user, and granted that managed identity the necessary permissions for the SQL database. Great job!</p>
<p>However, our work's not quite done yet. After all, what good is the managed identity if you're app isn't actually using it?!</p>
<p>To access and use the managed identity in a Node.js app, first we'll need the <code>@azure/identity</code> package, so run </p>
<pre><code><span class="hljs-built_in">npm</span> install @azure/identity
</code></pre><p>within your app directory to add it to the project dependencies.</p>
<p>The specific component we need from this package is the <code>DefaultAzureCredential</code>, as it is the most flexible, by allowing us to use different credential types during local development without making any code changes. Let's import that into the entry point of our app as follows:</p>
<pre><code><span class="hljs-section">const</span> { <span class="hljs-attribute">DefaultAzureCredential</span> } = require(<span class="hljs-string">'<span class="hljs-variable">@azure</span>/identity'</span>);
</code></pre><p>Now that we've imported the <code>DefaultAzureCredential</code> class, we need to create a new instance. Since we're going to need access to this credential instance in other parts of our app, let's add it to Express's <code>app.locals</code> object as follows:</p>
<pre><code>app.locals.credential <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> DefaultAzureCredential();
</code></pre><p>This constructor will look for existing credentials to use, which in our case will be the managed identity when deployed, but what about while we're developing locally? Well in that case, <code>DefaultAzureCredential</code> can use various credentials, such as Azure CLI, VS Code Azure extension, etc. Read more about that in the <a target="_blank" href="https://docs.microsoft.com/en-us/javascript/api/overview/azure/identity-readme?view=azure-node-latest#defaultazurecredential">Microsoft Docs</a>. </p>
<blockquote>
<p>The key point worth noting here is that whichever method you use to authenticate locally to Azure Active Directory, you'll need to follow the steps mentioned earlier to make sure that those credentials have the same level of access to the SQL database as your app's managed identity.</p>
</blockquote>
<p>Once we've instantiated the credential we need, we'll need to use it to connect to our SQL database. First, install the <code>mssql</code> package if not already installed by running </p>
<pre><code><span class="hljs-built_in">npm</span> install mssql
</code></pre><blockquote>
<p>You might be able to use a different SQL package, but <code>mssql</code> is maintained by Microsoft and therefore stays more up-to-date with Azure changes, such as managed identities.</p>
</blockquote>
<p>With that installed, let's import it into the app entry point as follows:</p>
<pre><code><span class="hljs-keyword">const</span> sql = <span class="hljs-keyword">require</span>(<span class="hljs-string">'mssql'</span>);
</code></pre><p>Next, let's decide how we're going to authenticate with the SQL server. There are many different options (at the time of writing this, the available options are: <code>default</code>, <code>ntlm</code>, <code>azure-active-directory-password</code>, <code>azure-active-directory-access-token</code>, <code>azure-active-directory-msi-vm</code>, and <code>azure-active-directory-msi-app-service</code>). To allow us to use <code>DefaultAzureCredential</code> locally and deployed, however, the easiest option to configure is <code>azure-active-directory-access-token</code>. Unfortunately, it does require the extra step of obtaining an access token from Azure Active Directory, so let's do that now.</p>
<p>We'll call the <code>getToken</code> method of the <code>DefaultAzureCredential</code> class and pass in a scope of <code>https://database.windows.net/.default</code> like so:</p>
<pre><code>app.locals.tokenObj <span class="hljs-operator">=</span> app.locals.credential.getToken(<span class="hljs-string">'https://database.windows.net/.default'</span>);
</code></pre><p>This method returns an object with the <code>token</code> as well as an <code>expiresOnTimestamp</code> property that we'll need later, so that's why we're storing it in Express's <code>app.locals</code> object and naming it <code>tokenObj</code> instead of just <code>token</code>. Also, this method is asynchronous since it is sending a network request to Azure Active Directory, so I find it best to add <code>async</code> to the <code>app.listen</code> callback, and <code>await</code> the result, like so:</p>
<pre><code>app.listen(<span class="hljs-number">7000</span>, async () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  app.locals.tokenObj <span class="hljs-operator">=</span> await app.locals.credential.getToken(
    <span class="hljs-string">'https://database.windows.net/.default'</span>
  );
  console.log(`Listening on ${process.env.PORT}`);
});
</code></pre><p>Now that we have our access token, let's create the connection <code>config</code> object that we'll need to provide when we connect to the server:</p>
<pre><code>const config = {
  authentication: {
    <span class="hljs-keyword">type</span>: <span class="hljs-string">'azure-active-directory-access-token'</span>,
    <span class="hljs-keyword">options</span>: {
      token: app.locals.tokenObj.token
    }
  },
  <span class="hljs-keyword">server</span>: <span class="hljs-string">'managedidsqlserver.database.windows.net'</span>,
  <span class="hljs-keyword">database</span>: <span class="hljs-string">'testdb'</span>
};
</code></pre><blockquote>
<p>Replace the <code>server</code> and <code>database</code> values accordingly</p>
</blockquote>
<p>Putting it all together, your index.js should now look like this:</p>
<pre><code>const express <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
const { DefaultAzureCredential } <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'@azure/identity'</span>);
const sql <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'mssql'</span>);

const app <span class="hljs-operator">=</span> express();

app.locals.credential <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> DefaultAzureCredential();

app.listen(process.env.PORT, async () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  app.locals.tokenObj <span class="hljs-operator">=</span> await app.locals.credential.getToken(
    <span class="hljs-string">'https://database.windows.net/.default'</span>
  );

  const config <span class="hljs-operator">=</span> {
    authentication: {
      <span class="hljs-keyword">type</span>: <span class="hljs-string">'azure-active-directory-access-token'</span>,
      options: {
        token: app.locals.tokenObj.token
      }
    },
    server: process.env.DB_SERVER,
    database: process.env.DB_NAME
  };

  await sql.connect(config);
  console.log(`Listening on ${process.env.PORT}`);
});
</code></pre><h2 id="heading-end-of-part-1">End of Part 1</h2>
<p>Success! You should now be able to connect to your Azure SQL database through your Node.js app using the managed identity when deployed, and your chosen authentication method when developing locally. If you ran into any errors, let me know in the comments.</p>
<p>Continue on to <a target="_blank" href="https://blog.richardcarrigan.dev/azure-sql-node-managed-id-part2">How to connect (and stay connected) to Azure SQL Database using managed identities in Node.js - Part 2: Testing connection &amp; handling token expiration</a>, where I'll show you how to use this connection in your queries, and also outline the process for refreshing our access token after it expires.</p>
<p>Till next time!</p>
]]></content:encoded></item></channel></rss>