Category: UI5 Integrations

  • Scan Bar Code Integration in SAP UI5

    Introduction

    In SAP’s world, the UI5 and Fiori Apps are used extensively to perform a large number of operations. Among these operations, there is a common requirement of a warehouse to scan a barcode pasted over a material and get the material number from it. It is similar to the bar code scanning you might have seen at a shopping mall outlet. In this article, we will learn simple steps for Scan Bar Code Integration in SAP UI5

    Pre requisite of Bar Code Scanning in SAP UI5 via Mobile

    The bar code scanning works fine on a laptop, but to make it work on a mobile phone or a tablet, you need to deploy your UI5 application as a Fiori Application. The fiori application should be used via the Fiori Launchpad mobile application. You can download the same from here:

    SAP Mobile Start: Fiori Launchpad for Android

    SAP Mobile Start: Fiori Launchpad for iOS

    Steps to create an SAP UI5 to scan a barcode

    To create a scanning app, follow the steps below:

    1. Create a UI5 project in any IDE

    2. Create a view and add a button to start scanning, and an input box to get the scanned data. The code would be like mentioned below:

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core"
        xmlns:html="http://www.w3.org/1999/xhtml">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Scan Bar Code Integration in SAP UI5">
                        <content>
                            <VBox>
                                <Button icon="sap-icon://bar-code" text="Scan" press="onScan"/>
                                <Label text="Material"/>
                                <Input id="materialNumber" value=""/>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

    Step 03: Add BarcodeScanner namespace and use it to scan the bar code, as shown below:

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox",
        "sap/m/MessageToast",
        "sap/ui/model/json/JSONModel",
        "sap/ndc/BarcodeScanner",
    ], function (Controller, MessageBox, MessageToast, JSONModel, BarcodeScanner) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            onScan: function (oEvent) {
                var that = this;
                BarcodeScanner.scan(
                    function (mResult) {
                        if (!mResult.cancelled) {
                            that.getView().byId("materialNumber").setValue(mResult.text);
                            MessageBox.show("We got a bar code\n" +
                                "Result: " + mResult.text + "\n" +
                                "Format: " + mResult.format + "\n");
                        }
                    },
                    function (Error) {
                        alert("Scanning failed: " + Error);
                    }
                );
            },
    
        });
    });

    Note: If your scanning is not getting started, turn on the given extension in WebIDE:

    Hybrid App Toolkit

    Output

    Before Scanning

    Scan Bar Code Integration in SAP UI5 Before Scanning

    During Scanning

    Scan Bar Code Integration in SAP UI5 During Scanning

    After Scanning

    Scan Bar Code Integration in SAP UI5 After Scanning

  • Quantum Random Number Generation in SAP UI5

    Preface – This post is part of the UI5 Integration Programs series.

    Introduction

    A quantum random number is a number generated using a quantum-mechanical process, which is inherently unpredictable. In classical computing, random numbers are generated using algorithms that are deterministic, meaning they use a predetermined set of rules to produce the numbers. However, these deterministic algorithms can be prone to biases or patterns, which makes them not truly random.

    In contrast, quantum random number generators (QRNGs) use the principles of quantum mechanics to produce truly random numbers. One such process is the measurement of a quantum system, such as a photon, that has properties that are inherently uncertain. The outcome of this measurement is truly random and can be used to generate a random number.

    QRNGs are important for many applications in cryptography, simulations, and other fields that require high-quality random numbers. They are also used in quantum key distribution protocols, where two parties use a shared set of random numbers to generate a secret key for secure communication.

    It’s worth noting that not all random number generators based on quantum mechanics are truly random. Some so-called “pseudo-random number generators” use a deterministic process but rely on the inherent randomness of the physical processes involved, such as the thermal noise in a resistor, to produce random numbers. While these generators are not truly random, they are still useful for many applications where high-quality randomness is not required.

    What is Quantum Random Number Generation?

    Quantum random number generation is the process of generating truly random numbers using quantum-mechanical processes. Unlike classical methods of generating random numbers that are based on algorithms and pseudorandom number generators, quantum random number generation produces numbers that are truly unpredictable and cannot be replicated.

    The basic principle behind quantum random number generation is that quantum-mechanical phenomena, such as the polarization of photons or the decay of radioactive atoms, have inherent randomness that cannot be predicted. By measuring these phenomena, one can generate a sequence of numbers that are truly random.

    There are several different methods for generating random numbers using quantum-mechanical processes, including:

    1. Photon-based quantum random number generators, which use the polarization of photons to generate random numbers.
    2. Vacuum fluctuation-based quantum random number generators, which use the random fluctuations in the vacuum of space to generate random numbers.
    3. Radioactive decay-based quantum random number generators, which use the unpredictable decay of radioactive atoms to generate random numbers.

    These methods are based on different quantum-mechanical phenomena, but they all share the same basic principle of using the inherent randomness of quantum mechanics to generate truly random numbers.

    Quantum random number generators have many important applications in cryptography, simulation, and other fields that require high-quality randomness. They are also a key component in quantum key distribution, where two parties use a shared set of random numbers to generate a secret key for secure communication.

    Difference between Quantum Random Number Generation and Random Number Generation

    The main difference between quantum random number generation and random number generation is in the source of the randomness. Random number generation refers to any method of generating numbers that appear random, regardless of the source of that randomness. In contrast, quantum random number generation specifically refers to the use of quantum-mechanical processes to generate truly random numbers.

    Classical methods of random number generation, such as pseudorandom number generators (PRNGs), use algorithms to generate a sequence of numbers that appear random but are actually deterministic. PRNGs start with a seed value, and then use a mathematical formula to generate a sequence of numbers that, while not truly random, appear random and are suitable for many applications.

    In contrast, quantum random number generation uses the inherent randomness of quantum-mechanical processes, such as the polarization of photons or the decay of radioactive atoms, to generate truly random numbers that cannot be predicted or replicated. Quantum random number generation provides a higher level of randomness than classical methods and is important for applications that require the highest level of security and unpredictability, such as in cryptography.

    Another difference between the two methods is the speed at which they can generate random numbers. Quantum random number generation is typically slower than classical methods, due to the time it takes to measure the quantum-mechanical processes involved. This makes it less suitable for applications that require large amounts of random data to be generated quickly, such as in simulations or games. In contrast, classical random number generators can generate large amounts of random data quickly, making them better suited for such applications.

    In summary, the main difference between quantum random number generation and classical random number generation is the source of the randomness. Quantum random number generation uses the inherent unpredictability of quantum-mechanical processes to generate truly random numbers, while classical methods use deterministic algorithms to generate numbers that appear random.

    How can we Generate Quantum Random Numbers?

    Quantum random numbers can be generated using various methods based on the inherent randomness of quantum-mechanical processes. Here are three common methods of generating quantum random numbers:

    1. Photon-Based Quantum Random Number Generation: In this method, random numbers are generated by measuring the polarization of photons. A polarizing beam splitter is used to split a single photon into two orthogonal polarizations. The measurement of one of the polarizations is used to generate a random number. Since the polarization of the photon is a quantum-mechanical process that is inherently random, the resulting numbers are also random.
    2. Vacuum Fluctuation-Based Quantum Random Number Generation: This method utilizes the random fluctuations in the vacuum of space to generate random numbers. The energy of these fluctuations is measured using a device called a quantum noise generator, and the resulting measurements are used to generate random numbers.
    3. Radioactive Decay-Based Quantum Random Number Generation: In this method, the unpredictable decay of radioactive isotopes is used to generate random numbers. A radioactive source is used to emit particles, and the time between emissions is used to generate random numbers. Since the decay of the radioactive isotopes is a quantum-mechanical process that is inherently random, the resulting numbers are also random.

    It is important to note that generating high-quality random numbers requires careful design and implementation of the experimental setup. Any imperfections or biases in the measurement apparatus can potentially introduce biases into the generated numbers. Therefore, careful calibration and verification are necessary to ensure the randomness and quality of the generated numbers.

    Quantum random number generators have important applications in cryptography, simulation, and other fields that require high-quality randomness. They are also a key component in quantum key distribution, where two parties use a shared set of random numbers to generate a secret key for secure communication.

    What is Qrypt?

    Qrypt is a company that provides a quantum-based security solution using quantum key distribution (QKD) to secure communications between two parties. The Qrypt system includes a QKD device, a trusted node, and secure communication channels. Here’s an overview of the Qrypt setup:

    1. QKD Device: The QKD device is a specialized hardware device that generates and distributes the quantum keys used for secure communication. The device generates the keys by measuring the polarization of individual photons or other quantum-mechanical properties. The keys are then transmitted to the trusted node over a quantum channel, which ensures the keys are transmitted securely and cannot be intercepted or measured without detection.
    2. Trusted Node: The trusted node receives the quantum keys from the QKD device and performs error correction and privacy amplification to ensure the keys are secure and error-free. The trusted node then sends the final keys to the communication endpoints over a classical channel, which can be any secure communication channel, such as an internet connection, optical fiber, or a satellite link. The trusted node is a critical component of the system, as it ensures the integrity and security of the generated keys.
    3. Secure Communication Channels: The final keys are used to secure the communication channels between the two parties. The keys are used to encrypt the data, ensuring that only the intended recipient can decrypt and read the message. The communication channels can be any secure communication channel, such as a virtual private network (VPN), encrypted email, or a secure messaging app.

    The Qrypt system is designed to provide secure communication channels that cannot be intercepted or decrypted by any third party, even if they have the most advanced computing resources available. The system is based on the fundamental principles of quantum mechanics and provides a high level of security and privacy for sensitive communications.

    Setup of Qrypt

    To setup Qrypt, follow the given steps:

    1. Visit https://portal.qrypt.com
    Qrypt portal

    2. Enter your details are create your account, you will land on your dashboard:
    Qrypt Dashboard

    3. Go to Token, and provide values as below to generate one for yourself:
    Generate Entropy Token

    4. Save the generated token somewhere locally, and it will be used in the integration later:
    Save your token

    5. You can check all your tokens as shown below:
    Token Created

    SAP UI5 Integration with Quantum Random Number Generator Qrypt

    Before you start with the development in UI5, test the same in Postman with given data:
    Type: Get
    URL: https://api-eus.qrypt.com/api/v1/quantum-entropy?size=1
    Authorization Type: Bearer Token
    Token Value: <Your Generated token>
    The postman output will look like this:

    Postman Output

    Now, implement the following:

    View.xml

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core"
    xmlns:html="http://www.w3.org/1999/xhtml">
    <Shell id="shell">
    <App id="app">
    <pages>
    <Page id="page" title="Quantum Random Number Generation in SAP UI5">
    <content>
    <VBox>
    <Button text="Generate Qunatum Random Number" press="onPressGenerate"/>
    <Title text="Response"/>
    <TextArea id="idText" height="500px" width="100%"/>
    </VBox>
    </content>
    </Page>
    </pages>
    </App>
    </Shell>
    </mvc:View>

    Controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox",
        "sap/m/MessageToast"
    ], function (Controller, MessageBox, MessageToast) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            onPressGenerate: function () {
                var that = this;
                // Specfify entropy token, requested size of entropy, and subdomain
                var accesstoken =
                    'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjM3Y2FiNjNkNzFiMzRmMWNhMDQ5N2VhMWViNjhiYjE3In0.eyJleHAiOjE2NzY4Mzg4MzcsIm5iZiI6MTY3Njc1MjQzNywiaXNzIjoiQVVUSCIsImlhdCI6MTY3Njc1MjQzNywiZ3JwcyI6WyJQVUIiXSwiYXVkIjpbIlJQUyJdLCJybHMiOlsiUk5EVVNSIl0sImNpZCI6Im9pd3MyV01xT0ZyQmNMX1VyNUl5XyIsImR2YyI6IjE0NTU1NzBhZjE3OTRmN2FhZDRkM2ZjYWI3MmE2ZmVhIiwianRpIjoiNGEyYTU4OTNlYmQxNGM3OWE1NjdmMmJjNTU1ODE4YmMiLCJ0eXAiOjN9.l1NajDLH-qLrQPa6_WrxuqCBwbjXPafamRXvJvbriZPe4KOb-tI3um8a7-Ce6xfSYVAbTb0aOgHGNst_qda3bg'
                var kibData = 1;
                var sub = 'api-weu'; //api-eus is for Eastern United States and api-weu is for Western Europe
    
                var settings = {
                    "url": "https://cors-anywhere.herokuapp.com/https://api-eus.qrypt.com/api/v1/quantum-entropy?size=1",
                    "method": "GET",
                    "timeout": 0,
                    "headers": {
                        "Authorization": "Bearer eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjM3Y2FiNjNkNzFiMzRmMWNhMDQ5N2VhMWViNjhiYjE3In0.eyJleHAiOjE2NzY4Mzg4MzcsIm5iZiI6MTY3Njc1MjQzNywiaXNzIjoiQVVUSCIsImlhdCI6MTY3Njc1MjQzNywiZ3JwcyI6WyJQVUIiXSwiYXVkIjpbIlJQUyJdLCJybHMiOlsiUk5EVVNSIl0sImNpZCI6Im9pd3MyV01xT0ZyQmNMX1VyNUl5XyIsImR2YyI6IjE0NTU1NzBhZjE3OTRmN2FhZDRkM2ZjYWI3MmE2ZmVhIiwianRpIjoiNGEyYTU4OTNlYmQxNGM3OWE1NjdmMmJjNTU1ODE4YmMiLCJ0eXAiOjN9.l1NajDLH-qLrQPa6_WrxuqCBwbjXPafamRXvJvbriZPe4KOb-tI3um8a7-Ce6xfSYVAbTb0aOgHGNst_qda3bg"
                    },
                };
    
                $.ajax(settings).done(function (response) {
                    console.log(response);
                    that.byId("idText").setValue(response);
                });
    
            }
        });
    });

    Note: Since browser doesn’t allow CORS, hence we have added https://cors-anywhere.herokuapp.com/ before our URL, to fix this. This is a temporary fix and the right way is to use Destination in SAP BTP.

    Output

    Quantum Random Number Generation in SAP UI5

  • Chat on WhatsApp button Integration in SAP UI5

    Preface – This post is part of the UI5 Integration Programs series.

    Introduction

    WhatsApp is a messaging app that allows users to communicate with each other through text-based chat, voice and video calls, and other multimedia features. The chat function on WhatsApp is one of its main features and is used by users to have conversations with their contacts.

    To start a chat on WhatsApp, you first need to have the app installed on your device and have an active account. Once you have the app open, you can navigate to the chat tab, where you will see a list of all your existing chats.

    To start a new chat, you can tap the “New Chat” button and then select the contact you want to chat with. You can also create a group chat with multiple contacts by selecting the “New Group” option.

    Once you are in a chat, you can type your message in the text box at the bottom of the screen and press the send button to send it. You can also use other features such as emojis, stickers, and GIFs to enhance your messages. If you want to make a voice or video call, you can use the call button at the top of the screen.

    WhatsApp also offers end-to-end encryption, which means that your messages are secure and can only be seen by you and the recipient. You can also customize your chat settings, such as notifications and chat backgrounds, to make your chatting experience more personalized.

    Overall, the chat function on WhatsApp is a simple and easy-to-use feature that allows users to communicate with their contacts in a fast and secure way.

    What is Chat on WhatsApp API

    WhatsApp API is a platform provided by WhatsApp that allows businesses to interact with their customers through the messaging app. The Chat function on WhatsApp API allows businesses to create and manage conversations with their customers using a programmable interface.

    With WhatsApp API, businesses can use their own applications to send and receive messages, media, and other types of content with their customers. This can include sending order confirmations, shipping notifications, and customer support messages. The chat function on WhatsApp API also allows businesses to automate certain parts of the conversation using chatbots, which can provide customers with quick answers to frequently asked questions.

    To use the Chat function on WhatsApp API, businesses need to have an approved WhatsApp Business Account and an integration with the WhatsApp Business API. Once these requirements are met, businesses can access the Chat API documentation and start building their chatbots and other messaging features.

    The Chat function on WhatsApp API is a powerful tool for businesses that want to reach their customers where they are, in a fast and convenient way. It can help businesses provide better customer support, increase engagement, and streamline their communication processes.

    How to use click to chat for WhatsApp

    Click to Chat is a feature on WhatsApp that allows you to create a link that, when clicked, opens a new chat with a specific phone number or contact. This can be useful if you want to make it easy for people to start a conversation with you on WhatsApp, without having to add your phone number to their contacts.

    To use Click to Chat for WhatsApp, follow these steps:

    1. Open your web browser and go to https://wa.me/ followed by the phone number you want to chat with in international format, without any spaces or symbols. For example, if the phone number is +1 (555) 123-4567, the link should be https://wa.me/15551234567.
    2. Hit the “Enter” key or click “Go” to load the link.
    3. If the phone number is associated with an active WhatsApp account, a new chat window will open with the phone number already entered.
    4. If the phone number is not associated with an active WhatsApp account, an error message will appear.

    You can also add a message to the link by adding ?text= followed by the message you want to send. For example, if you want to send a message that says “Hello, how can I help you?”, the link should be https://wa.me/15551234567?text=Hello,%20how%20can%20I%20help%20you%3F.

    Note that Click to Chat links can be shared on social media, email, websites, or any other platform where links can be posted. However, it’s important to be cautious when sharing your phone number or WhatsApp account information online, and to only share it with people or organizations you trust.

    How to Integrate Chat on WhatsApp button in SAP UI5

    To integrate WhatsApp in SAP UI5, you need to use the “click to chat” option, we have implemented as below:

    View.xml

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core"
        xmlns:html="http://www.w3.org/1999/xhtml">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Chat on WhatsApp button Integration in SAP UI5">
                        <content>
                            <Input id="idNumber" value="" placeholder="Enter a number with country code"/>
                            <Input id="idText" value="" placeholder="Enter a text to send"/>
                            <Image width="20%" src="./view/whatsapp.png" press="handleWhatsAppPress"/>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

    Controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox",
        "sap/m/MessageToast"
    ], function (Controller, MessageBox, MessageToast) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            handleWhatsAppPress: function () {
                var number = this.byId("idNumber").getValue();
                var text = this.byId("idText").getValue();
                // for Mobile Phone
                // var url = 'https:' + '//wa.me/' + number + '?text=' + text;
                // for Web Whatsapp
                var url = 'https:' + '//web.whatsapp.com/send/?phone=' + number + '&text=' + text + '&type=phone_number&app_absent=0';
                sap.m.URLHelper.redirect(url, true);
                // eg. +917070022222
            }
        });
    });

    Note: Remember to add an image in your view (or other) folder, we have added the image with name ‘whatsapp.png’.

    Output

    Chat on WhatsApp button Integration in SAP UI5

  • Video Call Integration in SAP UI5

    Preface – This post is part of the UI5 Integration Programs series.

    Introduction

    Video call is a feature that allows two or more people to communicate with each other using real-time video and audio transmissions over the internet. It allows people to connect and interact with each other, regardless of their physical location, by transmitting live video and audio signals through a digital network.

    Video calls can be made using a variety of devices, such as smartphones, tablets, laptops, desktop computers, and specialized video conferencing equipment. To make a video call, both parties must have compatible devices and access to the internet, either through Wi-Fi or mobile data.

    During a video call, the camera on each device captures live video of the person or people on the other end of the call, which is then transmitted over the internet to the other device. Similarly, the microphone on each device captures the audio of the person speaking, which is also transmitted over the internet to the other device.

    Video calling has become increasingly popular in recent years, as it provides a more personal and engaging way to communicate than traditional phone calls or text-based messaging. It’s often used for personal communication between family and friends, as well as for professional purposes such as virtual meetings, job interviews, and remote work collaboration.

    What is a video calling feature in a Web application?

    A video calling feature in a web application is a software functionality that allows users to initiate and participate in live video calls directly within a web browser. It enables people to have real-time audio and video communication through their desktop, laptop, or mobile device without the need for any additional software or hardware.

    To use the video calling feature in a web application, users typically need a compatible web browser, a webcam, a microphone, and a stable internet connection. Once the user has these components set up, they can initiate or join a video call with another user or a group of users in the web application.

    Web-based video calling is often integrated with other communication features such as instant messaging, screen sharing, and file sharing. It is commonly used for virtual meetings, remote work collaboration, online learning, and social communication.

    Web-based video calling can be done using various web technologies, including WebRTC (Web Real-Time Communication), which is an open-source project that enables real-time communication between browsers, and other proprietary solutions. Some popular examples of web-based video calling platforms include Zoom, Google Meet, Microsoft Teams, and Skype.

    What all ways can we integrate video calling feature in a Web Application?

    There are various ways to integrate a video calling feature in a web application, some of which include:

    1. WebRTC: WebRTC (Web Real-Time Communication) is a free, open-source project that enables real-time communication between browsers. It provides the necessary APIs for web developers to implement video calling directly in their web applications, without requiring additional software or plugins.
    2. Using third-party APIs and SDKs: Many video calling platforms, such as Zoom, Google Meet, and Twilio, provide APIs and SDKs that developers can use to integrate video calling features into their web applications.
    3. Building a custom solution: Developers can build a custom solution for video calling by leveraging various web technologies such as WebSockets, Node.js, and socket.io. This requires extensive development and testing but allows for greater customization and control over the video calling experience.
    4. Using a pre-built solution: There are also pre-built video calling solutions available that can be easily integrated into web applications, such as Agora.io, Vonage Video API, and Daily.co. These solutions typically offer a range of features, including screen sharing, recording, and chat, and can be customized to fit the specific needs of a web application.

    The choice of integration method will depend on factors such as the level of customization required, the budget and resources available, and the specific features needed for the web application.

    What is the concept of WebRTC API?

    WebRTC (Web Real-Time Communication) is a free, open-source project that enables real-time communication between browsers and mobile applications. It provides a set of JavaScript APIs that allow developers to integrate real-time communication capabilities, such as video and audio calling, directly into their web applications without requiring any additional software or plugins.

    WebRTC’s core components include:

    1. getUserMedia: This API allows web applications to access a user’s camera and microphone, enabling them to capture audio and video data.
    2. RTCPeerConnection: This API allows web applications to establish a peer-to-peer connection between browsers or mobile devices, enabling real-time communication of audio and video data.
    3. RTCDataChannel: This API allows web applications to create a bi-directional, low-latency communication channel for sending arbitrary data between peers.

    Together, these APIs form the basis of WebRTC and enable developers to build real-time communication features directly into their web applications. WebRTC is supported by all major browsers, including Google Chrome, Mozilla Firefox, Apple Safari, and Microsoft Edge, and is used for a variety of applications, including video conferencing, voice calling, and file sharing.

    WebRTC also offers a secure, end-to-end encrypted communication channel, ensuring that user data is protected during transmission. Because it’s an open-source project, WebRTC is constantly evolving, and new features and functionalities are being added all the time.

    Video Integration using Agora Web SDK

    Agora Web SDK is a software development kit that enables developers to integrate real-time video and audio communication into their web applications. Here’s how to integrate video using Agora Web SDK:

    1. Create an Agora developer account and generate an App ID: To use Agora Web SDK, you need to create an account on the Agora platform and generate an App ID, which is used to authenticate your application and enable access to the Agora services.
      Agora Video CallingOur goal here is to create a project within Agora and get App ID, Channel and Token. In our usecase, we have got these:

      App ID: 09ed05f4f81d4ec580c45277ab70dac5
      Channel: ui5Demo
      Token: 007eJxTYND+53eO3bl+x9yax6cU1HLqHHZKN/5+f2LLwvXr/s9Luu6vwGBgmZpiYJpmkmZhmGKSmmxqYZBsYmpkbp6YZG6QkphsOvXN++SGQEaGo1P+MzMyQCCIz85Qmmnqkpqbz8AAAJQWJIA=

       

    2. Add the Agora Web SDK to your project: Once you have an App ID, you can add the Agora Web SDK to your project by including the Agora JavaScript library in your HTML code.
      These are the script for that:

      <!-- Agora Scripts -->
      <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
      <script src="https://download.agora.io/sdk/release/AgoraRTC_N.js"></script>

       

    3. Initialize the Agora client: The next step is to initialize the Agora client in your JavaScript code using the App ID and other necessary parameters.
    4. Create a video call: To create a video call, you need to create a video call object that contains the necessary configuration parameters, such as the channel name, mode, and codec. Then, you can join the call by calling the Agora RTC client join method.
    5. Manage the video call: Once the call is established, you can use the Agora SDK to manage the call, including starting and stopping video streams, muting and unmuting audio, and sharing the screen.
    6. Clean up: Finally, when the call is complete, you can use the Agora SDK to release the resources and terminate the call.

    Agora Web SDK provides a range of additional features and functionalities, including the ability to customize the user interface, integrate with third-party services, and control the quality of service. By integrating video using Agora Web SDK, you can add real-time communication capabilities to your web application, enabling users to connect with each other in a more immersive and engaging way.

    How to integrate Video Calling feature in SAP UI5?

    To Integrate a Video calling in SAP UI5, we will 3rd party API of Agora and the concept of WebRTC API. Please find the respective code below:

    HTML Code:

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <!--<meta name="viewport" content="width=device-width, initial-scale=1.0">-->
            <title>My Project Ideas</title>
             <link rel="icon" type="image/x-icon" href="https://myprojectideas.com/wp-content/uploads/2021/08/cropped-Screenshot-2021-07-26-at-1.39.04-PM-32x32.png">
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"Test.Test": "./"}'
                data-sap-ui-compatVersion="edge"
                data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
                data-sap-ui-async="true"
                data-sap-ui-frameOptions="trusted">
            </script>
              <!-- Agora Scripts -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://download.agora.io/sdk/release/AgoraRTC_N.js"></script>
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="Test.Test" data-id="container" data-settings='{"id" : "Test"}'></div>
        </body>
    </html>

    View Code:

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core"
        xmlns:html="http://www.w3.org/1999/xhtml">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Video Call Integration in SAP UI5">
                        <content>
                            <core:HTML class="sapUiLargeMargin"
                                content='&lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;participant&quot; id=&quot;participant&quot;&gt;&lt;/div&gt; &lt;div class=&quot;fs&quot; id=&quot;fs&quot;&gt;&lt;/div&gt; &lt;/div&gt;'></core:HTML>
                        </content>
                        <footer >
                            <OverflowToolbar>
                                <Button id="idRemaining" type="Emphasized"/>
                                <ToolbarSpacer/>
                                <Button icon="sap-icon://popup-window" class="sapUiTinyMarginBeginEnd" text="Share Screen" press="onShareScreen"/>
                                <Button id="idMute" icon="sap-icon://sound-off" class="sapUiTinyMarginEnd" text="Mute" press="onPressMute"/>
                                <Button id="idUnmute" visible="false" class="sapUiTinyMarginEnd" icon="sap-icon://sound-loud" text="Unmute" press="onPressUnmute"/>
                                <Button type="Reject" text="Close Call" press="closeCall">
                                    <layoutData><OverflowToolbarLayoutData priority="NeverOverflow"/></layoutData>
                                </Button>
                            </OverflowToolbar>
                        </footer>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

    Controller Code:

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox",
        "sap/m/MessageToast"
    ], function (Controller, MessageBox, MessageToast) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            onAfterRendering: async function (evt) {
                var that = this;
                this.flag = 0;
                try {
                    var that = this;
                    var date = new Date();
                    var startTime = date.getTime();
                    this.appointmentURL = {
                        startTime: startTime,
                        channel: "ui5Demo",
                        token: "007eJxTYND+53eO3bl+x9yax6cU1HLqHHZKN/5+f2LLwvXr/s9Luu6vwGBgmZpiYJpmkmZhmGKSmmxqYZBsYmpkbp6YZG6QkphsOvXN++SGQEaGo1P+MzMyQCCIz85Qmmnqkpqbz8AAAJQWJIA="
                    };
                    this.timeOut = setInterval(function () {
                    that.alertFunc()
                    }.bind(that), 1000);
                    that.rtc = {
                        // For the local audio and video tracks.
                        localAudioTrack: null,
                        localVideoTrack: null,
                    };
                    if (this.appointmentURL) {
                        var options = {
                            // Pass your app ID here.
                            appId: "09ed05f4f81d4ec580c45277ab70dac5",
                            // Set the channel name.
                            channel: this.appointmentURL.channel,
                            // Set the user role in the channel.
                            role: "host"
                        };
                        var token = this.appointmentURL.token;
                    }
                    that.client = AgoraRTC.createClient({
                        mode: "rtc",
                        codec: "vp8"
                    });
                    var uid = "doctor";
                    var div = document.createElement("div");
                    div.id = uid;
                    div.className = "zoomOut"
                    that.client.on("user-left", async(user, mediaType) => {
                        var elem = document.getElementById("id" + user.uid);
                        elem.parentElement.removeChild(elem);
                        console.log("left");
                    });
                    that.client.on("user-published", async(user, mediaType) => {
                        await that.client.subscribe(user, mediaType);
                        console.log("subscribe success");
                        var uuid = "id" + user.uid;
                        if (document.getElementById(uuid) == undefined) {
                            var div = document.createElement("div");
                            div.id = uuid;
                            if (that.flag === 0) {
                                div.className = "zoomIn"
                            } else {
                                div.className = "zoomOut"
                            }
                            that.buttonUID = uuid;
                            var button = document.createElement("button");
                            if (that.flag === 0) {
                                button.innerHTML = "Unpin";
                            } else {
                                button.innerHTML = "Pin";
                            }
                            button.className = "zoomButton";
                            that.flag = 1;
                            button.addEventListener("click", function (oEvent) {
                                var a = document.getElementById(uuid).className;
                                if (a == "zoomOut") {
                                    if (document.getElementsByClassName("zoomIn").length > 0) {
                                        document.getElementsByClassName("zoomIn")[0].className = "zoomOut";
                                    }
                                    document.getElementById(uuid).className = "zoomIn";
                                    oEvent.currentTarget.innerHTML = "Unpin";
                                    var allButtons = document.getElementsByClassName("zoomOut");
                                    for (var i = 1; i < allButtons.length; i++) {
                                        var reqButton = allButtons[i].getElementsByClassName("zoomButton");
                                        if (reqButton.length > 0) {
                                            reqButton[0].style.display = "none";
                                        }
                                    }
                                } else {
                                    document.getElementById(uuid).className = "zoomOut";
                                    oEvent.currentTarget.innerHTML = "Pin";
                                    var allButtons = document.getElementsByClassName("zoomOut");
                                    for (var i = 1; i < allButtons.length; i++) {
                                        var reqButton = allButtons[i].getElementsByClassName("zoomButton");
                                        if (reqButton.length > 0) {
                                            reqButton[0].style.display = "block";
                                        }
                                    }
                                }
    
                            });
                            div.appendChild(button);
                            document.getElementById("participant").appendChild(div);
                        }
                        const remoteVideoTrack = user.videoTrack;
                        that.remotePlayerContainer = document.getElementById(uuid);
                        remoteVideoTrack.play(that.remotePlayerContainer);
                        if (mediaType === "audio") {
                            const remoteAudioTrack = user.audioTrack;
                            remoteAudioTrack.play();
                        }
    
                    });
                    document.getElementById("participant").appendChild(div);
                    // that.client.setClientRole(options.role);
                    await that.client.join(options.appId, options.channel, token, 0);
                    that.rtc.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();
                    that.rtc.localVideoTrack = await AgoraRTC.createCameraVideoTrack();
                    await that.client.publish([that.rtc.localAudioTrack, that.rtc.localVideoTrack]);
                    that.localPlayerContainer = document.getElementById(uid);
                    that.rtc.localVideoTrack.play(that.localPlayerContainer);
                    // Users joins for the first time
    
                } catch (error) {
                    console.log(error);
                    var errorMessage;
                    // Handle Errors here.
                    if (error && error.message) {
                        errorMessage = error.message;
                        if (error.code == 'CAN_NOT_GET_GATEWAY_SERVER') {
                            errorMessage = "The meeting session is no longer valid. Contact Admin";
                        }
                    } else {
                        errorMessage = "Something went wrong, contact Admin if the error persists";
                    }
                    MessageBox.error(errorMessage, {
                        actions: [MessageBox.Action.CLOSE],
                        onClose: function (sAction) {
                            if (sAction == 'CLOSE') {
                                // Write close operation
                            }
                        }
                    });
                };
            },
    
            onCancelCall: function (oEvent) {
                this.closeCall();
            },
    
            onMarkCompleteCall: function (oEvent) {
                this.closeCall();
            },
    
            closeCall: async function (oEvent) {
                var that = this;
                var date = new Date();
                var endTime = date.getTime();
                if (that.rtc) {
                    that.rtc.localAudioTrack.close();
                    // that.rtc.localVideoTrack.stop();
                    that.rtc.localVideoTrack.close();
                    // Traverse all remote users.
                    // Destroy the dynamically created DIV containers.
                    const playerContainer = document.getElementById('div2');
                    playerContainer && playerContainer.remove();
                    // Leave the channel.
                    await that.client.leave();
                }
            },
    
            alertFunc: function () {
                var that = this;
                var countDownDate = that.appointmentURL.startTime;
                // Get today's date and time
                var now = new Date().getTime();
                var endTime = "10-22-05";
                // Find the distance between now and the count down date
                var distance = now - countDownDate;
    
                // Time calculations for days, hours, minutes and seconds
                var hours = that.doubleDigit(Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)));
                var minutes = that.doubleDigit(Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)));
                var seconds = that.doubleDigit(Math.floor((distance % (1000 * 60)) / 1000));
                var timeRemaining =
                    new Date('01/01/2007 ' + endTime.split('-')[1] + ':00').getTime() -
                    new Date('01/01/2007 ' + endTime.split('-')[0] + ':00').getTime();
                var diff = Math.abs(
                    Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60)),
                );
    
                that.getView().byId("idRemaining").setText(hours + ':' + minutes + ':' + seconds);
                if (minutes > diff) {
                    that.getView().byId("idRemaining").setType("Critical");
                }
            },
    
            doubleDigit: function (time) {
                return ("0" + time).slice(-2);
            },
    
            onShareScreen: async function (oEvent) {
                var that = this;
                if (this.appointmentURL) {
                    var appId = "09ed05f4f81d4ec580c45277ab70dac5";
                    var channel = this.appointmentURL.channel;
                    var token = this.appointmentURL.token;
                }
                const screenClient = AgoraRTC.createClient({
                    mode: "rtc",
                    codec: "vp8"
                });
                await screenClient.join(appId, channel, token);
                const screenTrack = await AgoraRTC.createScreenVideoTrack();
                await screenClient.publish(screenTrack);
                return screenClient;
            },
    
            onPressMute: function (oEvent) {
                this.byId("idMute").setVisible(false);
                this.byId("idUnmute").setVisible(true);
                this.rtc.localAudioTrack.setEnabled(false);
            },
    
            onPressUnmute: function (oEvent) {
                this.byId("idMute").setVisible(true);
                this.byId("idUnmute").setVisible(false);
                this.rtc.localAudioTrack.setEnabled(true);
            },
    
            onPressZoomIn: function (oEvent) {
                var divID = oEvent.getSource().data("divID");
                document.getElementById(divID).style.width = "640px";
                document.getElementById(divID).style.height = "480px";
            },
    
            onPressZoomOut: function (oEvent) {
                var divID = oEvent.getSource().data("divID");
                document.getElementById(divID).style.width = "320px";
                document.getElementById(divID).style.height = "240px";
            }
        });
    });

     

    CSS Code:

    /* Enter your custom styles here */
    .EmphasizedText {
        font-weight: bold;
        -webkit-text-fill-color: #085caf;
    }
    
    .whitebg {
        background-color: white !important;
    }
    
    .container {
        display: flex;
    }
    
    .participant {
        width: 20%;
        height: 500px;
        text-align: center;
        display: flex;
        flex-direction: column;
        align-items: center;
       
    }
    
    .zoomOut {
        width: 80%;
        height: 200px;
        position: relative;
    }
    
    .fs {
        width: 80%;
        display: flex;
        align-items: center;
    }
    
    .zoomButton {
        position: absolute;
        z-index: 100;
        top: 5px;
        right: 5px;
        border-color: #fff;
        background: #fff;
        color: black;
    }
    
    .zoomButton:before {
        content: "📌 ";
    }
    
    .zoomIn {
        width: 80%;
        height: 100%;
        position: absolute;
        right: 10px;
    }
    
    html.sap-desktop .sapMShellAppWidthLimited .sapMShellCentralBox {
        width: 100% !important;
        margin-left: 5px !important;
        left: 0 !important;
    }

    Output

    Video Call Integration in SAP UI5

  • Copy to Clipboard Integration in SAP UI5

    Preface – This post is part of the UI5 Integration Programs series.

    Introduction

    Copy to Clipboard functionality refers to the ability of a computer or mobile device to copy selected text or data and temporarily store it in a virtual clipboard. The copied content can then be pasted into another location, such as a document or an email.

    The copy to clipboard function can be accessed through a variety of ways, such as right-clicking on the selected content and choosing “Copy” from a menu, or using a keyboard shortcut such as Ctrl+C (on Windows) or Command+C (on Mac). Once the content is copied to the clipboard, it can be pasted into another location using a keyboard shortcut such as Ctrl+V (on Windows) or Command+V (on Mac), or by right-clicking and choosing “Paste” from a menu.

    Copy to Clipboard is a widely used feature in modern computing, and is particularly useful for tasks such as copying text from a web page or document, and pasting it into an email or other document without having to retype the content.

    Why we need to have a Copy to Clipboard Functionality in Website

    Copy to Clipboard functionality is useful in websites for a variety of reasons. Here are a few:

    1. Convenience: Copy to Clipboard makes it easy for users to copy and paste text, links, or other content from a website without having to type it out manually.
    2. Accuracy: Copy to Clipboard can help ensure that users copy and paste content accurately, without introducing errors or typos.
    3. Sharing: Copy to Clipboard makes it easy for users to share content from a website with others via email, chat, or social media.
    4. Productivity: Copy to Clipboard can help users be more productive by allowing them to quickly copy and paste information from a website into other applications, such as word processors or spreadsheets.
    5. Accessibility: Copy to Clipboard can be particularly helpful for users who may have difficulty typing, such as those with disabilities or injuries.

    Overall, Copy to Clipboard functionality in websites is a useful tool that can help users save time and be more productive, while also reducing the risk of errors and increasing accuracy.

    How to Integrate Copy to Clipboard  functionality in UI5

    The copy to clipboard is a very simple functionality of HTML and JavaScript, but quite difficult in case of SAP UI5. There are three steps involved in HTML based copy to clipboard operation:
    1. Textarea with text value meant for copy
    2. Selection of the text using Select function
    3. Copy to Clipboard using Copy function

    The same three operations will be performed in SAP UI5.

    Before you start coding, create a JavaScript file (here customDOM.js) and keep it in a Js folder with given content:

    /**
     * @Author: Rudramani Pandey
     * Purpose: JS File for all Custom HTML DOM operations (copy to clipboard)
     * Modified: 17.02.2023
     */
    sap.ui.define([], function () {
        "use strict";
    
        return {
    
            createTextArea: function (text) {
                var textArea = document.createElement("textarea");
                textArea.value = text;
                return textArea;
            },
    
            insertTextArea: function (textArea) {
                document.body.appendChild(textArea);
                return true;
            },
    
            execCommand: function () {
                return document.execCommand('copy');
            },
    
            removeChild: function (textArea) {
                document.body.removeChild(textArea);
                return true;
            }
        };
    });

    Explanation:

    In the above code createTextArea would create a HTML element textArea. Then insertTextArea would append it to the body of the HTML. execCommand performs the copy function and removeChild removes the HTML element from the body once our task is done.

    Then create a view and have simple text area and copy to clipboard button:
    View.xml

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core"
        xmlns:html="http://www.w3.org/1999/xhtml">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Copy to Clipboard Integration in SAP UI5">
                        <content>
                            <VBox>
                                <TextArea id="idText" value="This is the text that I am going to copy!"/>
                                <Button text="Copy to Clipboard" press="onPressToClipboard"/>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

    Now, create a controller, include the JavaScript file in the define section. Now a function to get the text data from XML file.

    Controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "Test/Test/js/customDOM",
        "sap/m/MessageBox",
        "sap/m/MessageToast"
    ], function (Controller, customDOM, MessageBox, MessageToast) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            onInit: function () {
    
            },
    
            /** 
             * onPressToClipboard is invoked on click of Copy to Clipboard from UI.
             * Calls getText to receive the text value
             * @param oEvent
             * Output: Value of Text Area in HTML DOM
             */
            onPressToClipboard: function (oEvent) {
                var that = this;
                Promise.all([that.getText(oEvent, "CopyPassword")]).then(function (param) {
                    param = param[0];
                    var textArea = customDOM.createTextArea(param);
                    customDOM.insertTextArea(textArea);
                    textArea.select();
    
                    try {
                        var successful = customDOM.execCommand();
                        var sMsg = successful ? "successful" : "unsuccessful";
                        MessageToast.show("Password Copy to Clipboard was " + sMsg);
                    } catch (err) {
                        // Error Handled Later
                    }
                    customDOM.removeChild(textArea);
                }).catch(function (param) {
                    MessageBox.error(param.message);
                });
            },
    
            getText: function (oEvent, type) {
                var that = this;
                return new Promise(function (resolved, rejected) {
                    var text = that.byId("idText").getValue();
                    return resolved(text);
                });
            }
        });
    });

    Explanation:

    In the above code onPressToClipboard gets text from the function getText, and passes it to the function createTextArea to create a HTML TextArea. The function insertTextArea would pass the TextArea would insert into HTML body. textArea.select() would select the text, and then execCommand would finally copy the selected text to the clipboard.

    Output

    Copy to Clipboard Integration in SAP UI5

  • SAP BTP Destination Access in SAP UI5

    Preface – This post is part of the UI5 Integration Programs series.

    What is the concept of Destination in SAP BTP?

    In SAP Business Technology Platform (SAP BTP), a destination is a configuration object that defines the connection parameters for accessing a service or system from SAP BTP.

    A destination is used as a way to define the communication settings for a service and to ensure secure access to the service. The destination defines the target URL of the service, the credentials that are used to access the service, and other configuration properties such as the communication protocol, message format, and security settings.

    Destinations can be used to access a variety of services such as Cloud Foundry applications, APIs hosted on SAP API Business Hub, and data sources like databases or SAP S/4HANA systems.

    In SAP BTP, you can manage destinations through the Destination service in the SAP Cloud Platform cockpit, where you can create, update, or delete destinations as needed.

    What are the different ways that we can create a Destination in SAP BTP?

    There are several ways to create a destination in SAP Business Technology Platform (SAP BTP):

    1. SAP Cloud Platform Cockpit: You can use the SAP Cloud Platform cockpit to create and manage destinations. This is the recommended method for creating destinations in SAP BTP, as it provides a user-friendly interface and ensures that the destinations are properly secured and configured.
    2. API: You can use the SAP Cloud Platform Destination API to programmatically create and manage destinations. This is useful when you need to automate the creation and management of destinations or when you need to integrate the creation and management of destinations into a custom application.
    3. SAP Cloud Platform Connectivity Service: You can use the SAP Cloud Platform Connectivity Service to create destinations, which is particularly useful when connecting to external systems from SAP BTP.
    4. SAP Cloud Platform Extension Factory: You can use the SAP Cloud Platform Extension Factory to create destinations for services hosted within your SAP BTP landscape. This is useful when you need to access services that are not directly available through the SAP Cloud Platform cockpit.

    Regardless of the method used to create a destination, it is important to properly secure the destination by defining the appropriate authentication and authorization settings. This ensures that the destination can be used securely to access the target service or system from SAP BTP.

    In this article, we will focus on the below integrations:

    • Neo Destination in SAP UI5
    • Cloud Foundry Destination in SAP UI5
    • Destination as a Service in SAP UI5

    Creating a Destination in SAP BTP

    1. Visit your BTP Platform by visiting here: https://account.hana.ondemand.com/#/home/welcome

    2. Create a new Destination for your API, in our case, we have created one for YouTube and another for Northwind.

    Destination Setup in SAP BTP for an API

    Northwind OData

    Destination Setup in SAP BTP for an OData

    How to Consume Neo Destination in SAP UI5

    To consume a destination in SAP UI5 from the Neo environment, you need to perform the following steps:

    1. Create a destination: You need to create a destination in the SAP Business Technology Platform (SAP BTP) using one of the methods described in my previous answer. Make sure the destination is properly configured and secured, just like the way we have done above. You can read more here.
    2. Add the destination to your SAP UI5 application in Neo.json File: You need to add the destination to your SAP UI5 application by creating a binding in the manifest.json file of your application. The binding provides the necessary information to connect to the destination, such as the URL and authentication credentials. Add the below section within “routes” array of neo-app.json
      {
            "path": "/destination/youtube",
            "target": {
              "type": "destination",
              "name": "Test",
              "entryPath": "/destination/youtube"
            },
            "description": "Test Destination"
          },
          {
            "path": "/destinations/northwind",
            "target": {
              "type": "destination",
              "name": "northwind"
            },
            "description": "Northwind OData Service"
          }

       

    3. Consume the destination from Controller File: In your SAP UI5 code, you can consume the destination by using the SAPUI5 framework’s OData model. You can create an instance of the OData model and pass it the URL of the destination as well as any additional configuration parameters, such as authentication credentials.

    Here is an example of how you can consume a destination in SAP UI5:

    // Get the URL of the destination from the binding
    var sServiceUrl = this.getOwnerComponent().getModel("destination").sServiceUrl;
    
    // Create an instance of the OData model
    var oModel = new sap.ui.model.odata.v2.ODataModel(sServiceUrl, {
        useBatch: true
    });
    
    // Set the OData model on the view
    this.getView().setModel(oModel);
    

    In this example, the destination URL is obtained from the binding created in the manifest.json file of the application. The OData model is then created and set on the view, allowing you to access the data provided by the destination in your SAP UI5 code.

    For YouTube, we can directly consume the URL even in view, like this:

    <html:iframe height="100%" width="100%" src="/destination/youtube"/>

    For Northwind, we have added the given code in:

    manifest.json

    "dataSources": {
                "NorthwindModel": {
                    "uri": "/destinations/northwind/V2/Northwind/Northwind.svc/",
                    "type": "OData",
                    "settings": {
                        "odataVersion": "2.0"
                    }
                }
            }
    
    

    And also set the model using the above dataSoruce

    "": {
        "type": "sap.ui.model.odata.v2.ODataModel",
        "settings": {
            "defaultOperationMode": "Server",
            "defaultBindingMode": "OneWay",
            "defaultCountMode": "Request"
        },
        "dataSource": "NorthwindModel",
        "preload": true
    },

    Controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            onInit: function () {
                var that = this;
                var oOdataModel = this.getOwnerComponent().getModel();
                oOdataModel.setUseBatch(false);
                oOdataModel.read("/Products", {
                    success: function (oData) {
                        that.getView().setModel(new sap.ui.model.json.JSONModel(oData), "customerModel");
                    }
                });
            }
        });
    });

     

    View.xml

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core"
        xmlns:html="http://www.w3.org/1999/xhtml" xmlns:table="sap.ui.table">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Consuming Neo Destination in SAP UI5">
                        <content>
                            <table:Table id="customerTable" selectionMode="Single" rows="{customerModel>/results}" enableColumnReordering="false">
                                <!--columns for Product Name-->
                                <table:columns>
                                    <table:Column width="20%">
                                        <table:label>
                                            <Label text="Product Name"/>
                                        </table:label>
                                        <table:template>
                                            <Text text="{customerModel>ProductName}"/>
                                        </table:template>
                                    </table:Column>
                                </table:columns>
                            </table:Table>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

    Output For Table Binding

    Table binding from Destination Integration

    How to Consume Cloud Foundry Destination in SAP UI5

    To consume a Cloud Foundry destination in SAP UI5, you can follow these steps:

    1. Create a destination: First, you need to create a destination in SAP Business Technology Platform (SAP BTP) for the Cloud Foundry service you want to access. You can do this through the SAP Cloud Platform cockpit or by using the SAP Cloud Platform Destination API. Make sure the destination is properly configured and secured. You can read more here.
    2. Add the destination to your SAP UI5 application: You need to add the destination to your SAP UI5 application by creating a binding in the manifest.json file of your application. The binding provides the necessary information to connect to the destination, such as the URL and authentication credentials.
      Add the following codes:
      xs-app.json

      {
            "authenticationType": "none",
            "csrfProtection": false,
            "source": "^/Northwind/(.*)$",
            "destination": "Northwind",
            "target": "$1"
          }

      OData services and Models in Manifest:

      "dataSources": {
          "mainService": {
              "uri": "/V2/Northwind/Northwind.svc/",
              "type": "OData",
              "settings": {
                  "annotations": [],
                  "localUri": "localService/metadata.xml",
                  "odataVersion": "2.0"
              }
          }
      }
      "": {
          "dataSource": "mainService",
          "preload": true,
          "settings": {}
      }

      ui5.yaml

      # yaml-language-server: $schema=https://sap.github.io/ui5-tooling/schema/ui5.yaml.json
      
      specVersion: "2.5"
      metadata:
        name: cfxsapp
      type: application
      server:
        customMiddleware:
          - name: fiori-tools-proxy
            afterMiddleware: compression
            configuration:
              ignoreCertError: false # If set to true, certificate errors will be ignored. E.g. self-signed certificates will be accepted
              ui5:
                path:
                  - /resources
                  - /test-resources
                url: https://ui5.sap.com
              backend:
                - path: /V2
                  url: https://services.odata.org
                  destination: Northwind
          - name: fiori-tools-appreload
            afterMiddleware: compression
            configuration:
              port: 35729
              path: webapp
              delay: 300
          - name: fiori-tools-preview
            afterMiddleware: fiori-tools-appreload
            configuration:
              component: cfxsapp
              ui5Theme: sap_horizon
      
    3. Consume the destination: In your SAP UI5 code, you can consume the destination by using the SAPUI5 framework’s OData model. You can create an instance of the OData model and pass it the URL of the destination as well as any additional configuration parameters, such as authentication credentials.
      View.xml

      <mvc:View controllerName="cfxsapp.controller.Main"
          xmlns:mvc="sap.ui.core.mvc" displayBlock="true"
          xmlns="sap.m">
          <Page id="page" title="{i18n>title}">
              <content>
              <List items="{/Products}">
              <StandardListItem title="{ProductName}"/>
              </List>
              </content>
          </Page>
      </mvc:View>
      

      Output
      How to Consume Cloud Foundry Destination in SAP UI5

    A good article for step-by-step setup reference: Creating a sample SAPUI5 application with destination in Cloud Foundry environment | SAP Blogs

    How to Consume a Destination as a Service in MTA or CAPM App

    To consume a destination as a service in an MTA or CAPM (Cloud Application Programming Model) application in the SAP Business Technology Platform (SAP BTP), you need to follow these steps:

    1. Create a destination: First, you need to create a destination in SAP BTP for the service you want to access. You can do this through the SAP Cloud Platform cockpit or by using the SAP Cloud Platform Destination API. Make sure the destination is properly configured and secured.
      Step 01: Visit SAP HANA on demand portal here.
      Step 02: Enter into your Global account and click “Service Market Place” as shown below:
      Service Market Place
      Step 03: Search for “Destination”
      Search for Destination Service
      Step 04: Click three dots to create a new instance
      Create Destination Service
      Step 05: Enter details and provide a name for your destination and click next
      Create New Instance or Subscription of Destination
      Step 06: Once created, you can see your destination within your instance
      Destination Instance
      Step 07: Click your instance and click “Manage Instance” to open Dashboard of your destination service
      Manage Destination
      Step 08: Create a new Destination as you would have created within the BTP Destination section
      Destination as a Service
    2. Bind the destination to your MTA or CAPM application: To bind the destination to your MTA or CAPM application, you need to add a destination service to your mta.yaml file for MTA applications or to your package.json file for CAPM applications. The service definition provides the necessary information to connect to the destination, such as the URL and authentication credentials.
    3. Consume the destination: In your application code, you can consume the destination by using the appropriate client library for the service you are accessing. For example, if you are accessing an OData service, you can use the SAPUI5 framework’s OData model to connect to the service.

    Here is an example of how you can consume a destination as a service in an MTA application:

    # mta.yaml
    
    _schema-version: "2.1"
    
    ID: my-mta
    
    version: 0.0.1
    
    modules:
      - name: my-module
        type: nodejs
        path: my-module
        requires:
          - name: my-destination-service
            group: destinations
            properties:
              name: my-destination-service
    
    resources:
      - name: my-destination-service
        type: org.cloudfoundry.managed-service
        properties:
          service: destination
          service-plan: lite
          parameters:
            name: my-destination
            url: "<destination-url>"
            forwardAuthToken: true
            apiEndpoint: "<destination-api-endpoint>"
    

    In this example, the destination is bound to the MTA application as a service by adding a resources section to the mta.yaml file. The service definition includes the properties necessary to connect to the destination, such as the destination URL, API endpoint, and whether to forward the authentication token.

    For our usecase, we have this code in MTA.yaml

    _schema-version: '3.2'
    ID: mtaApp
    version: 0.0.1
    modules:
      - name: mtaapp-approuter
        type: approuter.nodejs
        path: mtaapp-approuter
        requires:
          - name: mtaApp_html_repo_runtime
            group: destinations
            properties:
              forwardAuthToken: false
              name: ui5
              url: 'https://ui5.sap.com'
        parameters:
          disk-quota: 256M
          memory: 256M
      - name: mtaApp_ui_deployer
        type: com.sap.application.content
        path: .
        requires:
          - name: mtaApp_html_repo_host
            parameters:
              content-target: true
        build-parameters:
          build-result: resources
          requires:
            - artifacts:
                - cfapp.zip
              name: cfapp
              target-path: resources/
      - name: cfapp
        type: html5
        path: cfapp
        build-parameters:
          build-result: dist
          builder: custom
          commands:
            - npm install
            - 'npm run build:cf'
          supported-platforms: []
    resources:
      - name: mtaApp_html_repo_runtime
        type: org.cloudfoundry.managed-service
        parameters:
          service: html5-apps-repo
          service-plan: app-runtime
      - name: mtaApp_html_repo_host
        type: org.cloudfoundry.managed-service
        parameters:
          service: html5-apps-repo
          service-plan: app-host
      - name: NorthwindTest
        type: org.cloudfoundry.managed-service
        parameters:
          service: destination
          service-plan: lite
    parameters:
      deploy_mode: html5-repo

    In the end the code is added for Destination.

    Once the destination is bound as a service, you can consume it in your code by using the appropriate client library for the service you are accessing. For example, if you are accessing an OData service, you can use the SAPUI5 framework’s OData model to connect to the service.

  • Base64 to Image Converter using SAP UI5

    Preface – This post is part of the UI5 Integration Programs series.

    When do we need to convert a Base64 to Image

    You may need to convert a Base64 string to an image for various reasons, such as:

    1. Displaying images on a web page: If you have a Base64 encoded image and you want to display it on a web page, you can create an HTML img element and set its src attribute to the Base64 encoded image data.
    2. Storing images in databases: If you have Base64 encoded images stored in a database and you want to display them, you need to convert them back to an image format before displaying them.
    3. Saving images to the file system: If you have Base64 encoded images and you want to save them to the file system, you need to first decode the Base64 data and then write the resulting binary data to a file.
    4. Using images in image processing applications: If you want to use Base64 encoded images in image processing applications, you need to convert them back to an image format so that they can be processed.

    In each of these cases, you will need to decode the Base64 string and write the binary data to an image file in a format such as PNG or JPEG. The exact steps to convert a Base64 string to an image will depend on the programming language you’re using and the specific requirements of your project.

    Steps to convert a Base64 to Image using JavaScript

    Here are the steps to convert a Base64 string to an image using JavaScript:

    1. Split the Base64 string at the comma to extract the content type and data:

    const [type, data] = base64.split(",");
    

    2. Create a Blob object using the data and the content type:

    const blob = new Blob([data], { type });
    

    3. Create an URL for the Blob object using URL.createObjectURL:

    const url = URL.createObjectURL(blob);
    

    4. Create an HTML img element and set its src attribute to the URL:

    const image = new Image();
    image.src = url;
    

    5. Append the image to the page or use it in any other way you need:

    document.body.appendChild(image);
    

    Here’s a complete example that converts a Base64 string to an image and displays it on a page:

    const base64 = "data:image/png;base64,iVBORw0KG...";
    const [type, data] = base64.split(",");
    const blob = new Blob([data], { type });
    const url = URL.createObjectURL(blob);
    const image = new Image();
    image.src = url;
    document.body.appendChild(image);
    

     

    Steps to convert a Base64 to an Image using SAP UI5

    To convert Base64 to Image in SAP UI5 using the element Image and setting its source value, as shown below:
    View.xml
    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core"
        xmlns:html="http://www.w3.org/1999/xhtml" xmlns:l="sap.ui.layout" xmlns:f="sap.ui.layout.form" xmlns:RichTextEditor="sap.ui.richtexteditor">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Base64 to Image Converter using UI5">
                        <content>
                            <VBox class="sapUiSmallMarginBegin">
                                <HBox>
                                    <TextArea id="idBase64Area" value='Base 64 Value' editable="true" height="300px" width="500px" change="onChangeDP"/>
                                    <Title text="Your Image"/>
                                    <Image id="idDP" width="30%"/>
                                </HBox>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller.js
    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            onChangeDP: function (oEvent) {
                var base64Data = this.byId("idBase64Area").getValue();
                this.byId("idDP").setSrc(base64Data);
            }
    
        });
    });

     

    Output
    Base64 to Image Converter using UI5
  • Image to Base64 Converter using SAP UI5

    Preface – This post is part of the UI5 Integration Programs series.

    When do we need to convert an Image to Base64

    You may want to convert an image to Base64 format for various reasons, some common use cases are:

    1. Storing images in databases: Instead of storing images as physical files, converting them to Base64 and storing the string in the database can simplify database management.
    2. Sending images in APIs: When sending images in APIs or other network protocols, it is often necessary to encode them as text-based data such as Base64, so they can be transmitted in a plain text format.
    3. Embedding images in HTML, CSS, or JavaScript: You can embed Base64 encoded images directly in your HTML, CSS, or JavaScript code, reducing the number of HTTP requests required to load a page.
    4. Reducing image file sizes: Base64 encoding increases the size of an image file, but it can be a useful optimization when multiple images are embedded in a single document, as it reduces the number of files that need to be loaded.

    It is worth noting that Base64 encoding increases the size of an image file by about 33%, so it’s not the most efficient way to store large images. However, for smaller images and icons, the overhead is usually not a problem.

    Steps to convert an Image to Base64 using JavaScript

    Here are the steps to convert an image to Base64 using JavaScript:

    1. Read the image file as a binary string using the FileReader API:

    const reader = new FileReader();
    
    reader.readAsDataURL(file);
    
    2. Once the file has been read, the load event will be triggered, and the result will be available in the reader.result property. This result will be a data URL that represents the image in Base64 format:
    reader.addEventListener("load", function() {
      const base64 = reader.result;
    });
    

    3. You can use the base64 variable in your JavaScript code to access the image data. For example, you can create an HTML img element and set its src attribute to the Base64 encoded image data:

    const image = new Image();
    image.src = base64;
    

    Here’s a complete example that reads an image file and displays it on a page:

    const input = document.querySelector("input[type='file']");
    const imageContainer = document.querySelector("#image-container");
    
    input.addEventListener("change", function(event) {
      const file = event.target.files[0];
      const reader = new FileReader();
    
      reader.readAsDataURL(file);
    
      reader.addEventListener("load", function() {
        const base64 = reader.result;
        const image = new Image();
        image.src = base64;
        imageContainer.appendChild(image);
      });
    });
    

     

    Steps to convert an Image to Base64 using SAP UI5

    In SAP UI5, you can use FileReader() function to convert the same. Codes are mentioned below:

    View.xml

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core"
        xmlns:html="http://www.w3.org/1999/xhtml" xmlns:l="sap.ui.layout" xmlns:f="sap.ui.layout.form" xmlns:RichTextEditor="sap.ui.richtexteditor">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Image to Base64 Converter using UI5">
                        <content>
                            <VBox class="sapUiSmallMarginBegin">
                                <HBox>
                                    <UploadCollection id="idDP" noDataText="Upload a square image preferably 640X640"
                                        maximumFilenameLength="30" maximumFileSize="1" multiple="false"
                                        sameFilenameAllowed="false" instantUpload="false" change="onChangeDP" fileDeleted="onFileDeletedDP" fileType="png,jpg,jpeg"
                                        filenameLengthExceed="onFilenameLengthExceed" fileSizeExceed="on1MBFileSizeExceed" typeMissmatch="onTypeMissmatch"
                                        uploadComplete="onUploadDPComplete" beforeUploadStarts="onBeforeUploadStarts"/>
                                    <TextArea id="idBase64Area" value='Base 64 Value' editable="false" height="300px" width="500px"/>
                                </HBox>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            onChangeDP: function (oEvent) {
                // Get File
                var that = this;
                var image = new Image();
                var file = oEvent.getParameter("files")[0];
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function () {
                    var data = reader.result;
                    //Set the Base64 string return from FileReader as text area value.
                    that.byId("idBase64Area").setValue(data);
                    image.onload = function () {
                        //	Check if image is bad/invalid
                        if (this.width + this.height === 0) {
                            that.dpImage = "";
                            sap.m.MessageBox.error("Invalid Image!");
                        }
                    };
                };
                reader.onerror = function (error) {
                    //Error Handling
                };
            }
    
        });
    });

    Output

    Image to Base64 Converter using UI5

     

  • Text to HTML Converter Integration in SAP UI5

    Preface – This post is part of the UI5 Integration Programs series.

    Introduction

    A Text to HTML Converter is a tool or software program that converts plain text into HTML (HyperText Markup Language) format. HTML is a markup language used to create web pages and display content on the internet. The HTML format provides a way to structure text and add visual elements, such as headings, paragraphs, lists, images, and links.

    When you use a Text to HTML Converter, you can take plain text and turn it into an HTML document, which can then be displayed on the web. The converter adds the necessary HTML tags and syntax to format the text and create a web page. This can be useful for people who want to publish text content on the web but don’t have experience with HTML coding.

    When do we need to convert Text to HTML in UI5?

    In SAP UI5, you might need to convert text to HTML when you want to display dynamic content on a web page, and you need to format that content in a specific way. For example, you might want to display text with different fonts sizes, colors, or styles. You might also want to include links, images, or lists in your content.

    When you use UI5 to build web applications, you can use the HTML format to create rich and dynamic user interfaces. The conversion from plain text to HTML can be done programmatically, for example, in a controller or helper class, and then the HTML content can be added to a UI5 control, such as a sap.m.Text control, for display in the user interface.

    This allows you to dynamically create and display formatted content in your UI5 applications, and provides a flexible and powerful way to present data and information to your users.

    The major business use case for Text to HTML converters is for the creation of an Email template. A business guy will create a template for you, and you will have to convert it into HTML, so that the same can be sent via Email. An email always sends data in HTML format.

    Text to HTML Converter Integration in SAP UI5

    1. Using RichTextEditor

    You can use RichTextEditor in view (commented here) or in the controller. When you try to get its value using getValue() function, then it always return HTML format data.

    View.xml

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core"
        xmlns:html="http://www.w3.org/1999/xhtml" xmlns:l="sap.ui.layout" xmlns:f="sap.ui.layout.form" xmlns:RichTextEditor="sap.ui.richtexteditor">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Text to HTML Converter using UI5">
                        <content>
                            <VBox class="sapUiSmallMarginBegin">
                                <HBox>
                                    <!--<RichTextEditor:RichTextEditor id="RichTextEditor1" height="300px" width="500px"/>-->
                                    <Text id="text2" class="sapUiSmallMarginBeginEnd sapUiSmallMarginTop"/>
                                    <VBox id="editorContainer"></VBox>
                                    <VBox class="sapUiLargeMargin">
                                        <Button text="Convert" width="100px" press="onConvert"/>
                                        <Button id="uploadText" text="Copy" width="100px" enabled="false" press="onSave"/>
                                    </VBox>
                                    <TextArea id="RichTextEditor2" value='' editable="false" height="300px" width="500px"/>
                                </HBox>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

    Controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            onInit: function () {
                var that = this;
                sap.ui.require(["sap/ui/richtexteditor/RichTextEditor"],
                    function (RTE) {
                        that.oRichTextEditor = new RTE("myRTE", {
                            editorType: sap.ui.richtexteditor.EditorType.TinyMCE,
                            width: "500px",
                            height: "300px",
                            showGroupFont: true,
                            tooltip: "Enter Text",
                            value: ""
                        });
    
                        that.getView().byId("editorContainer").addItem(that.oRichTextEditor);
                    });
            },
    
            onConvert: function () {
                var text = this.getView().byId("RichTextEditor2");
                var value = this.getView().byId("editorContainer").getItems()[0].getValue();
                if (value.length > 0) {
                    text.setValue(value);
                    this.getView().byId("uploadText").setEnabled(true);
                } else {
                    sap.m.MessageBox.information("Empty Input. Please type something");
                }
            }
        });
    });

    Output

    Text to HTML Converter using UI5

    2. Using JavaScript

    In SAP UI5, you can integrate a Text to HTML Converter in your web application by using JavaScript or any other programming language. Here’s an example of how you could implement a Text to HTML Converter in a UI5 application using JavaScript:

    1. Create a function that converts text to HTML format. This function can be called whenever you need to convert text to HTML.
      function convertTextToHTML(text) {
        // Use regular expressions or other string manipulation techniques to convert the text to HTML format
        var html = text.replace(/\n/g, "<br>");
        return html;
      }
      
    2. In your UI5 controller or helper class, call the convertTextToHTML function and pass the text that you want to convert.
      var html = convertTextToHTML("This is some sample text\nThis is a new line");
      
    3. Finally, set the HTML content to a UI5 control, such as a sap.m.Text control, and add it to the view.
      var textControl = new sap.m.Text({
        text: html
      });
      this.getView().addContent(textControl);
      

      This is just one way to implement a Text to HTML Converter in SAP UI5. The exact implementation will depend on the specific requirements of your application, such as the format of the input text and the desired output HTML format. However, this example should give you a general idea of how to integrate a Text to HTML Converter in your UI5 application.

  • Outlook or Email Client Integration in SAP UI5

    Preface – This post is part of the UI5 Integration Programs series.

    Introduction

    Outlook or Email Client Integration in SAP UI5 is a crucial aspect of modern-day business operations, as it streamlines the process of communication and data management within an organization. By integrating your email client with SAP UI5, you can efficiently manage emails, appointments, and contacts directly from your SAP system. This integration provides a seamless experience for users, improving productivity and reducing the time spent on manual tasks. With the help of SAP UI5’s intuitive interface and advanced features, you can easily manage your email and other communication needs, optimizing your work processes and increasing your overall efficiency.

    When do we need to integrate Outlook or Email Client with UI5?

    You may need to integrate Outlook or an Email Client with SAP UI5 in the following scenarios:

    1. Centralized Communication Management: Integrating your email client with SAP UI5 allows you to manage all your communication in a single platform, reducing the time spent on switching between different systems.
    2. Improved Productivity: By integrating your email client with SAP UI5, you can automate repetitive tasks such as sending emails, scheduling appointments, and updating contacts. This saves time and improves overall productivity.
    3. Better Collaboration: Integrating your email client with SAP UI5 makes it easier for team members to communicate and collaborate on projects. You can easily share information and track email conversations directly from the SAP system.
    4. Enhanced Data Security: By keeping all your communication within a secure platform like SAP UI5, you can ensure that sensitive information is protected and only accessible by authorized users.
    5. Better Customer Experience: By integrating your email client with SAP UI5, you can provide a seamless and efficient customer experience. You can respond to customer inquiries, send updates, and manage customer information directly from your SAP system.

    How to open up Outlook or Email Client from UI5 with preformatted text?

    We can open up Outlook or another email client in UI5 in two different ways:

    1. Using mailto URL scheme

    To open Outlook or an Email Client from SAP UI5 with preformatted text, you can use a combination of JavaScript and the mailto URL scheme. Here’s an example of how you can achieve this:

    var emailSubject = "SAP UI5 Email Integration";
    var emailBody = "Hello,\n\nThis is an email generated from SAP UI5.\n\nBest regards,\nSAP UI5 Team";
    var emailTo = "recipient@example.com";
    
    var mailLink = "mailto:" + emailTo + "?subject=" + encodeURIComponent(emailSubject) + "&body=" + encodeURIComponent(emailBody);
    
    window.location.href = mailLink;
    

    In this example, the email subject, body, and recipient’s email address are defined as variables. The mailto URL scheme is then used to create a mailto link, which opens up the email client with the preformatted text. The encodeURIComponent function is used to properly encode the subject and body text for use in a URL.

    When this code is executed, it opens the default email client with the specified subject, body, and recipient. Note that the behavior of this code may vary based on the email client being used and the settings on the user’s device.

    2. Using sap.m.URLHelper.triggerEmail

    The sap.m.URLHelper.triggerEmail method is a part of the SAP UI5 library and can be used to open the default email client with preformatted text. Here’s an example of how you can use this method:

    In this method we will try to create something where you can even select fields from UI and pass them to email like shown below:

    sap.m.URLHelper.triggerEmail("recipient@example.com", "SAP UI5 Email Integration", "Hello,\n\nThis is an email generated from SAP UI5.\n\nBest regards,\nSAP UI5 Team");
    

    In this example, the triggerEmail method takes three parameters: the recipient’s email address, the email subject, and the email body. When this code is executed, it opens the default email client with the specified subject, body, and recipient.

    This method provides a simpler and more convenient way to open the email client compared to manually constructing a mailto link. Additionally, it ensures that the email text is properly encoded for use in a URL.

    View.xml

    <mvc:View controllerName="ChatGPTGen.ChatGPTGen.controller.Main" xmlns:table="sap.ui.table" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="App to show Email Client Integration in SAP UI5">
                        <content>
                            <table:Table id="customerTable" selectionMode="Single" rows="{/customers}" enableColumnReordering="false">
                                <!-- columns for customer name, address, and email -->
                                <table:columns>
                                    <table:Column width="20%">
                                        <table:label>
                                            <Label text="Name"/>
                                        </table:label>
                                        <table:template>
                                            <Text text="{name}"/>
                                        </table:template>
                                    </table:Column>
                                    <table:Column width="30%">
                                        <table:label>
                                            <Label text="Address"/>
                                        </table:label>
                                        <table:template>
                                            <Text text="{address}"/>
                                        </table:template>
                                    </table:Column>
                                    <table:Column width="50%">
                                        <table:label>
                                            <Label text="Email"/>
                                        </table:label>
                                        <table:template>
                                            <Text text="{email}"/>
                                        </table:template>
                                    </table:Column>
                                </table:columns>
                            </table:Table>
                        </content>
                        <!-- buttons for creating, editing, and deleting records -->
                        <footer>
                            <Bar>
                                <contentLeft>
                                    <Button id="createButton" text="Create" press="handleCreate"/>
                                    <Button id="editButton" text="Edit" press="handleEdit"/>
                                    <Button id="deleteButton" text="Delete" press="handleDelete"/>
                                    <Button id="onHelpPress" text="Help" press="onHelpPress"/>
                                </contentLeft>
                            </Bar>
                        </footer>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

    Controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox"
    ], function (Controller, MessageBox) {
        "use strict";
    
        return Controller.extend("ChatGPTGen.ChatGPTGen.controller.Main", {
            onInit: function () {
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({
                    customers: [{
                        name: "John Doe",
                        address: "123 Main St",
                        email: "john.doe@example.com"
                    }, {
                        name: "Jane Doe",
                        address: "456 Oak Ave",
                        email: "jane.doe@example.com"
                    }]
                });
    
                // set the model on the core so that it is available to the entire application
                sap.ui.getCore().setModel(oModel);
                // bind the table to the model
                this.byId("customerTable").setModel(sap.ui.getCore().getModel());
            },
    
            // handler for creating a new customer record
            handleCreate: function () {
                // implement your logic for creating a new customer here
            },
    
            // handler for editing a customer record
            handleEdit: function () {
                // get the selected customer from the table
                var oTable = this.byId("customerTable");
                var oSelectedCustomer = oTable.getSelectedItem();
    
                // implement your logic for editing the selected customer here
            },
    
            // handler for deleting a customer record
            handleDelete: function () {
                // get the selected customer from the table
                var oTable = this.byId("customerTable");
                var iSelectedIndex = oTable.getSelectedIndex();
    
                // check if a customer is selected
                if (iSelectedIndex === -1) {
                    sap.m.MessageToast.show("Please select a customer to delete");
                    return;
                }
    
                // remove the selected customer from the model data
                var aCustomers = sap.ui.getCore().getModel().getData().customers;
                aCustomers.splice(iSelectedIndex, 1);
                sap.ui.getCore().getModel().setData({
                    customers: aCustomers
                });
    
                // show success message and refresh the table
                sap.m.MessageToast.show("Your selected row is deleted");
                // oTable.getBinding("items").refresh();
            },
    
            onHelpPress: function () {
                // Get data from selection on screen
                if (window.getSelection().baseNode === null) {
                    MessageBox.error(
                        "Please highlight the field and value for which you want to report issue!"
                    );
                } else {
                    var selectedData = window.getSelection().focusNode.nodeValue;
                    var getSelectedField = window.getSelection().anchorNode.nodeValue;
                    // Check if there was any selection
                    if (selectedData === null || getSelectedField === null) {
                        MessageBox.error(
                            "Please highlight the field and value for which you want to report issue!"
                        );
                    } else {
                        // Trigger email with custom email data
                        sap.m.URLHelper.triggerEmail("contact@rudelabs.in", "RUDE LABS: Data Issue for Customer " + selectedData, "Hello " + "Team" +
                            ", \n\n" +
                            "Kindly look into the Address with the following details: \n" +
                            "Customer name: " + selectedData + "\n" +
                            "Current Address: " + getSelectedField + "\n" +
                            "Reporter User ID: " + sap.ushell.Container.getService("UserInfo").getId() + "\n\n\n\n" +
                            "Thanks & Regards," + "\n" +
                            sap.ushell.Container.getService("UserInfo").getUser().getFullName()
                        );
                    }
                }
            }
    
        });
    });

     

    Output

    Selection of fields on UI5 screen

     

    Email triggerEmail