Click here to Skip to main content
15,884,425 members
Articles / Hosted Services / Azure
Article

Fusion Development for Hospitality Apps Part 2: Enabling Guest Check-In

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
21 Mar 2022CPOL6 min read 3.4K   2  
How to create a serverless app in Azure that reacts to data changes in Dataverse
This is Part 2 of a 3-part series that introduces the concept of fusion development and uses a real-work use case to show how it works from the perspective of a professional developer. This article explores how a professional developer can create a serverless app in Azure that reacts to data changes in Dataverse. This app helps the citizen developer modify their app without affecting actual data stored in the backend.

This article is a sponsored article. Articles such as these are intended to provide you with information on products and services that we consider useful and of value to developers

The first article of this three-part series demonstrated how a citizen developer might use a low-code solution like Microsoft Power Apps to create a self-sustaining app. The app manages guest check-ins, collecting additional information about services the guest requires.

This second article of the series explores how a professional developer can create a serverless app in Azure that reacts to data changes in Dataverse. This app helps the citizen developer modify their app without affecting actual data stored in the backend. Although this tutorial uses Python code as an example, other supported languages work, too.

Objective

The previous tutorial set up a Reservations table in the Dataverse and created a Power App to check in a guest. So far, the app only works with the Dataverse table. Hotel employees can use it to determine if anyone has checked in via the app. However, the chain-wide corporate database is oblivious to this activity.

As professional developers, who probably also maintain the corporate backend, we can now build a connector to link the data in Dataverse to their backend system. Subscribing to Azure Event Hub events enables reacting to the UI app’s changes without touching it.

The approach works like this:

  1. Create a mapping in the Microsoft system to send custom event messages.
  2. An employee checks in a guest.
  3. That action triggers an update event in the Dataverse.
  4. Through the mapping, Power Platform sends the event to the Event Hub.
  5. A Function app picks up the event, processes it, and informs the backend.

These steps happen without modifying the Power App, isolating the UI from backend functionality.

This process has four steps:

  1. Create the Event Hub in Azure.
  2. Register the Event Hub with Update operations in Dataverse.
  3. Verify the Events are sent.
  4. Create a Function app that responds to Event Hub events.

Creating the Event Hub

First, search for “Event Hub” in the Azure portal to create an Event Hub namespace. Once this step is complete, go to the resource.

Next, go to Shared Policies and create a policy with listen and send permissions. Copy the connection string and save it for subsequent steps.

Image 1

Then, click Create event to create an event that the Function app will monitor.

Registering the Service Endpoint

For Event Hub to monitor changes in the Dataverse, the connection needs to be registered. Refer to the Microsoft Document for instructions on downloading the Plugin Registration Tool.

First, open the Plugin Registration Tool and log in to the organization using the Office 365 option. When the login process is complete, the tool presents a list of all existing registrations. Click Register > Register New Service Endpoint.

Image 2

Using the connection string from the Event Hub, choose EventHub as Designation Type and JSON as the Message Format so the Function app can receive data in JSON format instead of XML. The service endpoint should resemble this screenshot:

Image 3

Now, tell Microsoft what the service endpoint will do by registering a new step that monitors changes in Dataverse. When the endpoint observes an Update in the Reservation table, an event fires in the Event Hub.

Image 4

Message is the type of operation the Event Hub should be monitoring. In this case, choose Update to watch update changes in the Reservations table.

Primary Entity is the entity to observe. In this case, monitor changes to the Reservation table.

The Registration Tool calls entities by their name. When the previous tutorial created the Dataverse table, it created a table with the display name “Reservation,” but Power Platform also made an internal table name. Use Power Platform’s name for the Primary Entity.

Image 5

Choose the service endpoint registered as the event handler.

Verifying Service Endpoint Registration

Everything is ready for Event Hub to fire when a record in the reservation table changes. Now, we need to verify the event registration is successful.

Test it using the Power App by editing a guest’s reservation.

Then, to confirm an event fired, go to the Power Apps Maker Portal. Click on the Settings gear and choose Advanced settings to go to the Dynamics 365 settings page.

Image 6

From the dropdown, choose System > System Jobs.

If the change was successful, “Checking in a guest” should appear next to the specific reservation code (the primary key) in the log.

Image 7

That’s all we need to do to take what the citizen developer has done and process it into the hotel’s backend. Notice that it didn’t require a single line of code!

Consuming the Event

Developers can create a Function app that responds to Event Hub triggers to consume the event. We can create a Function app and deploy it to Azure with the Azure Functions Tools extension using Visual Studio (VS) Code.

This action creates an Azure icon on the side panel. We can then directly create a project and a Function using the buttons on the pane.

This tutorial will create a Python app as an example, but any supported language works. The important setting here is to use the Event Hub trigger.

Image 8

First, follow the prompts to create a Python app using Event Hub Triggers, pointing to the Event Hub namespace from earlier. This action creates a JSON file with default properties.

Then, update the connection string to the Event Hub namespace. The connection string is from the namespace creation’s Shared Access Policies tab.

Finally, update the code to do something with the event. In this example, it will post the data to a temporary webhook.

Before deployment, ensure requirements.txt contains the necessary libraries for this project: azure-functions and requests. When VS code creates the project, it includes azure-functions. The requests library will make POST requests to a mock endpoint.

azure-functions
requests

This code sample passes the changed fields to a mock endpoint:

Python
from typing import List
import logging
import azure.functions as func
import json
import requests

def main(events: List[func.EventHubEvent]):
    logging.info('Started Function app')
    for event in events:
        body=event.get_body()
        # Convert the raw data into a dict struct by parsing JSON
        jsonContent = body.decode('utf-8')
        jsn = json.loads(jsonContent)

        # Take the input parameters from the incoming message
        inputParams = jsn['InputParameters'][0]['value']['Attributes']
        # Take the identifiers that identifies the reservation in the SQL database
        identifiers = jsn['PostEntityImages'][0]['value']['Attributes']

        # Create a payload that includes both the changed values and identifiers
        payload = {}
        payload['values'] = inputParams
        payload['ids'] = identifiers
 
        r = requests.post('https://webhook.site/4d2e2587-8d82-4605-ad06-47ad29827184', \
                           data=json.dumps(payload))

        message = body['MessageName']
        logging.info('Python EventHub trigger processed message: \
                      %s with input parameters %s', message, inputParams)

Deserializing event.get_body() helps analyze the entire event message. Then, the code extracts the Dataverse Update event’s changed attributes from the first element within InputParameters’ attribute values.

Next, deploy the function app. Then, test it by checking in another guest using the UI app. A post request will appear on the mock endpoint.

The sample JSON here shows that it contains all the required information in the InputParameters property:

JSON
{
    "values":[
        {
            "key":"cr7ec_checkintime",
            "value":"/Date(1631599320000)/"
        },
        {
            "key":"cr7ec_reservationid",
            "value":"1e7ac787-c077-ec11-8942-000d3a0c84c3"
        },
        {
            "key":"timezoneruleversionnumber",
            "value":0
        },
        {
            "key":"modifiedon",
            "value":"/Date(1643556032000)/"
        },
        ...
    ],
    "ids":[
        {
            "key":"cr7ec_reservationcode",
            "value":"CRX58345"
        },
        {
            "key":"cr7ec_reservationid",
            "value":"1e7ac787-c077-ec11-8942-000d3a0c84c3"
        }
    ]
}

The endpoint can use an identifier to point to the reservation (via reservation code) and the modified fields, then update the reservation’s status in the company’s SQL database.

The deployed Function app reacts to reservation table entry changes.

Next Steps

We’ve successfully created a Function app to react to changes in the UI app without changing anything in the UI app. So, the citizen developer can continue to modify the UI app in the Power Apps platform without involving the professional developer.

This approach is a big plus, as the citizen developer can adjust the app to meet fast-changing business requirements without having code proficiency or touching the backend system.

Continue to the final article to learn how we can add data to the system. The tutorial will explore inserting data into the Reservation Dataverse table then expand the UI app to include information about a guest’s previous visits.

To learn how to accelerate foundational app development, check out The Developer’s 7-Step Guide to Low-Code App Development.

This article is part of the series 'Fusion Development for Hospitality View All

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --