Blog

  • Multiupload multiple files simultaneously in UI5 (Async Multiple Upload files)

    Introduction

    Introducing Multiupload: the ultimate solution for uploading multiple files simultaneously in SAP UI5. With our Async Multiple Upload feature, you can easily select and upload multiple files in one go, saving you time and effort. Whether you need to upload documents, images, or any other file types, Multiupload streamlines the process, ensuring a smooth and efficient file upload experience. Say goodbye to tedious one-by-one uploads and embrace the power of simultaneous file uploading with Multiupload in UI5.

    Difference between Sync and Asyn File Uploads in JavaScript

    Synchronous (Sync) and asynchronous (Async) file uploads in JavaScript refer to different approaches for handling file upload operations.

    1. Synchronous File Upload:
    – In synchronous file upload, the upload process occurs in a blocking manner.
    – When a file is uploaded synchronously, the entire execution of the script is paused until the upload is complete.
    – Users have to wait for the file to be uploaded before they can continue interacting with the webpage.
    – Synchronous file uploads are straightforward to implement but may lead to a poor user experience, especially for larger files or slower network connections.

    2. Asynchronous File Upload:
    – In asynchronous file upload, the upload process occurs in a non-blocking manner.
    – When a file is uploaded asynchronously, the script continues executing without waiting for the upload to complete.
    – Users can continue interacting with the webpage while the file is being uploaded in the background.
    – Asynchronous file uploads are typically implemented using AJAX (Asynchronous JavaScript and XML) techniques, allowing for a smoother user experience.
    – Progress indicators and callbacks can be used to provide real-time feedback to the user during the upload process.

    The choice between synchronous and asynchronous file uploads depends on various factors such as the specific requirements of the application, file size, network conditions, and desired user experience. Asynchronous file uploads are commonly preferred as they allow for better responsiveness and improved user interactions while files are being uploaded.

    Multiupload multiple files simultaneously in UI5 (Async Multiple Upload files)

    View Code

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:upload="sap.m.upload">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="My Project Ideas: Multiupload multiple files simultaneously in UI5 (Async Multiple Upload files)">
                        <content>
                            <upload:UploadSet id="UploadSet" instantUpload="true" showIcons="true" uploadEnabled="true" terminationEnabled="true"
                                fileTypes="txt,doc,png" maxFileNameLength="30" maxFileSize="200" mediaTypes="text/plain,application/msword,image/png"
                                uploadUrl="../../../../upload" items="{path: '/items', templateShareable: false}" mode="MultiSelect" selectionChanged="onSelectionChange">
                                <upload:toolbar>
                                    <OverflowToolbar>
                                        <ToolbarSpacer/>
                                        <Button id="uploadSelectedButton" text="Upload selected" press="onUploadSelectedButton"/>
                                        <Button id="downloadSelectedButton" text="Download selected" press="onDownloadSelectedButton"/>
                                        <Button id="versionButton" enabled="false" text="Upload a new version" press="onVersionUpload"/>
                                        <upload:UploadSetToolbarPlaceholder/>
                                    </OverflowToolbar>
                                </upload:toolbar>
                                <upload:items>
                                    <upload:UploadSetItem fileName="{fileName}" mediaType="{mediaType}" url="{url}" thumbnailUrl="{thumbnailUrl}"
                                        markers="{path: 'markers', templateShareable: false}" statuses="{path: 'statuses', templateShareable: false}" uploadState="{uploadState}">
                                        <upload:markers>
                                            <ObjectMarker type="{type}" visibility="{visibility}"/>
                                        </upload:markers>
                                        <upload:statuses>
                                            <ObjectStatus title="{title}" text="{text}" state="{state}" icon="{icon}" active="{active}"/>
                                        </upload:statuses>
                                    </upload:UploadSetItem>
                                </upload:items>
                            </upload:UploadSet>
                            <VBox>
                                <Title text="Messages"/>
                                <TextArea width="100%" value="{appConfigModel>/msgModel}"/>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller Code

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            onInit: function () {
                var oUploadSet = this.byId("UploadSet");
                // Modify "add file" button
                oUploadSet.getDefaultFileUploader().setButtonOnly(false);
                oUploadSet.getDefaultFileUploader().setTooltip("");
                oUploadSet.getDefaultFileUploader().setIconOnly(true);
                oUploadSet.getDefaultFileUploader().setIcon("sap-icon://attachment");
                oUploadSet.attachUploadCompleted(this.onUploadCompleted.bind(this));
            },
    
            onUploadSelectedButton: function () {
                var that = this;
                // Message Model
                var msgModel = new sap.ui.model.json.JSONModel({});
                var oUploadSet = this.byId("UploadSet");
                var previous;
                oUploadSet.getItems().forEach(function (oItem) {
                    if (oItem.getListItem().getSelected()) {
                        // AJAX Call
                        var form = new FormData();
                        form.append("file", oItem);
                        return $.ajax({
                            method: "PUT",
                            url: "<Your API>",
                            data: form,
                            async: true,
                            processData: false,
                            mimeType: "multipart/form-data",
                            headers: {
                                "X-Csrf-Token": "<get security key from Data Model>"
                            },
                            contentType: false,
                        }).done((response) => {
                            previous = that.getOwnerComponent().getModel("appConfigModel").getProperty("/msgModel");
                            var updated = previous != "" ? previous.concat(response, ', ') : response;
                            that.getOwnerComponent().getModel("appConfigModel").setProperty("/msgModel", updated);
                        }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
                            // Updating the Message Popover
                            var sErrorMsg = XMLHttpRequest.responseText;
                            if (sErrorMsg) {
                                previous = that.getOwnerComponent().getModel("appConfigModel").getProperty("/msgModel");
                                var updated = previous != "" ? previous.concat(sErrorMsg, ', ') : sErrorMsg;
                                that.getOwnerComponent().getModel("appConfigModel").setProperty("/msgModel", updated);
                            }
                        });
                    }
                });
            },
    
            onDownloadSelectedButton: function () {
                var oUploadSet = this.byId("UploadSet");
    
                oUploadSet.getItems().forEach(function (oItem) {
                    if (oItem.getListItem().getSelected()) {
                        oItem.download(true);
                    }
                });
            },
    
            onSelectionChange: function () {
                var oUploadSet = this.byId("UploadSet");
                // If there's any item selected, sets version button enabled
                if (oUploadSet.getSelectedItems().length > 0) {
                    if (oUploadSet.getSelectedItems().length === 1) {
                        this.byId("versionButton").setEnabled(true);
                    } else {
                        this.byId("versionButton").setEnabled(false);
                    }
                } else {
                    this.byId("versionButton").setEnabled(false);
                }
            },
    
            onVersionUpload: function (oEvent) {
                var oUploadSet = this.byId("UploadSet");
                this.oItemToUpdate = oUploadSet.getSelectedItem()[0];
                oUploadSet.openFileDialog(this.oItemToUpdate);
            },
    
            onUploadCompleted: function (oEvent) {
                this.oItemToUpdate = null;
                this.byId("versionButton").setEnabled(false);
            }
        });
    });

    Output

    Multiupload multiple files simultaneously in UI5 (Async Multiple Upload files)

  • Custom Message Popover Integration in SAP UI5

    Introduction

    In this tutorial, we will learn simple steps to implement Custom Message Popover Integration in SAP UI5.

    In SAP UI5, the ability to display informative messages or notifications to users is crucial for enhancing user experience and providing important feedback. Custom Message Popover integration in SAP UI5 allows developers to create and display tailored messages in a visually appealing and interactive manner. By leveraging this feature, developers can effectively communicate messages, warnings, errors, or any other relevant information to users within their applications.

    Custom Message Popover integration in SAP UI5 involves utilizing the sap.m.Popover control to create a popover-like dialog that can be triggered programmatically. This popover can be customized to display messages with different severity levels, such as success, information, warning, or error. Developers have full control over the content, styling, and behavior of the popover, enabling them to design a highly interactive and visually consistent messaging experience.

    In this project, we will explore the process of integrating Custom Message Popover in SAP UI5 applications. We will learn how to define and customize the popover control, define messages with different severity levels, and dynamically populate the popover with relevant content. Additionally, we will explore how to handle user interactions with the popover, such as dismissals or further actions based on the displayed messages.

    By the end of this project, you will have a solid understanding of how to integrate Custom Message Popover in SAP UI5 and leverage its capabilities to deliver informative and visually appealing messages to users. This integration will enhance the usability of your applications and empower users with timely and actionable information, contributing to a more seamless and efficient user experience. So, let’s dive into the world of Custom Message Popover integration in SAP UI5 and unlock the potential to elevate your application’s messaging capabilities.

    What is Message Popover in SAP UI5

    In SAP UI5, a Message Popover is a UI control that provides a convenient and visually appealing way to display messages, notifications, or alerts to users within an application. It serves as a container for displaying multiple messages of different severity levels, such as success, information, warning, or error.

    The Message Popover control in SAP UI5, typically represented as a small dialog or popover-like element, offers a centralized location for presenting important information to users without disrupting their workflow. It allows developers to communicate various types of messages in a concise and organized manner, improving the overall user experience and facilitating effective communication.

    The Message Popover in SAP UI5 provides the following key features:

    1. Message Types and Severity Levels: The Message Popover supports different message types with associated severity levels, enabling developers to categorize and differentiate messages based on their importance or urgency.

    2. Message Aggregation: The Message Popover can aggregate multiple messages, allowing developers to display multiple notifications or alerts simultaneously. Messages can be added or removed dynamically based on application logic or user interactions.

    3. Styling and Formatting: Developers can customize the appearance and styling of the Message Popover to match the overall design language and branding of their application. This includes options to define the layout, colors, icons, and other visual elements.

    4. Interaction and Actionability: Users can interact with messages within the Message Popover by performing actions associated with each message. This can include dismissing a message, acknowledging it, or triggering further actions based on the message content.

    5. Localization and Accessibility: The Message Popover supports localization, allowing developers to display messages in different languages or adapt to regional preferences. It also ensures compliance with accessibility guidelines, making the messages accessible to users with disabilities.

    By leveraging the Message Popover control in SAP UI5, developers can effectively communicate important information, warnings, errors, or any other relevant messages to users in a user-friendly and organized manner. This enhances the usability and user experience of the application by providing timely and actionable feedback.

    Steps for Custom Message Popover Integration in SAP UI5

    Here are the steps for integrating a Custom Message Popover in SAP UI5:

    1. Set up the SAP UI5 Development Environment:
    – Install SAPUI5 library and necessary development tools.
    – Create a new SAP UI5 project or use an existing project as a base.

    2. Define the UI Layout:
    – Create a view or a page where the Message Popover will be displayed.
    – Design the overall layout using SAP UI5 controls like panels, containers, or grids.

    3. Create the Message Popover Control:
    – Instantiate the sap.m.Popover control in your view or page.
    – Configure the popover with desired properties such as width, height, and positioning.

    4. Define Message Models and Data Binding:
    – Define a message model to store the messages to be displayed in the popover.
    – Populate the message model with the relevant messages based on your application logic.
    – Bind the message model to the Message Popover control to dynamically display the messages.

    5. Customize the Message Popover Content:
    – Define the content of the Message Popover control, including the layout and formatting of the messages.
    – Utilize UI5 controls like sap.m.MessageStrip or sap.m.List to display individual messages within the popover.
    – Customize the appearance of the messages based on their severity levels using icons, colors, or formatting.

    6. Handle User Interactions:
    – Implement event handlers or listeners for user interactions with the messages, such as dismissals or further actions.
    – Define appropriate actions based on the user’s response to a message, like acknowledging or resolving the issue.

    7. Displaying the Message Popover:
    – Trigger the display of the Message Popover control based on specific events or application logic.
    – Set the popover’s position relative to a target control or a specific location on the screen.
    – Show or hide the Message Popover dynamically as needed.

    8. Test and Refine:
    – Test the integration of the Custom Message Popover by simulating various scenarios and verifying the display and behavior of messages.
    – Gather feedback from users and iterate on the design and functionality based on their requirements and suggestions.
    – Continuously refine and optimize the Custom Message Popover’s performance, styling, and user experience.

    By following these steps, you can successfully integrate a Custom Message Popover in your SAP UI5 application. This integration will enable you to display informative messages and notifications to users in a visually appealing and interactive manner, enhancing the usability and overall user experience of your application.

    View Code

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:l="sap.ui.layout" height="100%"
        displayBlock="true">
        <Page>
            <customHeader>
                <Bar>
                    <contentLeft>
                        <Button id="msgpop1" icon="sap-icon://message-popup" text="{popoverModel>/messagesLength}" type="{popoverModel>/type}"
                            press="handleMessagePopoverPress"/>
                    </contentLeft>
                    <contentMiddle>
                        <Title text="My Project Ideas: Message Popover Integration in SAP UI5" titleStyle="H2"></Title>
                    </contentMiddle>
                    <contentRight>
                        <Button text="Get Success Message" press="onSuccess" icon="sap-icon://message-success"/>
                        <Button text="Get Error Message" press="onError" icon="sap-icon://message-error"/>
                    </contentRight>
                </Bar>
            </customHeader>
        </Page>
    </mvc:View>

     

    Controller Code

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox",
        "sap/m/MessageToast",
        "sap/ui/model/json/JSONModel",
        "sap/ui/Device",
        'sap/m/MessagePopover',
        'sap/m/MessagePopoverItem'
    ], function (Controller, MessageBox, MessageToast, JSONModel, Device, MessagePopover, MessagePopoverItem) {
        "use strict";
    
        var oMessageTemplate = new MessagePopoverItem({
            type: '{T}',
            title: '{S}',
        });
    
        var oMessagePopover = new MessagePopover({
            items: {
                path: '/',
                template: oMessageTemplate
            }
        });
    
        return Controller.extend("Test.Test.controller.Main", {
            onInit: function () {
                var that = this;
                var pop_msgModel = new sap.ui.model.json.JSONModel({
                    "messagesLength": "",
                    "type": "Default"
                });
                this.getView().setModel(pop_msgModel, "popoverModel");
                var popModel = new sap.ui.model.json.JSONModel({});
                oMessagePopover.setModel(popModel);
            },
    
            onSuccess: function () {
                var that = this;
                var message = "This is a success message!";
                var w_data = [];
                w_data.push({
                    T: "Success",
                    S: message
                });
                var previous = oMessagePopover.getModel().getData();
                if (previous.length === undefined)
                    previous = [];
                var updated = previous !== "" ? previous.concat(w_data) : w_data
                oMessagePopover.getModel().setData(updated);
                oMessagePopover.getModel().refresh(true);
                that.getView().getModel("popoverModel").getData().messagesLength = updated.length;
                that.getView().getModel("popoverModel").getData().type = "Emphasized";
                that.getView().getModel("popoverModel").refresh(true);
            },
    
            onError: function () {
                var that = this;
                var message = "This is an error message!";
                var w_data = [];
                w_data.push({
                    T: "Error",
                    S: message
                });
                var previous = oMessagePopover.getModel().getData();
                if (previous.length === undefined)
                    previous = [];
                var updated = previous !== "" ? previous.concat(w_data) : w_data
                oMessagePopover.getModel().setData(updated);
                oMessagePopover.getModel().refresh(true);
                that.getView().getModel("popoverModel").getData().messagesLength = updated.length;
                that.getView().getModel("popoverModel").getData().type = "Emphasized";
                that.getView().getModel("popoverModel").refresh(true);
            },
    
            handleMessagePopoverPress: function (oEvent) {
                oMessagePopover.toggle(oEvent.getSource());
            }
        });
    });

     

    Output

    Custom Message Popover Integration in SAP UI5

  • Design a Code Editor using SAP UI5

    Introduction

    In this tutorial, we will learn how to design a simple code editor using SAP UI5. These code editors can be used to run, pretty printer and test codes. SAP UI5 provides different types of code editors like javascript, ABAP, etc.

    In the world of software development, a well-designed code editor is an essential tool for programmers to write, edit, and debug their code efficiently. SAP UI5, a robust framework developed by SAP, provides a powerful and flexible solution for creating code editors with its sap.ui.codeeditor library.

    Designing a code editor using SAP UI5’s sap.ui.codeeditor involves leveraging the extensive capabilities of this library to create a user-friendly interface and enhance the overall coding experience. This powerful UI5 library offers a variety of features and functionalities, including syntax highlighting, code completion, line numbering, and more, enabling developers to streamline their coding tasks.

    In this project, we will explore the process of designing a code editor using SAP UI5’s sap.ui.codeeditor. We will delve into the key components and concepts of the sap.ui.codeeditor library and learn how to integrate them seamlessly into a user interface. By the end of this project, you will have a solid understanding of how to leverage SAP UI5 to build a code editor that caters to the needs of developers and empowers them to write clean, efficient, and error-free code.

    So, let’s embark on this journey of designing a code editor using SAP UI5’s sap.ui.codeeditor and unlock the potential to create a top-notch coding environment for programmers.

    Types of Code Editors in SAP UI5

    In SAP UI5, you have two types of code editors:

    1. Default Autocompletion:

    The Default Autocompletion feature in SAP UI5 code editors saves developers time by reducing the need to manually type long names or search for the correct syntax. It enhances productivity and accuracy by offering intelligent suggestions, thus minimizing the chance of typographical errors or misspelled identifiers. By providing real-time assistance, this autocompletion feature enables developers to write code more efficiently and maintain a consistent coding style.

    The Default Autocompletion feature in SAP UI5 code editors provides built-in support for suggesting code completions as you type. This feature leverages the code editor’s understanding of the programming language’s syntax and context to offer relevant suggestions. When enabled, the code editor analyzes the code you’re writing and provides a list of available completions for functions, variables, classes, methods, and more.

    2. Custom Autocompletion:

    In addition to the Default Autocompletion feature, SAP UI5 code editors also allow developers to define their own custom autocompletion rules. This enables them to extend the autocompletion functionality and tailor it to their specific requirements or domain-specific languages.

    With Custom Autocompletion, developers can define their own sets of suggestions for commonly used code snippets, libraries, frameworks, or any other custom context-specific completions. These custom autocompletion rules can be defined based on predefined trigger characters or specific events, such as pressing a hotkey or invoking a code generation action.

    Custom Autocompletion empowers developers to create personalized coding experiences and streamline repetitive tasks. It allows for the integration of project-specific or industry-specific code snippets, abbreviations, or templates, making it easier to write code and adhere to coding standards or best practices.

    By leveraging both the Default Autocompletion and Custom Autocompletion features in SAP UI5 code editors, developers can benefit from intelligent suggestions, improved coding speed, reduced errors, and a more tailored coding experience, ultimately enhancing their productivity and efficiency in software development.

    How to Design a Code Editor using SAP UI5

    Designing a code editor using SAP UI5 involves creating a user-friendly interface and integrating the sap.ui.codeeditor library to provide essential code editing functionalities. Here is a step-by-step guide to designing a code editor using SAP UI5:

    1. Set up the SAP UI5 Development Environment:
    – Install SAPUI5 library and necessary development tools.
    – Create a new SAP UI5 project or use an existing project as a base.

    2. Define the UI Layout:
    – Create a view or a page to hold the code editor component.
    – Design the overall layout using SAP UI5 controls like panels, containers, or grids.
    – Set up the necessary structure for the code editor and other supporting components.

    3. Integrate the Code Editor Component:
    – Include the sap.ui.codeeditor library in your project dependencies.
    – Instantiate the sap.ui.codeeditor.CodeEditor control in your view or page.
    – Configure the code editor with desired properties like height, width, syntax highlighting, and initial code content.

    4. Implement Code Editor Functionalities:
    – Enable basic code editing functionalities such as text selection, cursor navigation, and text manipulation (insertion, deletion).
    – Implement syntax highlighting by defining syntax rules for different programming languages.
    – Enable code formatting options to automatically format the code based on predefined rules.
    – Implement code validation and error highlighting by integrating with relevant parsers or linters.
    – Implement code completion feature to provide intelligent suggestions for code elements.
    – Add support for keyboard shortcuts and hotkeys to enhance the coding experience.

    5. Enhance the User Experience:
    – Implement line numbering and gutter indicators to improve code readability.
    – Add search and replace functionality to enable text search and replace operations within the code.
    – Integrate version control system functionalities like Git integration for code versioning and history tracking.
    – Provide options to customize the editor’s theme or visual appearance.
    – Implement code folding feature to allow collapsing and expanding sections of code for better organization.

    6. Handle User Interactions:
    – Implement event handlers to capture user interactions such as code changes, cursor movements, or code selection.
    – Define appropriate callbacks or event listeners to respond to user actions and trigger corresponding actions or updates.

    7. Test and Refine:
    – Test the code editor with sample code snippets to ensure proper functionality and responsiveness.
    – Gather feedback from users and iterate on the design based on their requirements and suggestions.
    – Continuously refine and optimize the code editor’s performance and user experience.

    By following these steps, you can design a code editor using SAP UI5 that provides a feature-rich and intuitive coding environment for developers. Remember to leverage the capabilities of the sap.ui.codeeditor library and tailor the editor’s functionalities to suit your specific development needs.

    View Code

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:l="sap.ui.layout"
        xmlns:CodeEditor="sap.ui.codeeditor" height="100%" displayBlock="true">
        <Page title="My Project Ideas: Code Editor">
            <content></content>
        </Page>
        <IconTabHeader id="iconTabHeader" selectedKey="invalidKey" select=".onSelectTab">
            <items>
                <IconTabFilter text="Default Autocompletion" key="A"/>
                <IconTabFilter text="Custom Autocompletion" key="B"/>
            </items>
        </IconTabHeader>
        <CodeEditor:CodeEditor id="aCodeEditor" height="300px" type="javascript"/>
        <Button text="Pretty Printer" press="onPrettyCode"/>
        <Button text="Run JavaScript Code" press="onRunCode"/>
    </mvc:View>

     

    Controller Code

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox",
        "sap/m/MessageToast",
        "sap/ui/model/json/JSONModel",
        "sap/ui/Device",
        "sap/ui/codeeditor/CodeEditor",
    ], function (Controller, MessageBox, MessageToast, JSONModel, Device, CodeEditor) {
        "use strict";
        var oEditor;
        var example1 = "function loadDoc() {\n\treturn 'Default Autocompletion: Write JavaScript Here';\n}";
        var example2 = "function myFunction(p1, p2) {\n\treturn 'Custom Autocompletion: Write ABAP Here';\n}";
    
        return Controller.extend("Test.Test.controller.Main", {
            onInit: function () {
                oEditor = this.byId("aCodeEditor");
                oEditor.setValue("// select tabs to see value of CodeEditor changing");
            },
    
            onSelectTab: function (oEvent) {
                var sFilterId = oEvent.getParameter("selectedKey");
                switch (sFilterId) {
                case "A":
                    oEditor.setValue(example1);
                    oEditor.setType("javascript");
                    break;
                case "B":
                    oEditor.setValue(example2);
                    oEditor.setType("abap");
                    oEditor.addCustomCompleter({
                        getCompletions: function (callback, context) {
                            // callback is provided to us by ACE so we can execute it as shown
                            // below to display suggestions to the user
                            // ideally, the array argument, provided to the following method call
                            // will be dynamically generated based on the content of the context object
                            // let's assume the context contains an sPrefix equal to 'read', which
                            // means the cursor in ACE is at the end of a 'read' word
                            // by executing the following call, we can show a list of suggestions
                            // such as: readFile, readStream, readResponse
                            callback(null, [{
                                value: "readFile()",
                                score: 100,
                                meta: "rhyme"
                            }, {
                                value: "readStream(input)",
                                score: 1,
                                meta: "params: input"
                            }, {
                                value: "readNow",
                                score: 1,
                                meta: "params: input"
                            }, {
                                value: "readStream(input, encoding)",
                                score: 1,
                                meta: "params: input, encoding"
                            }, {
                                value: "rudra(input, encoding)",
                                score: 1,
                                meta: "params: input, encoding"
                            }, {
                                value: "My Project Ideas(input, encoding)",
                                score: 1,
                                meta: "params: input, encoding"
                            }]);
                        }
    
                    });
                    break;
                default:
                    oEditor.setValue();
                    break;
                }
            },
    
            onPrettyCode: function () {
                oEditor.prettyPrint();
            },
    
            onRunCode: function () {
                var code = oEditor.getValue();
                try {
                    // Use eval to execute the code
                    eval(code);
                } catch (error) {
                    // Display any error that occurred during execution
                    alert("Code Running Failed");
                }
            }
        });
    });

     

    Output

    Output of Code Editor
    Output of Code Editor

     

    Custom Autocompletion in Code Editor
    Custom Autocompletion in Code Editor
  • Blockchain For Trade Finance

    Introduction

    The smooth functioning of international trade relies heavily on trade finance, which serves as a critical enabler for cross-border transactions. A wide range of essential financial instruments and products helps to facilitate the timely and efficient delivery of goods and services across international boundaries.

    However, traditional systems have long suffered from inefficiencies and complexities. For example, these outdated systems heavily rely on paper-based documentation, manual processes, and numerous intermediaries, leading to delays, high costs, and increased risks of fraud and errors.

    Blockchain brings a decentralized and transparent approach that has the potential to revolutionize how business owners participate in international trade. Smart contracts, for instance, leverage self-executing agreements written in code to automate and enforce contractual terms. By eliminating intermediaries, smart contracts streamline processes, reducing delays and costs while enhancing trust and security.

    Furthermore, by implementing a shared ledger system like blockchain among all counterparties, traders will have access to a reliable source of information. This will lead to a greater understanding of global trade and commodity availability, resulting in a more stable and predictable trading environment. It will prevent incidents like the “Great Grain Robbery,” where unknown deals and quantities caused significant disruptions. Additionally, enhanced data availability empowers traders involved in secondary market trading to make more precise and well-informed decisions. The transparent and immutable nature of blockchain ensures the integrity and accuracy of historical price data. This enables traders and finance professionals to identify chart patterns, optimize their strategies, and effectively mitigate risks, ultimately leading to improved trading outcomes.

    This transformative technology has the potential to simplify the challenges associated with international trade by digitizing trade-related documents. Rather than relying on physical paperwork and manual verification, digital storage and access provide a secure alternative. In addition to expediting the information flow, this digital transformation significantly minimizes the likelihood of errors, leading to a substantial improvement in overall operational efficiency.

    Blockchain-Based Trade Finance Solutions

    Blockchain technology has paved the way for innovative solutions and by leveraging the unique features of blockchain, several applications and platforms have emerged. Here are some of the key solutions offered:

    Enterprises embracing blockchain are actively striving to develop smooth and intuitive user experiences while simultaneously tackling the complexities of regulatory and legal requirements.

    Benefits of Using Blockchain in Trade Finance

    The integration of blockchain technology in international trade has a wide range of benefits, transforming the way businesses conduct international trade. Below are some of the key advantages of using blockchain in the industry:

    • Enhanced Transparency and Traceability
    • Streamlined Processes and Efficiency Gains
    • Improved Security and Fraud Prevention
    • Cost Reduction and Accessibility
    • Enhanced Trust and Collaboration
    • Real-time Data and Analytics

    The benefits for trade finance are clear, offering increased efficiency, security, transparency, and accessibility. As more organizations embrace blockchain technology, we can expect further innovation and refinements in trade finance processes, enabling businesses to thrive in the global marketplace.

    Potential Challenges and Considerations

    While the application of blockchain technology presents immense possibilities in revolutionizing global trade transactions, it also brings forth a host of challenges and factors that demand careful deliberation to ensure its widespread integration. Here are some crucial aspects that necessitate attention and resolution to facilitate seamless adoption:

    Regulatory and Legal Issues: The adoption of blockchain in international trade raises regulatory and legal considerations. Given the cross-border nature of blockchain operations involving multiple entities, it becomes imperative to establish a well-defined legal framework that effectively tackles concerns like jurisdiction, data privacy, and the resolution of disputes. To facilitate compliance and promote innovation within the realm of international trade, regulators must adapt and formulate comprehensive guidelines. Such measures will not only ensure adherence to legal obligations but also foster an environment conducive to the advancement of global trade.

    Adoption and Industry Collaboration: The successful adoption of blockchain in the context of international trade requires industry-wide collaboration and consensus. In order to drive progress in the realm of global trade transactions, it is imperative for a diverse array of stakeholders to join forces. This includes financial institutions, trade facilitators, governmental entities, and technology vendors, who must collaborate to lay the groundwork for shared standards, protocols, and exemplary approaches. Through synergistic cooperation, these collective endeavors can surmount obstacles to adoption, foster knowledge exchange, and fuel innovation, propelling the field of global trade transactions towards unprecedented growth and advancement.

    Security and Data Integrity: While blockchain technology offers enhanced security compared to traditional systems, it is not completely immune to cybersecurity threats. As blockchain networks grow, ensuring robust security measures to protect against hacking attempts, unauthorized access, and data breaches becomes imperative. Implementing strong encryption, access controls, and regular security audits are essential to maintain the integrity and confidentiality of data in global trade transactions on the blockchain.

    Addressing these challenges and considerations will be crucial to exploiting the full potential of blockchain technology in the realm of global trade. Through proactive collaboration, regulatory clarity, scalable solutions, and continuous education, the industry can overcome barriers and embrace the benefits, driving efficiency, transparency, and innovation in the world of international trade.

    Future of Blockchain In Trade Finance

    The future of blockchain is being sculpted by a multitude of emerging trends and innovations. Notably, the spotlight is on achieving interoperability among diverse blockchain platforms, facilitating smooth communication and collaboration across networks.

    The landscape of global transactions is on the brink of a transformative era fueled by the boundless potential and thrilling opportunities offered by blockchain-enabled. As this innovative technology continues to evolve and gain widespread acceptance, we can expect remarkable advancements and emerging trends to shape the industry’s future.

    The inherent characteristics of decentralization and transparency that define blockchain provide a sturdy foundation for secure and efficient processes. With growing awareness among key players such as financial institutions, governments, and technology providers, we anticipate an accelerated adoption and seamless integration of blockchain solutions across the realm of global transactions.

  • How to create SAP Crystal Reports Using Blank Report Templates

    What are SAP Crystal Reports?

    SAP Crystal Reports is a powerful business intelligence tool used for designing and generating reports from various data sources. It provides a robust platform for creating highly formatted, pixel-perfect reports that can be distributed electronically or printed. Crystal Reports is widely used across industries to extract meaningful insights and present data in a visually appealing and understandable manner.

    Key features and functionalities of SAP Crystal Reports include:

    1. Data Connectivity: Crystal Reports allows you to connect to a wide range of data sources, including databases like SAP HANA, Oracle, Microsoft SQL Server, and more. It supports both relational and multidimensional data sources, enabling you to access and analyze data from different systems.

    2. Report Design and Layout: The Crystal Reports designer provides a user-friendly interface for designing reports. It offers a WYSIWYG (What You See Is What You Get) editor that allows you to arrange fields, apply formatting, insert charts, images, and other graphical elements. You can create complex reports with grouping, sorting, subreports, cross-tabs, and drill-down functionality.

    3. Powerful Formulas and Expressions: Crystal Reports includes a formula editor that enables you to create custom calculations, expressions, and logic within your reports. This allows for advanced data manipulation, calculations, and conditional formatting based on specific criteria.

    4. Interactive Features: Crystal Reports supports interactive features such as drill-downs, parameterized reports, and dynamic sorting. Users can explore the data and navigate through different levels of details within the report, enhancing the data analysis experience.

    5. Export and Distribution: Reports created in Crystal Reports can be exported to various formats, including PDF, Excel, Word, HTML, and more. This flexibility enables sharing and distribution of reports through email, web portals, or printing.

    6. Integration with SAP and Other Systems: Crystal Reports seamlessly integrates with SAP applications and systems, allowing you to leverage data and business logic directly from SAP. It can also be integrated with other business intelligence tools and platforms to complement larger analytics and reporting solutions.

    7. Report Viewing and Delivery: Crystal Reports provides runtime components and viewers that allow end-users to view and interact with reports without requiring the full design environment. These viewers can be embedded in web applications, desktop applications, or SAP portals for easy access to reports.

    Overall, SAP Crystal Reports empowers organizations to create comprehensive and visually appealing reports that facilitate data-driven decision-making. It is a versatile tool that offers extensive data connectivity, design flexibility, and distribution options, making it a popular choice for reporting and business intelligence needs.

    Steps to Create SAP Crystal Reports Using Blank Report Templates

    To create SAP Crystal Reports using the Blank Report template, you can follow these steps:

    1. Launch the SAP Crystal Reports application on your computer.
    2. Click on “File” in the top menu and select “New” to create a new report.
    3. In the New Report Wizard window, choose “Blank Report” as the template and click “OK.”

    4. The Crystal Reports designer interface will open with a blank canvas. Here, you can design your report by adding fields, formatting elements, and arranging the layout. Follow these steps to create a basic report:

    a. Connect to a Data Source [if there is a data source]:
    – Click on “Database” in the top menu and select “Database Expert.”
    – In the Database Expert window, you can select the data source you want to connect to, such as an SAP database, Microsoft SQL Server, Oracle, etc.
    – Follow the prompts to establish the connection and specify the necessary credentials or connection details.

    b. Add Fields to the Report [if there is a data source]:
    – From the “Field Explorer” pane on the right, expand the data source you connected to and locate the desired fields or tables.
    – Drag and drop the required fields onto the report canvas. You can place them in the report header, details section, or any other desired location.

    c. Format and Customize the Report:
    – Use the various formatting options available in the top menu and toolbar to customize the appearance of the report.
    – You can modify font styles, colors, alignments, add borders, insert images, and more to enhance the visual presentation of the report.

    d. Arrange Report Sections:
    – Crystal Reports divides the report into sections such as Page Header, Report Header, Details, Report Footer, etc.
    – You can resize or reposition these sections by clicking and dragging the section boundaries.
    – To add additional sections, right-click on the report canvas, select “Insert,” and choose the desired section type.

    e. Preview and Save the Report:
    – To preview your report, click on the “Preview” tab in the lower section of the designer interface. This allows you to see how the report will look when generated.
    – Once you are satisfied with the design, click on “File” in the top menu and select “Save” or “Save As” to save the report file (.rpt) to a desired location on your computer.

    5. After saving the report, you can generate it by providing the necessary data at runtime using Crystal Reports runtime libraries or by integrating it into an application or SAP system.

    By following these steps, you can create a basic SAP Crystal Report using the Blank Report template and customize it according to your reporting requirements.

    Tutorial Video

    You can watch the video below to learn implementation:

    [embedyt] https://www.youtube.com/watch?v=m1KD1fT5tII[/embedyt]
  • What is the difference between SAP Crystal Reports and SAP SmartForms

    SAP Crystal Reports and SAP SmartForms are two different tools used for reporting and form generation within the SAP ecosystem. Here are the key differences between the two:

    1. Purpose and Functionality

    – SAP Crystal Reports: It is primarily a reporting tool used to design and generate pixel-perfect, highly formatted reports. Crystal Reports allows you to connect to various data sources, create complex reports with sorting, grouping, aggregations, and add interactive features like drill-downs, charts, and parameters.

    – SAP SmartForms: It is a form generation tool that enables the creation of structured, interactive forms. SmartForms are typically used for printing purposes, such as generating purchase orders, invoices, or other business documents. SmartForms provide basic layout capabilities, support for tables, graphics, and can be integrated with SAP workflows.

    2. Design and Layout

    – Crystal Reports: It offers a rich and flexible design environment with a WYSIWYG (What You See Is What You Get) editor. You have precise control over the placement of elements, formatting options, and can design complex reports with multiple sections, subreports, and cross-tabulations.

    – SmartForms: The design and layout capabilities in SmartForms are more structured and focus on generating forms with fixed positioning. It provides a hierarchical layout, allowing you to define pages, windows, and individual elements within them. SmartForms have limited design features compared to Crystal Reports but are optimized for printing scenarios.

    3. Integration with SAP Systems

    – Crystal Reports: It can connect to various data sources, including SAP systems, and leverage the SAP BusinessObjects suite for advanced reporting and analytics. Crystal Reports can access data from SAP’s Business Warehouse (BW) and other databases, making it suitable for creating comprehensive reports across different systems.

    – SmartForms: It is tightly integrated with SAP systems and is part of the SAP application server. SmartForms directly access SAP data and can utilize the system’s business logic and integration with workflows. It is well-suited for generating forms that are closely tied to SAP processes.

    4. User-Friendliness and Learning Curve

    – Crystal Reports: It provides a more comprehensive and feature-rich reporting environment, which can result in a steeper learning curve for new users. Designing complex reports may require advanced knowledge of the tool and database querying concepts.

    – SmartForms: Compared to Crystal Reports, SmartForms have a simpler and more structured design interface, making it relatively easier to create basic forms. Users familiar with SAP transactions and workflows may find it easier to work with SmartForms.

    In summary, SAP Crystal Reports is a powerful reporting tool suitable for designing detailed reports with various data sources, while SAP SmartForms is a more specialized form generation tool integrated with SAP systems, primarily used for creating structured, printable forms tied to SAP processes. The choice between the two depends on your specific reporting or form generation requirements within the SAP environment.

  • Media Upload and Download using SAP UI5 and Google Firebase Storage

    Introduction

    Welcome to the ultimate guide on performing media upload and download operations using SAP UI5 and Google Firebase Storage! If you’re looking to empower your SAP UI5 application with the ability to handle media files seamlessly, you’ve come to the right place.

    In this comprehensive tutorial, we will walk you through the step-by-step process of integrating SAP UI5, a powerful JavaScript framework for building web applications, with Google Firebase Storage, a scalable and secure cloud storage solution. By combining these technologies, you’ll be able to implement robust media upload and download functionality in your SAP UI5 application.

    Throughout this tutorial, we will cover all aspects of media handling using SAP UI5 and Google Firebase Storage. We’ll guide you through the setup process, including creating a Firebase project and enabling Firebase Storage for your application.

    Next, we’ll delve into the implementation of media upload functionality. You’ll learn how to create a user interface in your SAP UI5 application where users can select and upload media files. We’ll guide you through the process of configuring Firebase Storage rules and utilizing the Firebase Storage SDK to securely upload media files to the cloud.

    After that, we’ll explore the media download process. You’ll discover how to retrieve and display media files from Firebase Storage in your SAP UI5 application. We’ll cover techniques for efficiently managing and organizing media files, allowing users to easily access and download them as needed.

    Additionally, we’ll address advanced features such as handling file metadata, implementing file filtering, and supporting various file formats. You’ll learn how to enhance the user experience by incorporating progress indicators, error handling, and file management functionalities.

    By the end of this tutorial, you’ll have a solid understanding of how to perform media upload and download operations using SAP UI5 and Google Firebase Storage. You’ll be able to seamlessly integrate media handling capabilities into your SAP UI5 application, empowering your users to efficiently manage and access media files.

    So, whether you’re a seasoned SAP UI5 developer or new to web application development, this tutorial is designed to equip you with the knowledge and skills needed to implement media upload and download functionality effectively. Get ready to take your SAP UI5 application to the next level by unlocking the power of media handling with SAP UI5 and Google Firebase Storage!

    Steps to perform Media Upload and Download using SAP UI5 and Google Firebase Storage

    Sure! Here are the steps to perform media upload and download operations using SAP UI5 and Google Firebase Storage:

    1. Set up your SAP UI5 project: Create a new SAP UI5 project or use an existing one. Set up the necessary project structure and dependencies.

    2. Set up Google Firebase: Go to the Firebase console (https://console.firebase.google.com/) and create a new project or use an existing one. Enable Firebase Storage for your project.

    3. Configure Firebase Storage: In the Firebase console, navigate to the Storage section and set up the necessary rules and permissions for your storage buckets. Define the access rules to ensure the security and privacy of your media files.

    4. Connect SAP UI5 with Google Firebase: In your SAP UI5 project, create a new JavaScript file (e.g., “firebase.js”) to handle the connection between SAP UI5 and Google Firebase. Import the necessary Firebase libraries and initialize Firebase with your project’s configuration.

    5. Implement Media Upload: Create a user interface in your SAP UI5 app that allows users to select media files for upload. Implement the logic to capture the selected file(s) and use the Firebase Storage API to upload the media files to Firebase Storage.

    6. Display Uploaded Media: Create a user interface to display the uploaded media files. Retrieve the list of uploaded files from Firebase Storage using the Firebase Storage API and bind them to SAP UI5 controls for display.

    7. Implement Media Download: Create a user interface to enable users to download media files. Implement the logic to download the selected media file(s) from Firebase Storage using the Firebase Storage API.

    8. Advanced Features: Consider implementing additional features such as file metadata management, file filtering, and supporting various file formats. Enhance the user experience by incorporating progress indicators, error handling, and file management functionalities.

    9. Update Storage Rules: To allow the upload and download functionality, you need to update storage rules. For our case, we have removed all the conditions. You can read more about it here.

    Update Storage Rules

    10. Test and Refine: Thoroughly test your media upload and download operations to ensure they are working correctly. Verify that media files can be uploaded, displayed, and downloaded properly. Handle any error scenarios gracefully and provide appropriate feedback to the user.

    By following these steps, you’ll be able to perform media upload and download operations using SAP UI5 and Google Firebase Storage. Remember to consult the documentation for SAP UI5 and Google Firebase Storage for more detailed instructions and best practices. Happy coding!

    UI5 Code to perform Media Upload and Download using Google Firebase Storage

    Main.view.xml

    <mvc:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:l="sap.ui.layout" xmlns:f="sap.ui.layout.form"
        controllerName="firebaseApp.firebaseApp.controller.Main" xmlns:html="http://www.w3.org/1999/xhtml">
        <App>
            <pages>
                <Page title="Media operation using SAP UI5 and Google Storage">
                    <content>
                        <VBox class="sapUiSmallMargin">
                            <UploadCollection id="idMultiUploader" maximumFilenameLength="55" maximumFileSize="10" multiple="true" sameFilenameAllowed="false"
                                instantUpload="false" change="onChangeUpload" fileDeleted="onFileDeleted" fileType="png,jpg,jpeg"
                                filenameLengthExceed="onFilenameLengthExceed" fileSizeExceed="onFileSizeExceed" typeMissmatch="onTypeMissmatch"
                                uploadComplete="onUploadComplete" beforeUploadStarts="onBeforeUploadStarts"/>
                            <Link design="Bold" id="idTextArea" target="_blank" href="" text="Download Media"/>
                        </VBox>
                    </content>
                </Page>
            </pages>
        </App>
    </mvc:View>

     

    Main.controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox"
    ], function (Controller, MessageBox) {
        "use strict";
    
        return Controller.extend("firebaseApp.firebaseApp.controller.Main", {
    
            /**
             * Called when a controller is instantiated and its View controls (if available) are already created.
             * Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
             * @memberOf firebaseApp.firebaseApp.view.Main
             */
            onInit: function (oEvent) {
                this.oRouter = sap.ui.core.UIComponent.getRouterFor(this);
            },
    
            onChangeUpload: function (oEvent) {
                var that = this;
                var collectionName = "Media";
                // Get File
                var file = oEvent.getParameter("files")[0];
                // Create a Store Ref
                var Firestore = this.getView().getModel("fbModel").getData().fireStorage;
                var storageRef = Firestore.ref(collectionName + '/' + file.name);
                // Upload files
                var task = storageRef.put(file);
                // Get Links
                task.on('state_changed',
                    function progress(snapshot) {},
                    function error(err) {
                        MessageBox.error("File Upload failed for: " + file.name + ". Please uplaod this file again!");
                    },
                    function complete(data) {
    
                    });
                var url = 'https://' + 'firebasestorage.googleapis.com/v0/b/myprojectideas-c2512.appspot.com/o/' + collectionName + '%2F' +
                    file.name +
                    '?alt=media';
                if (url) {
                    that.byId("idTextArea").setHref(url);
                }
            },
    
            onTypeMissmatch: function () {
                MessageBox.error("Only png images allowed. Please uplaod this file again!");
            },
    
            onUploadComplete: function () {
                var collectionName = this.byId("idCollection").getValue();
                if (collectionName === "") {
                    this.byId("idMultiUploader").removeAllItems();
                }
            },
    
        });
    
    });

     

    Output

    Media operation using SAP UI5 and Google Storage

  • CRUD operation using SAP UI5 and Google Firestore | Firebase

    Introduction

    Welcome to the comprehensive guide on performing CRUD (Create, Read, Update, Delete) operations using SAP UI5 and Google Firestore! If you’re looking to build a robust web application with real-time data management capabilities, you’re in the right place.

    In this tutorial, we’ll walk you through the process of integrating SAP UI5, a powerful JavaScript framework for building web applications, with Google Firestore, a flexible and scalable NoSQL database. By combining these technologies, you’ll be able to create a dynamic and interactive application that allows users to perform CRUD operations seamlessly.

    Throughout this tutorial, we’ll cover all aspects of the CRUD operations using SAP UI5 and Google Firestore. We’ll guide you through setting up a project in SAP UI5 and configuring the necessary dependencies. You’ll also learn how to create a collection in Google Firestore to store your application’s data.

    We’ll then delve into the implementation of each CRUD operation. You’ll discover how to create new records, retrieve data, update existing records, and delete entries from the Firestore database using SAP UI5. We’ll provide you with code examples, best practices, and tips to ensure a smooth and efficient implementation.

    Additionally, we’ll explore real-time data synchronization capabilities offered by Google Firestore. You’ll learn how to leverage Firestore’s powerful listeners to automatically update your SAP UI5 application whenever changes occur in the database. This will enable you to build responsive and real-time applications that provide an exceptional user experience.

    By the end of this tutorial, you’ll have a solid understanding of how to perform CRUD operations using SAP UI5 and Google Firestore. You’ll be able to create, read, update, and delete data in your application’s database with ease.

    So, whether you’re a seasoned SAP UI5 developer or just starting your journey in web application development, this tutorial is perfect for you. Get ready to unlock the full potential of SAP UI5 and Google Firestore as you master the art of performing CRUD operations in your applications. Let’s get started on this exciting journey of building dynamic and data-driven web applications!

    Steps to perform CRUD operation using SAP UI5 and Google Firestore

    Sure! Here are the steps to perform CRUD (Create, Read, Update, Delete) operations using SAP UI5 and Google Firestore:

    1. Set up your SAP UI5 project: Create a new SAP UI5 project or use an existing one. Set up the necessary project structure and dependencies.

    2. Set up Google Firestore: Go to the Google Cloud Console (https://console.cloud.google.com/) and create a new project or use an existing one. Enable Firestore for your project and set up the necessary Firestore collections and documents to store your application’s data.

    3. Connect SAP UI5 with Google Firestore: In your SAP UI5 project, create a new JavaScript file (e.g., “firestore.js”) to handle the connection between SAP UI5 and Google Firestore. Import the necessary Firestore libraries and initialize the Firestore client with your project’s configuration.

    4. Implement Create operation: Create a user interface in your SAP UI5 app where users can input data for creating new records. In the “firestore.js” file, implement the logic to add new documents to the Firestore collection using the Firestore client API.

    5. Implement Read operation: Create a user interface to display the existing data from Firestore. In the “firestore.js” file, retrieve the data from the Firestore collection using the Firestore client API and bind it to the SAP UI5 controls for display.

    6. Implement Update operation: Create a user interface to allow users to edit existing records. Implement the logic to update the Firestore documents when the user makes changes using the Firestore client API.

    7. Implement Delete operation: Add functionality to delete records from Firestore. Create a user interface to display the existing records and allow users to delete specific entries. Implement the logic to remove documents from the Firestore collection using the Firestore client API.

    8. Update Rules in Firebase: Rules in Firebase are used to restrict wrong users from performing any CRUD operation over data base. You can read more about it here. As of now, we have removed all the restrictions for testing purposes.

    Rules update in Firebase

    9. Test and refine: Thoroughly test your CRUD operations to ensure they are working correctly. Verify that new records can be created, existing records can be retrieved, updated, and deleted. Handle any error scenarios gracefully and provide appropriate feedback to the user.

    By following these steps, you’ll be able to perform CRUD operations using SAP UI5 and Google Firestore. Remember to consult the documentation for SAP UI5 and Google Firestore for more detailed instructions and best practices.

    UI5 Code to Perform CRUD operation using Google Firestore

    index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>firebaseApp</title>
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"firebaseApp.firebaseApp": "./"}'
                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>
             <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>
    
      <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-analytics.js"></script>
    
      <!-- Add Firebase products that you want to use -->
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-auth.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-firestore.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-database.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.23.0/firebase-storage.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-functions.js"></script>
            
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="firebaseApp.firebaseApp" data-id="container" data-settings='{"id" : "firebaseApp"}'></div>
        </body>
    </html>

     

    Firebase.js

    sap.ui.define([
        "sap/ui/model/json/JSONModel",
    ], function (JSONModel) {
        "use strict";
        return {
            // Firebase-config retrieved from the Firebase-console
            initializeFirebase: function () {
                // Replace with your config here
                const firebaseConfig = {
                    apiKey: "AIzaSyBGCi3pHJZqMmpJEeNjnoII8Ic_BL2v8vU",
                    authDomain: "myprojectideas-c2512.firebaseapp.com",
                    projectId: "myprojectideas-c2512",
                    storageBucket: "myprojectideas-c2512.appspot.com",
                    messagingSenderId: "121838639924",
                    appId: "1:121838639924:web:39794cab14d51551172361"
                };
                // Initialize Firebase with the Firebase-config
                firebase.initializeApp(firebaseConfig);
    
                // Create a Firestore reference
                const firestore = firebase.firestore();
    
                // Create a Authentication reference
                const fireAuth = firebase.auth();
    
                // Get Firebase Instance
                const oFirestore = firebase.firestore;
    
                // Create a Fire Storage reference
                const fireStorage = firebase.storage();
    
                // Create a Fire Functions reference
                const fireFunctions = firebase.app().functions('asia-east2');
    
                // Firebase services object
                const oFirebase = {
                    firestore: firestore,
                    fireAuth: fireAuth,
                    oFirestore: oFirestore,
                    fireStorage: fireStorage,
                    fireFunctions: fireFunctions
                };
    
                // Create a Firebase model out of the oFirebase service object which contains all required Firebase services
                var fbModel = new JSONModel(oFirebase);
    
                // Return the Firebase Model
                return fbModel;
            }
        };
    });

     

    model.js

    sap.ui.define([
        "sap/ui/model/json/JSONModel",
        "sap/ui/Device"
    ], function (JSONModel, Device) {
        "use strict";
    
        return {
    
            createDeviceModel: function () {
                var oModel = new JSONModel(Device);
                oModel.setDefaultBindingMode("OneWay");
                return oModel;
            },
    
            //app Congiguration model
            createAppConfigModel: function () {
                var appData = {
                    "otpSent": false
                };
                var oModel = new JSONModel(appData);
                return oModel;
            }
    
        };
    });

     

    manifest.json

    {
        "_version": "1.12.0",
        "sap.app": {
            "id": "firebaseApp.firebaseApp",
            "type": "application",
            "i18n": "i18n/i18n.properties",
            "applicationVersion": {
                "version": "1.0.0"
            },
            "title": "{{appTitle}}",
            "description": "{{appDescription}}",
            "sourceTemplate": {
                "id": "ui5template.basicSAPUI5ApplicationProject",
                "version": "1.40.12"
            }
        },
        "sap.ui": {
            "technology": "UI5",
            "icons": {
                "icon": "",
                "favIcon": "",
                "phone": "",
                "phone@2": "",
                "tablet": "",
                "tablet@2": ""
            },
            "deviceTypes": {
                "desktop": true,
                "tablet": true,
                "phone": true
            }
        },
        "sap.ui5": {
            "flexEnabled": false,
            "rootView": {
                "viewName": "firebaseApp.firebaseApp.view.Login",
                "type": "XML",
                "async": true,
                "id": "Login"
            },
            "dependencies": {
                "minUI5Version": "1.65.6",
                "libs": {
                    "sap.ui.layout": {},
                    "sap.ui.core": {},
                    "sap.m": {}
                }
            },
            "contentDensities": {
                "compact": true,
                "cozy": true
            },
            "models": {
                "i18n": {
                    "type": "sap.ui.model.resource.ResourceModel",
                    "settings": {
                        "bundleName": "firebaseApp.firebaseApp.i18n.i18n"
                    }
                }
            },
            "resources": {
                "css": [{
                    "uri": "css/style.css"
                }]
            },
            "routing": {
                "config": {
                    "routerClass": "sap.m.routing.Router",
                    "viewType": "XML",
                    "async": true,
                    "viewPath": "firebaseApp.firebaseApp.view",
                    "controlAggregation": "pages",
                    "controlId": "app",
                    "clearControlAggregation": false
                },
                "routes": [{
                    "pattern": "",
                    "name": "",
                    "target": "Login"
                }, {
                    "pattern": "Main",
                    "name": "Main",
                    "target": "Main"
                }],
                "targets": {
                    "Login": {
                        "viewType": "XML",
                        "transition": "slide",
                        "clearControlAggregation": false,
                        "viewId": "Login",
                        "viewName": "Login"
                    },
                    "Main": {
                        "viewType": "XML",
                        "transition": "slide",
                        "clearControlAggregation": false,
                        "viewId": "Main",
                        "viewName": "Main"
                    }
                }
            }
        }
    }

     

    component.js

    sap.ui.define([
        "sap/ui/core/UIComponent",
        "sap/ui/Device",
        "firebaseApp/firebaseApp/model/models",
        "firebaseApp/firebaseApp/js/Firebase"
    ], function (UIComponent, Device, models, Firebase) {
        "use strict";
    
        return UIComponent.extend("firebaseApp.firebaseApp.Component", {
    
            metadata: {
                manifest: "json"
            },
    
            /**
             * The component is initialized by UI5 automatically during the startup of the app and calls the init method once.
             * @public
             * @override
             */
            init: function () {
                // call the base component's init function
                UIComponent.prototype.init.apply(this, arguments);
    
                // enable routing
                this.getRouter().initialize();
    
                // set the device model
                this.setModel(models.createDeviceModel(), "device");
    
                // set the app Config model
                this.setModel(models.createAppConfigModel(), "AppConfig");
    
                //set Firebase Model
                this.setModel(Firebase.initializeFirebase(), "fbModel");
            }
        });
    });

     

    login.view.xml

    <mvc:View controllerName="firebaseApp.firebaseApp.controller.Login" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:html="http://www.w3.org/1999/xhtml" xmlns:core="sap.ui.core">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="OTP Login Integration in SAP UI5 using Google Firebase">
                        <content>
                            <VBox height="100%" alignItems="Center">
                                <HBox height="100%" alignItems="Center">
                                    <Image height="70px" class="sapUiLargeMarginEnd"
                                        src="https://www.loc-online.co.uk/berkshire-loc/wp-content/uploads/sites/23/2020/06/Screenshot-2020-05-28-at-16.35.37-266x300.png"/>
                                    <IconTabBar id="idIconTabBarNoIcons" expanded="{device>/isNoPhone}" selectedKey="mail" class="sapUiResponsiveContentPadding">
                                        <items>
                                            <IconTabFilter text="Mobile Login" key="mobile">
                                                <VBox id="idInitialDetails">
                                                    <Label design="Bold" text="Enter Registered Mobile number" required="true"/>
                                                    <HBox>
                                                        <ComboBox id="idcc" selectedKey="65" width="90px" class="sapUiTinyMarginEnd">
                                                            <core:Item key="65" text="+65"/>
                                                            <core:Item key="60" text="+60"/>
                                                            <core:Item key="62" text="+62"/>
                                                            <core:Item key="91" text="+91"/>
                                                        </ComboBox>
                                                        <Input width="200px" id="idMob" required="true" type="Number" placeholder="0000000" submit="ongetOTP"/>
                                                    </HBox>
                                                    <HBox visible="{= ${AppConfig>/otpSent} === true ? false : true}">
                                                        <Button width="145px" class="sapUiTinyMarginEnd" text="Get OTP" press="ongetOTP"/>
                                                        <Button width="145px" text="Reset" press="onReset"/>
                                                    </HBox>
                                                    <Label visible="{AppConfig>/otpSent}" design="Bold" text="OTP" required="true"/>
                                                    <Input visible="{AppConfig>/otpSent}" width="300px" id="idOTP" required="true" submit="onASignin"/>
                                                    <HBox visible="{AppConfig>/otpSent}">
                                                        <Button width="145px" class="sapUiTinyMarginEnd" text="Sign In" press="onASignin"/>
                                                        <Button width="145px" text="Resend OTP" press="ongetOTP"/>
                                                    </HBox>
                                                </VBox>
                                            </IconTabFilter>
                                        </items>
                                    </IconTabBar>
                                    <!--Code for Recaptcha-->
                                    <core:HTML content='&lt;div id=&quot;sign-in-button&quot;&gt;&lt;/div&gt;'></core:HTML>
                                </HBox>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    login.controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox"
    ], function (Controller, MessageBox) {
        "use strict";
    
        return Controller.extend("firebaseApp.firebaseApp.controller.Login", {
            onInit: function () {
                this.oRouter = sap.ui.core.UIComponent.getRouterFor(this);
            },
    
            onAfterRendering: async function () {
                sap.ui.core.BusyIndicator.show();
                await this.onGetRecaptcha();
                sap.ui.core.BusyIndicator.hide();
            },
    
            onGetRecaptcha: function (oEvent) {
                var that = this;
                sap.ui.core.BusyIndicator.show();
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
                    'size': 'invisible',
                    'callback': (response) => {
                        // reCAPTCHA solved, allow signInWithPhoneNumber.
                        sap.ui.core.BusyIndicator.hide();
                    }
                });
            },
    
            ongetOTP: function () {
                sap.ui.core.BusyIndicator.show();
                var appVerifier = window.recaptchaVerifier;
                var that = this;
                var cc = this.byId("idcc")._getSelectedItemText();
                var mob = this.byId("idMob").getValue();
                mob = cc + mob;
                this.phone = mob;
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                firebase.auth().signInWithPhoneNumber(mob, appVerifier)
                    .then((confirmationResult) => {
                        sap.ui.core.BusyIndicator.hide();
                        // SMS sent. Prompt user to type the code from the message, then sign the
                        // user in with confirmationResult.confirm(code).
                        window.confirmationResult = confirmationResult;
                        that.getOwnerComponent().getModel("AppConfig").setProperty("/otpSent", true);
                    }).catch((error) => {
                        sap.ui.core.BusyIndicator.hide();
                        // Error; SMS not sent
                        var errorMessage = error.message;
                        that.getOwnerComponent().getModel("AppConfig").setProperty("/otpSent", false);
                        MessageBox.error(errorMessage);
                    });
            },
    
            onASignin: async function (oEvent) {
                sap.ui.core.BusyIndicator.show();
                var that = this;
                var otp = this.byId("idOTP").getValue();
                var errorMessage = "";
                // Create a Fireauth Auth reference
                var oModel = that.getView().getModel("fbModel").getData();
                localStorage.setItem("oModelFireAuth", JSON.stringify(oModel.fireAuth));
                var fireAuth = oModel.fireAuth;
                var firestoreData = oModel.firestore;
                var fireFunctions = oModel.fireFunctions;
                //get Token for the call
                window.confirmationResult.confirm(otp).then(async(result) => {
                    await fireAuth.currentUser.getIdToken( /* forceRefresh */ true).then(async function (idToken) {
                        MessageBox.success("You are logged in via OTP!");
                        that.oRouter.navTo("Main");
                        sap.ui.core.BusyIndicator.hide();
                    }).catch(function (error) {
                        sap.ui.core.BusyIndicator.hide();
                        that.onReset();
                        MessageBox.error("User is not registered, kindly contact Admin.");
                        fireAuth.signOut().then(function (success) {
                            // MessageBox.error("You are logged out, refresh and try again!");
                        }).catch(function (error) {
                            MessageBox.error(error.error.Error);
                        });
                    });
                }).catch((error) => {
                    // User couldn't sign in (bad verification code?)
                    sap.ui.core.BusyIndicator.hide();
                    errorMessage = error.message;
                    MessageBox.error(errorMessage);
                    fireAuth.signOut().then(function (success) {
                        // jQuery.sap.storage.put(that.userID, null);
                    }).catch(function (error) {});
                });
            },
    
            onReset: function (oEvent) {
                this.byId("idOTP").setValue("");
                this.byId("idMob").setValue("");
                this.getOwnerComponent().getModel("AppConfig").setProperty("/otpSent", false);
            }
        });
    });

     

    main.view.xml

    <mvc:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:l="sap.ui.layout" xmlns:f="sap.ui.layout.form"
        controllerName="firebaseApp.firebaseApp.controller.Main" xmlns:html="http://www.w3.org/1999/xhtml">
        <App>
            <pages>
                <Page title="CRUD operation using SAP UI5 and Google Firestore">
                    <content>
                        <VBox class="sapUiSmallMargin">
                            <f:SimpleForm id="SimpleFormOrg" editable="true" layout="ResponsiveGridLayout" title="Organizations" labelSpanXL="3" labelSpanL="3"
                                labelSpanM="3" labelSpanS="12" adjustLabelSpan="false" emptySpanXL="4" emptySpanL="4" emptySpanM="4" emptySpanS="0" columnsXL="1"
                                columnsL="1" columnsM="1" singleContainerFullSize="false">
                                <f:content>
                                    <Label text="Name of Organization"/>
                                    <Input id="idOrgName"/>
                                    <Button text="Add" type="Accept" press="onAddOrg"/>
                                </f:content>
                            </f:SimpleForm>
                            <Table id="idOrgTable" inset="false" items="{/orgs}" sticky="ColumnHeaders,HeaderToolbar" class="sapFDynamicPageAlignContent" width="auto">
                                <columns>
                                    <Column>
                                        <Text text="ID"/>
                                    </Column>
                                    <Column>
                                        <Text text="Name of Organization"/>
                                    </Column>
                                    <Column vAlign="Right">
                                        <Text text="New Name"/>
                                    </Column>
                                    <Column vAlign="Right">
                                        <Text text="Perform Operations"/>
                                    </Column>
                                </columns>
                                <items>
                                    <ColumnListItem>
                                        <cells>
                                            <Text text="{ID}"/>
                                            <Text text="{name}"/>
                                            <Input value="{newName}"/>
                                            <HBox alignItems="Center" justifyContent="Start">
                                                <Button icon="sap-icon://edit" press="onUpdate"/>
                                                <Button icon="sap-icon://delete" press="onDelete"/>
                                            </HBox>
                                        </cells>
                                    </ColumnListItem>
                                </items>
                            </Table>
                        </VBox>
                    </content>
                </Page>
            </pages>
        </App>
    </mvc:View>

     

    main.controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox"
    ], function (Controller, MessageBox) {
        "use strict";
    
        return Controller.extend("firebaseApp.firebaseApp.controller.Main", {
    
            /**
             * Called when a controller is instantiated and its View controls (if available) are already created.
             * Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
             * @memberOf firebaseApp.firebaseApp.view.Main
             */
            onInit: function (oEvent) {
                this.oRouter = sap.ui.core.UIComponent.getRouterFor(this);
            },
    
            onAfterRendering: async function () {
                this.onSelectOrg();
            },
    
            onSelectOrg: function () {
                var that = this;
                var oItems = {};
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                var collRefUsers = firestoreData.collection("Organization");
                collRefUsers.onSnapshot(collection => {
                    var aItems = collection.docs.map(function (docUser) {
                        var finalData = docUser.data();
                        finalData.ID = docUser.id;
                        return finalData;
                    });
                    oItems.orgs = aItems;
                    // Create and set the created object to the the UserModel
                    var oModel = new sap.ui.model.json.JSONModel(oItems);
                    this.getView().byId("idOrgTable").setModel(oModel);
                    sap.ui.core.BusyIndicator.hide();
                }, error => {
                    sap.ui.core.BusyIndicator.hide();
                    // MessageBox.error("Missing or insufficient permissions!");
                });
    
            },
    
            onAddOrg: function () {
                var that = this;
                var org = this.byId("idOrgName").getValue();
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                var collRefUsers = firestoreData.collection("Organization");
                if (org) {
                    collRefUsers.doc(org).set({
                        name: org
                    }).then(function (success) {
                        sap.m.MessageBox.success("Organization Added Successfully!");
                        that.byId("idOrgName").setValue("");
                    }).catch(function (error) {
                        // Handle Errors here.
                        var errorMessage = error.message;
                        MessageBox.error(errorMessage);
                    });
                } else {
                    MessageBox.error("Enter an Organization Name to Add!");
                }
            },
    
            onDelete: function (oEvent) {
                var that = this;
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                var collRefUsers = firestoreData.collection("Organization");
                var selected = oEvent.getSource().getBindingContext().getObject().ID;
                sap.m.MessageBox.confirm("Do you want to Delete selected Organization?", function (rValue) {
                    if (rValue == "OK") {
                        collRefUsers.doc(selected).delete().then(function () {
                            sap.m.MessageBox.success("Organization Deleted!");
                        }).catch(function (error) {
                            // Handle Errors here.
                            var errorMessage = error.message;
                            MessageBox.error(errorMessage);
                        });
                    } else {}
                });
            },
    
            onUpdate: function (oEvent) {
                var that = this;
                var selected = oEvent.getSource().getBindingContext().getObject().name;
                var updated = oEvent.getSource().getBindingContext().getObject().newName;
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                var collRefUsers = firestoreData.collection("Organization");
                sap.m.MessageBox.confirm("Do you want to Update selected Organization?", function (rValue) {
                    if (rValue == "OK") {
                        collRefUsers.doc(selected).update({
                            name: updated
                        }).then(function (success) {
                            sap.m.MessageBox.success("Organization Updated Successfully!");
                        }).catch(function (error) {
                            // Handle Errors here.
                            var errorMessage = error.message;
                            MessageBox.error(errorMessage);
                        });
                    } else {}
                });
            }
    
        });
    
    });

    Output

    CRUD operation using SAP UI5 and Google Firestore

  • OTP Login Integration in SAP UI5 using Google Firebase

    Introduction

    Welcome to the ultimate guide for integrating OTP (One-Time Password) login functionality in SAP UI5 using the power of Google Firebase! If you’re looking to enhance the security and user experience of your SAP UI5 application, implementing OTP login is a fantastic choice.

    In this comprehensive tutorial, we will walk you through the step-by-step process of seamlessly integrating OTP login functionality into your SAP UI5 application using Google Firebase. By leveraging Firebase’s robust authentication services, you can provide users with a secure and convenient login experience.

    In the world of modern web applications, OTP login has become increasingly popular due to its effectiveness in preventing unauthorized access. With OTP login, users receive a unique, time-sensitive code via SMS or email, which they enter to authenticate themselves. This adds an extra layer of security to your application.

    Throughout this tutorial, we will cover everything you need to know to successfully integrate OTP login in your SAP UI5 application. Starting from setting up a Firebase project and configuring the necessary Firebase services, to implementing OTP generation and verification logic within your application, we’ve got you covered.

    You will learn how to leverage Firebase Authentication and the Firebase SDK to generate and send OTP codes to users. We will guide you through the process of capturing and validating OTPs, ensuring a smooth and secure login process. Additionally, we’ll explore best practices for handling error scenarios and improving the overall user experience.

    By the end of this tutorial, you’ll have a fully functional OTP login system integrated seamlessly into your SAP UI5 application, powered by the secure and reliable infrastructure of Google Firebase.

    So, if you’re ready to take your SAP UI5 application’s security to the next level, join us in this exciting journey of OTP login integration. Let’s get started on creating a secure, user-friendly, and highly-protected login system for your SAP UI5 application using Google Firebase.

    OTP Login Integration in SAP UI5 using Google Firebase

    Sure! Here are the steps to do OTP login integration in SAP UI5 using Google Firebase:

    1. Set up a Firebase project: Create a new Firebase project or use an existing one. Go to the Firebase console (https://console.firebase.google.com/) and create a new project. Enable the Firebase Authentication service for your project.

    Enable Authentication in Google Firebase

    Enable the test OPT Mobile Number in Google Firebase:

    Test OPT Mobile Number in Google Firebase

    2. Install the Firebase SDK: In your SAP UI5 project, open the terminal or command prompt and navigate to the project directory. Run the following command to install the Firebase JavaScript SDK:

    npm install firebase

    3. Initialize Firebase: Create a new JavaScript file in your SAP UI5 project, such as “firebase.js”. Import the Firebase SDK and initialize Firebase with your project’s configuration. Obtain the Firebase configuration object from the Firebase console by navigating to Project Settings > General > Your apps > Firebase SDK snippet. Copy the code snippet for the web app configuration and paste it into your “firebase.js” file.

    4. Generate and send OTP: Implement a user interface in your SAP UI5 app where users can enter their phone number or email address. When the user requests an OTP, use the Firebase Authentication SDK to generate and send the OTP to the provided phone number or email address.

    5. Verify OTP: Create another user interface where users can enter the OTP they received. Use the Firebase Authentication SDK to verify the entered OTP against the generated OTP. If the verification is successful, proceed with the login process.

    6. Handle authentication events: Implement Firebase authentication state listeners to detect when a user is logged in or logged out. Update your SAP UI5 app’s UI and behavior accordingly based on the user’s authentication status.

    7. Test and refine: Test the OTP login integration thoroughly to ensure a smooth user experience. Verify that OTPs are generated and delivered correctly and that the verification process is working as expected. Handle error scenarios gracefully and provide appropriate feedback to the user.

    By following these steps, you’ll be able to integrate OTP login functionality into your SAP UI5 application using Google Firebase. Remember to consult the Firebase documentation and the SAP UI5 guidelines for more detailed instructions and best practices. Happy coding!

    UI5 Code to Integrate OTP Login using Google Firebase

    index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <!--<meta name="viewport" content="width=device-width, initial-scale=1.0">-->
            <title>HealthBridge Doctor</title>
              <link rel="icon" type="image/x-icon" href="https://healthbridge-intl.com/wp-content/uploads/2021/09/cropped-Colour-Logo-Only-1-32x32.png">
            <script id="sap-ui-bootstrap"
                src="https://openui5.hana.ondemand.com/1.96.7/resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"Healthbridge-Doctor.Healthbridge-Doctor": "./"}'
                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>
    <!--Check if device is mobile: Create a media condition that targets viewports at least 768px wide-->
    <script>
    const mediaQuery = window.matchMedia('(max-width: 768px)')
    // Check if the media query is true
    if (mediaQuery.matches) {
      // Then trigger an alert
      alert('This device is not supported, contact Admin!')
      window.location = 'https://healthbridge-intl.com/';
    }
    </script>
            <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->
    <script type="text/javascript" src="https://unpkg.com/virgil-crypto@^4.0.0/dist/browser.umd.js"></script>
       <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>
    
      <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-analytics.js"></script>
    
      <!-- Add Firebase products that you want to use -->
      <script src="https://www.gstatic.com/firebasejs/7.23.0/firebase-auth.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-firestore.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-database.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.23.0/firebase-storage.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-functions.js"></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="Healthbridge-Doctor.Healthbridge-Doctor" data-id="container" data-settings='{"id" : "Healthbridge-Doctor"}'></div>
        </body>
    </html>

     

    Model.js

    sap.ui.define([
        "sap/ui/model/json/JSONModel",
        "sap/ui/Device"
    ], function (JSONModel, Device) {
        "use strict";
    
        return {
    
            createDeviceModel: function () {
                var oModel = new JSONModel(Device);
                oModel.setDefaultBindingMode("OneWay");
                return oModel;
            },
    
            //app Congiguration model
            createAppConfigModel: function () {
                var appData = {
                    "otpSent": false
                };
                var oModel = new JSONModel(appData);
                return oModel;
            }
    
        };
    });

     

    Firebase.js

    sap.ui.define([
        "sap/ui/model/json/JSONModel",
    ], function (JSONModel) {
        "use strict";
        return {
            // Firebase-config retrieved from the Firebase-console
            initializeFirebase: function () {
                // Replace with your config here
                const firebaseConfig = {
                    apiKey: "AIzaSyBGCi3pHJZqMmpJEeNjnoII8Ic_BL2v8vU",
                    authDomain: "myprojectideas-c2512.firebaseapp.com",
                    projectId: "myprojectideas-c2512",
                    storageBucket: "myprojectideas-c2512.appspot.com",
                    messagingSenderId: "121838639924",
                    appId: "1:121838639924:web:39794cab14d51551172361"
                };
                // Initialize Firebase with the Firebase-config
                firebase.initializeApp(firebaseConfig);
    
                // Create a Firestore reference
                const firestore = firebase.firestore();
    
                // Create a Authentication reference
                const fireAuth = firebase.auth();
    
                // Get Firebase Instance
                const oFirestore = firebase.firestore;
    
                // Create a Fire Storage reference
                const fireStorage = firebase.storage();
    
                // Create a Fire Functions reference
                const fireFunctions = firebase.app().functions('asia-east2');
    
                // Firebase services object
                const oFirebase = {
                    firestore: firestore,
                    fireAuth: fireAuth,
                    oFirestore: oFirestore,
                    fireStorage: fireStorage,
                    fireFunctions: fireFunctions
                };
    
                // Create a Firebase model out of the oFirebase service object which contains all required Firebase services
                var fbModel = new JSONModel(oFirebase);
    
                // Return the Firebase Model
                return fbModel;
            }
        };
    });

     

    Component.js

    sap.ui.define([
        "sap/ui/core/UIComponent",
        "sap/ui/Device",
        "firebaseApp/firebaseApp/model/models",
        "firebaseApp/firebaseApp/js/Firebase"
    ], function (UIComponent, Device, models, Firebase) {
        "use strict";
    
        return UIComponent.extend("firebaseApp.firebaseApp.Component", {
    
            metadata: {
                manifest: "json"
            },
    
            /**
             * The component is initialized by UI5 automatically during the startup of the app and calls the init method once.
             * @public
             * @override
             */
            init: function () {
                // call the base component's init function
                UIComponent.prototype.init.apply(this, arguments);
    
                // enable routing
                this.getRouter().initialize();
    
                // set the device model
                this.setModel(models.createDeviceModel(), "device");
    
                // set the app Config model
                this.setModel(models.createAppConfigModel(), "AppConfig");
    
                //set Firebase Model
                this.setModel(Firebase.initializeFirebase(), "fbModel");
            }
        });
    });

     

    Login.view.xml

    <mvc:View controllerName="firebaseApp.firebaseApp.controller.Login" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:html="http://www.w3.org/1999/xhtml" xmlns:core="sap.ui.core">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="OTP Login Integration in SAP UI5 using Google Firebase">
                        <content>
                            <VBox height="100%" alignItems="Center">
                                <HBox height="100%" alignItems="Center">
                                    <Image height="70px" class="sapUiLargeMarginEnd"
                                        src="https://www.loc-online.co.uk/berkshire-loc/wp-content/uploads/sites/23/2020/06/Screenshot-2020-05-28-at-16.35.37-266x300.png"/>
                                    <IconTabBar id="idIconTabBarNoIcons" expanded="{device>/isNoPhone}" selectedKey="mail" class="sapUiResponsiveContentPadding">
                                        <items>
                                            <IconTabFilter text="Mobile Login" key="mobile">
                                                <VBox id="idInitialDetails">
                                                    <Label design="Bold" text="Enter Registered Mobile number" required="true"/>
                                                    <HBox>
                                                        <ComboBox id="idcc" selectedKey="65" width="90px" class="sapUiTinyMarginEnd">
                                                            <core:Item key="65" text="+65"/>
                                                            <core:Item key="60" text="+60"/>
                                                            <core:Item key="62" text="+62"/>
                                                            <core:Item key="91" text="+91"/>
                                                        </ComboBox>
                                                        <Input width="200px" id="idMob" equired="true" type="Number" placeholder="0000000" submit="ongetOTP"/>
                                                    </HBox>
                                                    <HBox visible="{= ${AppConfig>/otpSent} === true ? false : true}">
                                                        <Button width="145px" class="sapUiTinyMarginEnd" text="Get OTP" press="ongetOTP"/>
                                                        <Button width="145px" text="Reset" press="onReset"/>
                                                    </HBox>
                                                    <Label visible="{AppConfig>/otpSent}" design="Bold" text="OTP" required="true"/>
                                                    <Input visible="{AppConfig>/otpSent}" width="300px" id="idOTP" required="true" submit="onASignin"/>
                                                    <HBox visible="{AppConfig>/otpSent}">
                                                        <Button width="145px" class="sapUiTinyMarginEnd" text="Sign In" press="onASignin"/>
                                                        <Button width="145px" text="Resend OTP" press="ongetOTP"/>
                                                    </HBox>
                                                </VBox>
                                            </IconTabFilter>
                                        </items>
                                    </IconTabBar>
                                    <!--Code for Recaptcha-->
                                    <core:HTML content='&lt;div id=&quot;sign-in-button&quot;&gt;&lt;/div&gt;'></core:HTML>
                                </HBox>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Login.controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox"
    ], function (Controller, MessageBox) {
        "use strict";
    
        return Controller.extend("firebaseApp.firebaseApp.controller.Login", {
            onInit: function () {
    
            },
    
            onAfterRendering: async function () {
                sap.ui.core.BusyIndicator.show();
                await this.onGetRecaptcha();
                sap.ui.core.BusyIndicator.hide();
            },
    
            onGetRecaptcha: function (oEvent) {
                var that = this;
                sap.ui.core.BusyIndicator.show();
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
                    'size': 'invisible',
                    'callback': (response) => {
                        // reCAPTCHA solved, allow signInWithPhoneNumber.
                        sap.ui.core.BusyIndicator.hide();
                    }
                });
            },
    
            ongetOTP: function () {
                sap.ui.core.BusyIndicator.show();
                var appVerifier = window.recaptchaVerifier;
                var that = this;
                var cc = this.byId("idcc")._getSelectedItemText();
                var mob = this.byId("idMob").getValue();
                mob = cc + mob;
                this.phone = mob;
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                firebase.auth().signInWithPhoneNumber(mob, appVerifier)
                    .then((confirmationResult) => {
                        sap.ui.core.BusyIndicator.hide();
                        // SMS sent. Prompt user to type the code from the message, then sign the
                        // user in with confirmationResult.confirm(code).
                        window.confirmationResult = confirmationResult;
                        that.getOwnerComponent().getModel("AppConfig").setProperty("/otpSent", true);
                    }).catch((error) => {
                        sap.ui.core.BusyIndicator.hide();
                        // Error; SMS not sent
                        var errorMessage = error.message;
                        that.getOwnerComponent().getModel("AppConfig").setProperty("/otpSent", false);
                        MessageBox.error(errorMessage);
                    });
            },
    
            onASignin: async function (oEvent) {
                sap.ui.core.BusyIndicator.show();
                var that = this;
                var otp = this.byId("idOTP").getValue();
                var errorMessage = "";
                // Create a Fireauth Auth reference
                var oModel = that.getView().getModel("fbModel").getData();
                localStorage.setItem("oModelFireAuth", JSON.stringify(oModel.fireAuth));
                var fireAuth = oModel.fireAuth;
                var firestoreData = oModel.firestore;
                var fireFunctions = oModel.fireFunctions;
                //get Token for the call
                window.confirmationResult.confirm(otp).then(async(result) => {
                    await fireAuth.currentUser.getIdToken( /* forceRefresh */ true).then(async function (idToken) {
                        MessageBox.success("You are logged in via OTP!");
                        sap.ui.core.BusyIndicator.hide();
                    }).catch(function (error) {
                        sap.ui.core.BusyIndicator.hide();
                        that.onReset();
                        MessageBox.error("User is not registered, kindly contact Admin.");
                        fireAuth.signOut().then(function (success) {
                            // MessageBox.error("You are logged out, refresh and try again!");
                        }).catch(function (error) {
                            MessageBox.error(error.error.Error);
                        });
                    });
                }).catch((error) => {
                    // User couldn't sign in (bad verification code?)
                    sap.ui.core.BusyIndicator.hide();
                    errorMessage = error.message;
                    MessageBox.error(errorMessage);
                    fireAuth.signOut().then(function (success) {
                        // jQuery.sap.storage.put(that.userID, null);
                    }).catch(function (error) {});
                });
            },
    
            onReset: function (oEvent) {
                this.byId("idOTP").setValue("");
                this.byId("idMob").setValue("");
                this.getOwnerComponent().getModel("AppConfig").setProperty("/otpSent", false);
            }
        });
    });

     

    Output

    OTP Login Output UI5

  • Email and Password Login Integration in SAP UI5 using Google Firebase

    Introduction

    Welcome to the comprehensive guide on integrating email and password login functionality in SAP UI5 using Google Firebase! Securing your SAP UI5 application with user authentication is crucial for protecting sensitive data and providing a personalized user experience. By leveraging the power of Google Firebase, you can easily implement a robust and secure login system.

    In this tutorial, we will walk you through the step-by-step process of integrating email and password login functionality into your SAP UI5 application. By following these instructions, you’ll be able to authenticate users using their email and password, ensuring a seamless and secure login experience.

    We’ll start by setting up Google Firebase and enabling the Email/Password authentication provider. Firebase simplifies the authentication process, handling all the necessary backend operations for you. You’ll learn how to install the Firebase SDK into your SAP UI5 project and initialize Firebase with your project’s configuration.

    Next, we’ll guide you in implementing the login functionality within your SAP UI5 app. You’ll create a login page or dialog where users can enter their email and password. We’ll demonstrate how to capture user input and utilize Firebase’s signInWithEmailAndPassword method to authenticate the user securely.

    Furthermore, we’ll show you how to handle authentication state events to dynamically adjust your application’s behavior based on whether a user is logged in or logged out. This will enable you to tailor the user experience and provide access to protected routes or resources.

    Lastly, we’ll emphasize the importance of testing and refining your email and password login integration. Ensuring that users can successfully log in, handling authentication errors gracefully, and implementing additional security measures such as password reset functionality or email verification will enhance the overall user experience.

    By the end of this tutorial, you’ll have a fully functional email and password login system integrated seamlessly into your SAP UI5 application, powered by the robust authentication capabilities of Google Firebase.

    So let’s get started on this exciting journey of empowering your SAP UI5 app with secure user authentication using email and password login integration with Google Firebase!

    How to do Email and Password Login Integration in SAP UI5 using Google Firebase

    Integrating email and password login functionality in SAP UI5 using Google Firebase is a powerful way to provide secure authentication for your application users. Follow these steps to accomplish this integration:

    1. Set up Google Firebase: Create a Firebase project and enable the Authentication service. Navigate to the Firebase console and click on “Authentication” in the left-hand menu. Enable the “Email/Password” authentication provider.
    2. Install Firebase SDK: In your SAP UI5 project, open the terminal or command prompt and navigate to the project directory. Run the following command to install the Firebase JavaScript SDK:
      npm install firebase
      

       

    3. Initialize Firebase: Create a new JavaScript file in your SAP UI5 project, such as “firebase.js”. Import the Firebase SDK and initialize Firebase with your project’s configuration. Obtain the Firebase configuration object from the Firebase console by navigating to Project Settings > General > Your apps > Firebase SDK snippet. Copy the code snippet for the web app configuration and paste it into your “firebase.js” file.
    4. Implement the login functionality: In your SAP UI5 app, create a login page or a dialog where users can enter their email and password. Capture the user’s input and use the Firebase SDK methods to authenticate the user. For example, use the signInWithEmailAndPassword method to authenticate the user with their email and password.
      Enable Authentication in Google Firebase
    5. Handle authentication events: Firebase provides authentication state events that allow you to handle changes in the user’s authentication status. Implement event listeners to detect when a user logs in or logs out. You can display different content or redirect the user to different pages based on their authentication status.
    6. Secure routes and resources: To ensure that only authenticated users can access certain routes or resources in your SAP UI5 app, implement security checks using Firebase Authentication. You can restrict access to specific routes or components based on the user’s authentication status or their assigned roles.
    7. Test and refine: Test the email and password login integration thoroughly to ensure it functions as expected. Verify that users can log in with their credentials and that appropriate error handling is in place. Consider adding features like password reset functionality or email verification to enhance the user experience and security.

    By following these steps, you can successfully integrate email and password login functionality using Google Firebase in your SAP UI5 application. Remember to consult the Firebase documentation and the SAP UI5 guidelines for more detailed instructions and best practices. Happy coding!

    UI5 Code to Integrate Email and Password Login using Google Firebase

    Login.view.xml

    <mvc:View controllerName="firebaseApp.firebaseApp.controller.Login" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:html="http://www.w3.org/1999/xhtml" xmlns:core="sap.ui.core">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Email and Password Login Integration in SAP UI5 using Google Firebase">
                        <content>
                            <VBox height="100%" alignItems="Center">
                                <HBox height="100%" alignItems="Center">
                                    <Image height="100px" class="sapUiLargeMarginEnd"
                                        src="https://www.loc-online.co.uk/berkshire-loc/wp-content/uploads/sites/23/2020/06/Screenshot-2020-05-28-at-16.35.37-266x300.png"/>
                                    <IconTabBar id="idIconTabBarNoIcons" expanded="{device>/isNoPhone}" selectedKey="mail" class="sapUiResponsiveContentPadding">
                                        <items>
                                            <IconTabFilter text="Email Login" key="mail">
                                                <VBox id="idMailDetails">
                                                    <Label design="Bold" text="Enter Registered Email ID" required="true"/>
                                                    <Input width="300px" id="idu_admin" required="true" placeholder="username@mail.com" submit="onEmailSignin"/>
                                                    <Label design="Bold" text="Enter Password" required="true"/>
                                                    <Input width="300px" id="idp_admin" required="true" type="Password" placeholder="*****" submit="onEmailSignin"/>
                                                    <HBox>
                                                        <Button width="145px" class="sapUiTinyMarginEnd" text="Sign In" press="onEmailSignin"/>
                                                        <Button width="145px" text="Reset" press="onReset"/>
                                                    </HBox>
                                                </VBox>
                                            </IconTabFilter>
                                        </items>
                                    </IconTabBar>
                                </HBox>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Login.controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("firebaseApp.firebaseApp.controller.Login", {
            onInit: function () {
                
            },
    
            onEmailSignin: function (oEvent) {
                var that = this;
                sap.ui.core.BusyIndicator.show();
                var email = this.byId("idu_admin").getValue();
                var password = this.byId("idp_admin").getValue();
                var errorMessage = "";
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                var firestoreData = oModel.firestore;
                fireAuth.signInWithEmailAndPassword(email, password).then(function (usersigned) {
                    sap.ui.core.BusyIndicator.hide();
                    MessageBox.success("You are Logged in!");
                    that.onReset();
                }).catch(function (error) {
                    sap.ui.core.BusyIndicator.hide();
                    // Handle Errors here.
                    errorMessage = error.message;
                    MessageBox.error(errorMessage);
                });
            },
    
            onReset: function (oEvent) {
                this.byId("idu_admin").setValue("");
                this.byId("idp_admin").setValue("");
            }
        });
    });

    Output

    Email and Password Login Integration in SAP UI5 using Google Firebase