Thursday, December 19, 2024

JavaScript to automatically select a record in a subgrid when the form loads

JavaScript Subgrid Selection

Yesterday, someone from a WhatsApp group asked me to help on the following scenario:

“Any idea, when form loads, check form type if not new and has related record in subgrid then I need to select record on subgrid automatically. Any suggestion how we can use JavaScript?”

To achieve the requirement where a form loads, checks if the form type is not "new," and selects a related record in a subgrid if it exists, you can use JavaScript in your model-driven app. Here's how to implement this:

Step-by-Step Implementation

1. Setup Your Subgrid and Form

  • Ensure the subgrid is configured to display related records.
  • Identify the subgrid's name (you can find it in the form editor by selecting the subgrid and checking its properties, e.g., subgrid_name).

2. Add the JavaScript to Your Solution

async function onFormLoad(executionContext) {
    // Get form context
    const formContext = executionContext.getFormContext();

    // Check if form type is not "new"
    if (formContext.ui.getFormType() !== 1) { // 1 = Create form (New)
        try {
            // Wait for the subgrid to load and get its rows
            const subgridRows = await waitForSubgridLoad(formContext, "subgrid_name");

            // If subgrid has rows, perform your logic
            if (subgridRows.length > 0) {
                // Example: Select the first record or fetch data from an API
                const firstRow = subgridRows[0];

                // Call an API or perform additional operations (example API call)
                const apiData = await fetchApiData(firstRow.getData().getEntity().getId());
                console.log("API Data:", apiData);

                // Select the row in the subgrid
                firstRow.setSelected(true);
            }
        } catch (error) {
            console.error("Error handling subgrid or API:", error);
        }
    }
}

// Wait for the subgrid to load
function waitForSubgridLoad(formContext, subgridName) {
    return new Promise((resolve, reject) => {
        const subgrid = formContext.getControl(subgridName);
        if (!subgrid) {
            reject(new Error(`Subgrid '${subgridName}' not found.`));
            return;
        }

        // Subgrid may not load immediately; wait for it to finish loading
        subgrid.addOnLoad(() => {
            try {
                const rows = subgrid.getGrid().getRows();
                resolve(rows);
            } catch (err) {
                reject(err);
            }
        });
    });
}

// Fetch data from an API (example function)
async function fetchApiData(recordId) {
    const apiUrl = `https://your-api-endpoint.com/data/${recordId}`; // Replace with your actual API endpoint
    const response = await fetch(apiUrl, {
        method: "GET",
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer YOUR_ACCESS_TOKEN" // Replace with actual token if needed
        }
    });

    if (!response.ok) {
        throw new Error(`API request failed with status: ${response.status}`);
    }

    return response.json();
}

3. Add the JavaScript to Your Form

  • Upload the JavaScript file to your solution as a web resource.
  • Open the form editor for the entity.
  • Go to Form Properties > Events tab.
  • Add the web resource under the Form Load event.
  • Add the function onFormLoad and ensure you pass the executionContext parameter.

Key Notes:

  1. Custom Selection Logic:
    • If you want to select a specific record based on certain criteria, you can loop through the rows collection and match the record based on your conditions:
      rows.forEach(function (row) {
          var data = row.getData();
          var entity = data.getEntity();
          if (entity.getId() === "desired_record_id") {
              row.setSelected(true);
          }
      });

Microsoft Power Fx formula to Auto Populate User Name and Time Stamp

Power Apps Guide

Yesterday, someone from a WhatsApp group asked me to help with the following scenario:

I have a Power Apps requirement:
Created 2 fields: First Response By and First Response On on the form.
When a case is assigned to a user, that user's value should auto-populate in the First Response By field, and the time should be filled in the First Response On field.

To achieve this Power Apps requirement, you can use Power Fx formulas to configure the behavior for the First Response By and First Response On fields. Here's a step-by-step guide:

Steps to Implement:

1. Add Fields to the Form:

  • Ensure the fields First Response By (Text/Person field) and First Response On (DateTime field) are added to your data source (e.g., Dataverse table, SharePoint list, etc.) and included in the form.

2. Set Default Value for "First Response By":

When the case is assigned to a user, this field should auto-populate with the assigned user's name.

  • Go to the OnChange property of the field used to assign the case (e.g., "Assigned To").
  • Add this formula:
If(
  IsBlank(ThisItem.'First Response By'),
  UpdateIf(
    YourDataSource,
    ID = ThisItem.ID,
    { 'First Response By': AssignedTo.DisplayName }
  )
)
  • Replace YourDataSource with the name of your table and AssignedTo with the name of your user assignment field.

3. Set Time for "First Response On":

To capture the timestamp when the case is assigned, you can use the OnChange property of the same "Assigned To" field.

  • Add this formula:
If(
  IsBlank(ThisItem.'First Response On'),
  UpdateIf(
    YourDataSource,
    ID = ThisItem.ID,
    { 'First Response On': Now() }
  )
)

4. Handle Updates in the Form:

If you're working with a Power Apps form, ensure these updates are reflected correctly:

  • Use the Patch function to update the fields in your data source whenever the "Assigned To" field changes:
Patch(
  YourDataSource,
  ThisItem,
  {
    'First Response By': AssignedTo.DisplayName,
    'First Response On': If(IsBlank('First Response On'), Now(), 'First Response On')
  }
)

Optional Enhancements:

  • Add validation to ensure these fields are not overwritten after the first update.
  • Use conditions to handle edge cases (e.g., if a case is reassigned).

Send an email to all users of a team in Dynamics 365 when a checkbox is checked

Dynamics 365 Team Email Notification

Yesterday, someone from a WhatsApp group asked me to help with the following scenario:

"I have created one team in Dynamics 365. I want to send an email to all the users when one of the checkboxes on the form is enabled.

(I am able to fetch the team name, but not able to fetch the users' email IDs of that group.) Any idea how to send an email to all the users of the team?"

To send an email to all users of a team in Dynamics 365 when a checkbox is enabled, you can follow these steps:

1. Understand Dynamics 365 Team and Users Relationship

  • In Dynamics 365, each Team is associated with multiple Users.
  • The relationship is typically stored in the TeamMembership table, linking Teams and Users.

2. Fetch Users' Email Addresses from the Team

To fetch the email addresses of users in a team, you can query the TeamMembership and SystemUser tables:

  • Team Table: Get the Team's GUID.
  • TeamMembership Table: Use the Team's GUID to retrieve associated User IDs.
  • SystemUser Table: Fetch email addresses for those User IDs.

3. Use a Plugin, Workflow, or Power Automate

Option 1: Using a Plugin

If you're using a plugin, the logic can look like this:

Trigger Point:

  • The plugin is triggered when the checkbox field is updated.

Plugin Code Sample:


public void Execute(IServiceProvider serviceProvider)
{
    IPluginExecutionContext context = 
        (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    IOrganizationServiceFactory serviceFactory = 
        (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

    // Fetch the team ID from the context or related entity
    Guid teamId = new Guid("TEAM_GUID");

    // Query to fetch users in the team
    QueryExpression query = new QueryExpression("teammembership")
    {
        ColumnSet = new ColumnSet(false)
    };
    query.Criteria.AddCondition("teamid", ConditionOperator.Equal, teamId);
    EntityCollection teamMemberships = service.RetrieveMultiple(query);

    // Collect user emails
    List emails = new List();
    foreach (var teamMembership in teamMemberships.Entities)
    {
        Guid userId = teamMembership.GetAttributeValue("systemuserid");
        Entity user = service.Retrieve("systemuser", userId, new ColumnSet("internalemailaddress"));
        string email = user.GetAttributeValue("internalemailaddress");
        if (!string.IsNullOrEmpty(email))
        {
            emails.Add(email);
        }
    }

    // Send email logic
    // Create and send email using the collected email addresses
}
    

Option 2: Using Power Automate

  1. Trigger: Set the trigger as When a record is updated for the entity containing the checkbox.
  2. Actions:
    • Use the team ID to fetch the team record.
    • List team members using the List Rows action on the TeamMembership table with the teamid filter.
    • Fetch user emails from the SystemUser table.
    • Send an email using the collected email addresses.

Option 3: Using a Workflow

  1. Trigger: The workflow is triggered when the checkbox is updated.
  2. Steps:
    • Retrieve users in the team using the RetrieveMultiple method.
    • Send an email to all retrieved users.

Calculate Age from Date of Birth using PowerFx

Calculate Age in PowerFX

Calculate Age using Power FX formula

To calculate age using Power FX (the formula language used in Microsoft Power Apps), you can use a formula that calculates the difference between the current date and the date of birth (DOB).

PowerFX Code:

// Assume DateOfBirth is a Date field in your app
Age = DateDiff(DateOfBirth, Today(), Years)

Explanation:

  • DateOfBirth: The field that contains the user's birthdate.
  • Today(): This function gets the current date.
  • DateDiff: This function calculates the difference between two dates.
  • Years: The unit for the difference, which will return the age in years.

Example Use Case in a Label Control:

  1. Suppose you have a form with a DateOfBirth field.
  2. Add a label to your Power App.
  3. In the Text property of the label, enter the following formula:
"Age: " & Text(DateDiff(DateOfBirth.SelectedDate, Today(), Years))

This will display the age in years based on the selected date of birth in the DateOfBirth field.

Considerations:

  • This method assumes the person has already had their birthday this year. If the birthday hasn't occurred yet in the current year, the result will be one year less.
  • If you need to adjust this for precise age calculation (e.g., considering if the birthday has passed this year), you can add more logic to handle that.

Migrate KB Articles with all attachments from Dynamics 365/CRM

KB Articles Migration Guide

KB Articles Migration Guide

Yesterday, someone from a WhatsApp group asked me to help with "How to migrate KB Articles with all attachments from CRM to another system".

Migrating Knowledge Base (KB) Articles along with their attachments from Microsoft Dynamics 365 CRM to another system requires careful planning. Below is a detailed step-by-step approach to achieve this:


1. Analyze the Target System

Before starting the migration, ensure the target system supports the following:

  • KB Articles: The system should have an equivalent data structure for KB Articles.
  • Attachments: Ensure the target system can handle attachments and metadata such as filenames and file types.

2. Export KB Articles and Attachments from CRM

In Dynamics 365 CRM, KB Articles are stored as records in the KnowledgeArticle entity. Attachments are stored in the Annotation entity.

Option A: Use Power Automate or Power Platform Dataflows

  1. Export KB Articles:
    • Use Dataverse (Common Data Service) connector in Power Automate to extract KB Articles from the KnowledgeArticle table.
    • Export key fields such as:
      • Title
      • Content
      • Author
      • Keywords
      • State (Published/Draft)
      • Created On / Modified On
  2. Export Attachments:
    • Extract the corresponding records from the Annotation table where the objectid field links to the KnowledgeArticleId.
    • For each attachment:
      • Save the notetext (description), filename, and the encoded file (documentbody).
  3. Store Data:
    • Save the exported data (articles and attachments) in a structured format like CSV, JSON, or Azure Blob Storage.

Option B: Use a Third-Party Tool

  • Tools like KingswaySoft, Scribe, or XrmToolBox plugins (e.g., "Attachment Manager") can help you export KB Articles and attachments in bulk.

3. Transform Data for the Target System

  • Clean and prepare the exported data to match the schema of the target system.
  • Convert the CRM-specific fields (e.g., documentbody for attachments, which is base64 encoded) into formats required by the target system.

4. Import KB Articles and Attachments into the Target System

Option A: Use Target System's API

  1. KB Articles:
    • Use the target system’s API to create articles.
    • Map fields from the exported data (e.g., title, content, metadata) to the corresponding fields in the target system.
  2. Attachments:
    • Upload attachments using the target system’s API by:
      • Decoding the documentbody (base64).
      • Attaching the file to the corresponding article.

Option B: Use a File-Based Import

If the target system supports file-based imports:

  1. Prepare files (e.g., CSV, JSON, or XML) for articles and attachments.
  2. Use the target system’s import functionality to upload the data.

5. Validate the Migration

  • Check that all KB Articles have been imported correctly.
  • Ensure that attachments are linked to the correct articles and are accessible.
  • Test article searchability and formatting in the target system.

Sample Power Automate Flow

A high-level view of how to use Power Automate for this migration:

  1. Trigger: Run manually or on schedule.
  2. Action (Dataverse): Fetch records from KnowledgeArticle table.
  3. Action (Dataverse): Fetch related Annotation records for attachments.
  4. Action (Apply to Each):
    • Save articles and attachments to a target storage location or directly post to the target system API.

Custom Migration Tool for Dynamics 365

However, I suggested using a custom console application built with C# to create your own migration tool.

The code leverages the Dataverse Web API along with the Microsoft.Xrm.Sdk and Microsoft.Crm.Sdk namespaces.

Below is the sample implementation:

Prerequisites

  1. Add the following NuGet packages:
    • Microsoft.PowerPlatform.Dataverse.Client
    • Microsoft.CrmSdk.CoreAssemblies
    • Newtonsoft.Json (if needed for API calls to the target system)
  2. Set up an Azure App Registration for authentication to Dynamics 365 CRM.
  3. Provide necessary permissions to the app (Dataverse scope for KnowledgeArticle and Annotation).

Code

using Microsoft.PowerPlatform.Dataverse.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk;
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace KBMigration
{
    /// <summary>
    /// A console application designed to migrate Knowledge Base (KB) Articles
    /// along with their related attachments from Dynamics 365 CRM to a local directory.
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            // Step 1: Initialize the connection to the Dataverse (Dynamics 365) CRM
            string connectionString = "AuthType=OAuth;Url=https://yourorg.crm.dynamics.com;Username=yourusername;Password=yourpassword;AppId=your-app-id;RedirectUri=your-redirect-uri;";

            try
            {
                // Establish a service client to interact with CRM
                var serviceClient = new ServiceClient(connectionString);

                // Check if the connection is successful
                if (!serviceClient.IsReady)
                {
                    throw new InvalidOperationException("Failed to connect to CRM. Please check your credentials and network connection.");
                }

                Console.WriteLine("Connected to CRM successfully!");

                // Step 2: Retrieve and process KB Articles
                var articles = RetrieveKBArticles(serviceClient);

                if (articles.Entities.Count == 0)
                {
                    Console.WriteLine("No KB Articles found in CRM.");
                }
                else
                {
                    foreach (var article in articles.Entities)
                    {
                        Guid articleId = article.Id;
                        string title = article.GetAttributeValue<string>("title");
                        string content = article.GetAttributeValue<string>("content");

                        Console.WriteLine($"Processing Article: {title} (ID: {articleId})");

                        var attachments = RetrieveAttachments(serviceClient, articleId);
                        SaveArticleAndAttachments(articleId, title, content, attachments);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }

        static EntityCollection RetrieveKBArticles(ServiceClient serviceClient)
        {
            // Implementation for retrieving KB Articles
        }

        static EntityCollection RetrieveAttachments(ServiceClient serviceClient, Guid articleId)
        {
            // Implementation for retrieving attachments
        }

        static void SaveArticleAndAttachments(Guid articleId, string title, string content, EntityCollection attachments)
        {
            // Implementation for saving articles and attachments
        }
    }
}
        

Potential Enhancements

  • Retry Logic: Add logic for retrying failed operations (useful for network-related errors).
  • Pagination Handling: If there are too many KB Articles or attachments, implement pagination to handle large datasets efficiently.
  • Parallel Processing: Consider parallel processing to speed up the migration (using Task.WhenAll or Parallel.ForEach).

Key Considerations

  1. Authentication

    Use Azure Active Directory authentication for security (replace Username/Password with ClientSecret for production).

  2. Scalability

    For large datasets, consider using pagination with RetrieveMultiple.

  3. Custom Fields

    If you have custom fields in KB Articles, include them in the ColumnSet.

  4. Migration to Target System

    Replace the SaveArticleAndAttachments method with an API call or logic to import the data into your target system.

Example of Advanced UI customization in PowerApps, using custom HTML, CSS, and JavaScript

PowerApps Canvas Apps Customization

PowerApps Canvas Apps allow limited customization directly with HTML, CSS, and JavaScript. However, you can use HTML Text Controls, integrate PowerApps Portals for advanced customization, or use Power Automate with Azure Functions for JavaScript-like logic. Here's an example of advanced UI customization using HTML web resources in a PowerApps Canvas App:

Scenario

Create a responsive and visually appealing data table with Search/Filtering Functionality using advanced HTML and CSS styling embedded in a PowerApps Canvas App.

Steps to Implement

1. Design Your HTML/CSS Web Resource

Create an HTML file with embedded CSS for a styled table. Save it as a web resource in your Dataverse environment.

Example HTML (HTML File):

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
    }

    .custom-table-container {
      margin: 20px;
      overflow-x: auto; /* Enables horizontal scrolling on smaller screens */
    }

    .search-container {
      margin: 10px 20px;
      text-align: right;
    }

    .search-input {
      width: 100%;
      max-width: 300px;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 16px;
    }

    .custom-table {
      width: 100%;
      border-collapse: collapse;
      margin: 20px 0;
    }

    .custom-table th,
    .custom-table td {
      border: 1px solid #ddd;
      padding: 10px;
      text-align: left;
    }

    .custom-table th {
      background-color: #0078D7;
      color: white;
    }

    .custom-table tr:nth-child(even) {
      background-color: #f2f2f2;
    }

    .custom-table tr:hover {
      background-color: #ddd;
    }

    /* Responsive Styles */
    @media (max-width: 768px) {
      .custom-table th,
      .custom-table td {
        font-size: 14px;
        padding: 8px;
      }
    }

    @media (max-width: 480px) {
      .custom-table th,
      .custom-table td {
        font-size: 12px;
        padding: 6px;
      }

      .custom-table-container {
        margin: 10px;
      }
    }

    @media (max-width: 320px) {
      .custom-table th,
      .custom-table td {
        font-size: 10px;
        padding: 4px;
      }
    }
  </style>
</head>
<body>
  <div class="search-container">
    <input
      type="text"
      id="searchInput"
      class="search-input"
      placeholder="Search the table..."
      onkeyup="filterTable()"
    />
  </div>

  <div class="custom-table-container">
    <table class="custom-table" id="dataTable">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Value</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>1</td>
          <td>John Doe</td>
          <td>100</td>
        </tr>
        <tr>
          <td>2</td>
          <td>Jane Smith</td>
          <td>200</td>
        </tr>
        <tr>
          <td>3</td>
          <td>Sam Wilson</td>
          <td>150</td>
        </tr>
        <tr>
          <td>4</td>
          <td>Sara Connor</td>
          <td>180</td>
        </tr>
      </tbody>
    </table>
  </div>

  <script>
    function filterTable() {
      // Get the input field and its value
      const input = document.getElementById("searchInput");
      const filter = input.value.toUpperCase();

      // Get the table and rows
      const table = document.getElementById("dataTable");
      const rows = table.getElementsByTagName("tr");

      // Loop through all rows (skip the header row)
      for (let i = 1; i < rows.length; i++) {
        const row = rows[i];
        let isVisible = false;

        // Check each cell in the row
        const cells = row.getElementsByTagName("td");
        for (let j = 0; j < cells.length; j++) {
          const cell = cells[j];
          if (cell) {
            const text = cell.textContent || cell.innerText;
            if (text.toUpperCase().indexOf(filter) > -1) {
              isVisible = true;
              break;
            }
          }
        }

        // Show or hide the row based on the match
        row.style.display = isVisible ? "" : "none";
      }
    }
  </script>
</body>
</html>

2. Add a JavaScript File for Dynamic Data

Create a JavaScript file that injects data dynamically into the table.


function populateTable(data) {
  const tableBody = document.getElementById("data-table").querySelector("tbody");
  tableBody.innerHTML = ""; // Clear existing rows

  data.forEach(row => {
    const tr = document.createElement("tr");
    Object.values(row).forEach(value => {
      const td = document.createElement("td");
      td.textContent = value;
      tr.appendChild(td);
    });
    tableBody.appendChild(tr);
  });
}

3. Host the HTML/JS Resources

  • Upload the HTML and JavaScript files as web resources in Dataverse.
  • Copy the URLs of the hosted files.

4. Embed HTML in PowerApps

  1. Add an HTML Text Control in your Canvas App.

  2. Embed the URL of your hosted HTML file inside the control.

    Example for the HTMLText property:

    "<iframe src='https://<your-hosted-html-file-url>' width='100%' height='400px' frameborder='0'></iframe>"

5. Pass Data from PowerApps to HTML

To dynamically populate the table:

  1. Add a Power Automate Flow or use an API to pass the data to your web resource.
  2. For example, use the following pattern in your Canvas App:

    Set(dataPayload, JSON(DataSource));
    HtmlTextControl.HtmlText = 
        "<script>" & "populateTable(" & dataPayload & ");" & "</script>";

Key Features

  • Table columns dynamically.
  • Case-insensitive search.
  • Responsive layout for both the search bar and table.

Thanks for visiting!

Monday, July 13, 2020

Dynamics 365: Set Lookup Field To Current User on Selection of an OptionSet using JavaScript

Approval Type Scenario

Approval Type Automation in PowerApps

Yesterday, one of my LinkedIn connections asked me to help with a business scenario:

Business Scenario

The scenario involved two fields in a Business Process Flow:

  • Approval Type (optionset)
  • Approved By (systemuser lookup)

If Approval Type is set to "Approved," the Approved By field should automatically set its value to the current logged-in user.

Implementation in PowerApps Model-Driven App

You can achieve this functionality using a combination of JavaScript and event handlers. Here's how:

Steps to Implement:

  1. Create a JavaScript Web Resource:
    • Go to Solutions in the PowerApps Maker portal.
    • Add a JavaScript web resource to your solution.
    • Write JavaScript code to check the value of the Approval Type field and set the Approved By field to the current logged-in user.
  2. Add the Script to the Form:
    • Open the entity form where the Approval Type and Approved By fields exist.
    • Go to Form Properties.
    • Add the JavaScript web resource you created to the form.
  3. Add an Event Handler:
    • In the same Form Properties, go to the Event Handlers section.
    • Attach the setApprovedByOnApprovalTypeChange function to the OnChange event of the Approval Type field.
    • Ensure you pass the executionContext to the function.
  4. Publish Customizations:
    • After adding the event handler, save and publish the form.

Sample Code Snippet


function setApprovedByOnApprovalTypeChange(executionContext) {
    var formContext = executionContext.getFormContext();

    // Get the value of the Approval Type field
    var approvalType = formContext.getAttribute("approvaltype").getValue(); // Replace 'approvaltype' with your field's schema name

    // Check if Approval Type is "Approved" (value may vary based on your option set)
    if (approvalType === "Approved") { // Replace with the correct option value for "Approved"
        // Get the current logged-in user
        var currentUserId = Xrm.Utility.getGlobalContext().userSettings.userId;
        var currentUserName = Xrm.Utility.getGlobalContext().userSettings.userName;

        // Set the Approved By field
        formContext.getAttribute("approvedby").setValue([
            {
                id: currentUserId,
                entityType: "systemuser",
                name: currentUserName
            }
        ]);
    } else {
        // Clear the Approved By field if Approval Type is not "Approved"
        formContext.getAttribute("approvedby").setValue(null);
    }
}

        

Enhancing Model-Driven App Views with Custom Column Icons

Enhancing Model-Driven App Views with Custom Column Icons A Hidden Feature That Can Make Your Views Much More User-Friendly I came acro...