Category: UI5

  • Convert Excel data to JSON Data in SAP UI5

    Introduction

    Welcome to our comprehensive guide on ‘Converting Excel Data to JSON Data in SAP UI5.’ This practical approach simplifies the way we manage and interpret large Excel data sets, translating them into compact, easy-to-handle JSON files within the SAP UI5 framework. With this strategy, we aim to improve your data integration processes and quicken application development, allowing for more efficient and streamlined operations. We will learn how to Upload an excel file and convert it into JSON and bind it to the table or any other component.

    Excel to JSON in JavaScript

    Converting Excel data to JSON format in JavaScript typically involves parsing the Excel file, reading its data, and then transforming it into JSON format. Here is a simple step-by-step process using the ‘xlsx’ library, a popular JavaScript library to read, write and parse various spreadsheet formats.

    1. Create an HTML input element of type ‘file’ that accepts Excel files, allowing the user to select an Excel file from their device.

    2. Use the FileReader API to read the content of the selected file. The FileReader API is part of the web API and allows you to read file content in JavaScript.

    3. Use a library like `xlsx` to parse the Excel data. The parsing process converts the raw file data into a format that the library can work with.

    4. Extract a specific worksheet from the workbook. If you’re unsure, you can simply extract the first sheet.

    5. Use a function provided by the `xlsx` library to convert the worksheet data into JSON format.

    6. At this point, the Excel data has been converted into an array of JavaScript objects (JSON format). You can now use this data in your application.

    xlsx.js library

    The xlsx.js library is a robust and comprehensive JavaScript library that is designed to simplify the process of parsing and manipulating Excel files within the browser and Node.js. The library provides the capability to read and write various spreadsheet formats such as XLSX, XLSM, XLSB, and ODS.

    Convert Excel data to JSON Data in SAP UI5

    Index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>My Project Ideas</title>
            <link rel="icon" type="image/x-icon" href="https://myprojectideas.com/wp-content/uploads/2021/08/cropped-Screenshot-2021-07-26-at-1.39.04-PM.png"/>
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"exceltoJson.exceltoJson": "./"}'
                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>
            <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="exceltoJson.exceltoJson" data-id="container" data-settings='{"id" : "exceltoJson"}'></div>
        </body>
    </html>

     

    View

    <mvc:View controllerName="exceltoJson.exceltoJson.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:u="sap.ui.unified">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="My Project Ideas: Converting Excel data to JSON Data in UI5">
                        <content>
                            <u:FileUploader id="fileUploader" change="onFileUpload"/>
                            <TextArea id="textArea" rows="10" width="100%" editable="false"/>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("exceltoJson.exceltoJson.controller.Main", {
            onInit: function () {
    
            },
    
            onFileUpload: function (event) {
                var that = this;
                var file = event.getParameter("files")[0];
                var reader = new FileReader();
    
                reader.onload = function (e) {
                    var data = new Uint8Array(e.target.result);
                    var workbook = XLSX.read(data, {
                        type: 'array'
                    });
    
                    // Extract data from the first sheet
                    var worksheet = workbook.Sheets[workbook.SheetNames[0]];
                    var jsonData = XLSX.utils.sheet_to_json(worksheet);
    
                    // Use the jsonData as desired (e.g., display in a table, perform operations, etc.)
                    console.log(jsonData);
                    that.byId("textArea").setValue(JSON.stringify(jsonData));
                };
    
                reader.readAsArrayBuffer(file);
            }
    
        });
    });

     

    Input

    Output

  • Convert a JSON to Excel in SAP UI5

    Introduction

    Looking to seamlessly convert JSON data to Excel format within your SAP UI5 application? Look no further! In this comprehensive guide, we’ll walk you through a step-by-step process to effortlessly convert JSON data to Excel spreadsheets using SAP UI5. This powerful integration allows you to efficiently export and share your data in a user-friendly Excel format, enabling better data analysis and collaboration across your organization. Follow along to unlock the full potential of your SAP UI5 application by mastering the art of JSON to Excel conversion. Let’s dive in and learn How can we export JSON data to EXCEL in SAPUI5.

    JSON to Excel in JavaScript

    JSON (JavaScript Object Notation) is a lightweight data-interchange format that is widely used for storing and exchanging data. It is easy for humans to read and write, and also easy for machines to parse and generate. On the other hand, Excel is a popular spreadsheet program that allows users to store, organize, and analyze data in a tabular format.

    Converting JSON to Excel in JavaScript involves the process of transforming JSON data into a format compatible with Excel. This transformation is typically done using JavaScript libraries or functions that facilitate data manipulation and export capabilities.

    The steps involved in the JSON to Excel conversion process using JavaScript are as follows:

    1. Parsing JSON Data: The first step is to parse the JSON data and convert it into a JavaScript object, which allows for easy access and manipulation of the data.

    2. Creating Excel-Compatible Data: Next, JavaScript functions or libraries are used to structure the JSON data into a format that can be interpreted by Excel. This may involve converting the JSON object into an array of arrays or other Excel-friendly data structures.

    3. Generating Excel File: Once the data is prepared in a compatible format, JavaScript can be used to generate an Excel file. This process involves creating the appropriate Excel file format, populating it with the converted JSON data, and configuring any necessary settings, such as cell formatting and sheet names.

    4. Download or Display: Finally, the generated Excel file can be made available to the user for download or displayed directly within the web application, depending on the desired functionality.

    By leveraging the power of JavaScript and its libraries, developers can seamlessly convert JSON data to Excel format, enabling efficient data handling and analysis in Excel spreadsheets. This capability is valuable for web applications that need to export data for reporting, sharing, or further analysis in the familiar Excel environment.

    xlsx.js library

    xlsx.js is a powerful JavaScript library that enables seamless manipulation and generation of Microsoft Excel files (XLSX format) directly within web applications. With xlsx.js, developers can create, read, modify, and export Excel spreadsheets using pure JavaScript code, eliminating the need for server-side processing or browser plugins.

    Convert a JSON to Excel in SAP UI5

    Index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>My Project Ideas</title>
            <link rel="icon" type="image/x-icon" href="https://myprojectideas.com/wp-content/uploads/2021/08/cropped-Screenshot-2021-07-26-at-1.39.04-PM.png"/>
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"excelProject.excelProject": "./"}'
                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>
            <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="excelProject.excelProject" data-id="container" data-settings='{"id" : "excelProject"}'></div>
        </body>
    </html>

     

    View

    <mvc:View controllerName="excelProject.excelProject.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="My Project Ideas: Convert a JSON to Excel in UI5">
                        <content>
                            <Button text="Export to Excel" press="onExportToExcel"/>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("excelProject.excelProject.controller.Main", {
            onInit: function () {
    
            },
    
            onExportToExcel: function () {
                // Get the JSON data
                var jsonData = [{
                    Name: "John",
                    Age: 25,
                    City: "New York"
                }, {
                    Name: "Alice",
                    Age: 30,
                    City: "London"
                }, {
                    Name: "Bob",
                    Age: 35,
                    City: "Paris"
                }];
    
                // Convert JSON to Excel workbook
                var workbook = XLSX.utils.book_new();
                var worksheet = XLSX.utils.json_to_sheet(jsonData);
                XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
    
                // Save the workbook as an Excel file
                XLSX.writeFile(workbook, "data.xlsx");
            }
    
        });
    });

     

    Output

    Convert a JSON to Excel in SAP UI5

  • Multiupload multiple files one by one in SAP UI5 (Sync Multiple Files Upload)

    Introduction

    Boost your productivity with the power of synchronous multiple file upload in SAP UI5. With our innovative solution, you can easily and efficiently upload multiple files one by one, simplifying your workflow and saving valuable time. Say goodbye to the hassle of uploading files individually and embrace the convenience of synchronous file uploads. Streamline your processes, enhance collaboration, and improve efficiency with Sync Multiple Files Upload in SAP UI5. Experience a seamless and optimized file uploading experience like never before.

    Difference between Sync and Async File Uploads in JavaScript

    Synchronous (Sync) and asynchronous (Async) file uploads in JavaScript refer to two different approaches for handling file upload operations. Here’s a breakdown of the key differences between the two:

    1. Execution Flow:
    – Sync: In synchronous file uploads, the execution of code pauses until the file upload operation is complete. It means that other code or operations won’t execute until the upload is finished.
    – Async: Asynchronous file uploads, on the other hand, allow the execution of code to continue while the file upload operation is in progress. The code doesn’t block and waits for the upload to complete.

    2. User Experience:
    – Sync: Synchronous file uploads can potentially cause the user interface to freeze or become unresponsive during the upload process. This is because the entire upload operation blocks the execution of other code or user interactions until it finishes.
    – Async: Asynchronous file uploads provide a better user experience as they allow the user interface to remain responsive while the upload is happening. Users can continue interacting with the application without any interruptions.

    3. Code Structure:
    – Sync: Synchronous file upload code is typically written in a linear and sequential manner. The code execution waits for the upload to complete before proceeding to the next line of code.
    – Async: Asynchronous file upload code is structured using callbacks, promises, or async/await syntax. It allows for non-blocking execution, enabling other code or operations to run concurrently while the upload progresses.

    4. Scalability and Performance:
    – Sync: Synchronous file uploads may not be suitable for large file uploads or scenarios with high concurrency. They can impact the scalability and performance of the application, especially if multiple users are uploading files simultaneously.
    – Async: Asynchronous file uploads are more scalable and performant as they allow for concurrent execution of multiple operations. This is particularly beneficial when dealing with large file uploads or multiple users uploading files concurrently.

    5. Error Handling:
    – Sync: Synchronous file uploads often handle errors using exception handling mechanisms. If an error occurs during the upload process, it can lead to program crashes or disruptions in the code flow.
    – Async: Asynchronous file uploads provide better error handling capabilities. They allow for the use of error callbacks, rejection handling in promises, or try-catch blocks with async/await, enabling more graceful error handling and recovery options.

    In summary, synchronous file uploads block the execution of other code until the upload is complete, while asynchronous file uploads allow concurrent execution, providing a better user experience, scalability, and performance. Asynchronous approaches are typically preferred for modern web applications where responsiveness and efficiency are crucial.

    When to choose Sync File Upload?

    Synchronous file uploads can be appropriate in certain scenarios where the following conditions are met:

    1. Simplicity: If the file upload operation is simple and doesn’t involve complex processing or interactions with other parts of the application, synchronous file uploads can be a straightforward solution. They have a linear code structure, making it easier to understand and implement.

    2. Small File Sizes: Synchronous file uploads can be suitable for small file sizes that can be uploaded quickly without causing significant delays or freezing the user interface. If the file sizes are small and the upload process is expected to complete rapidly, synchronous uploads may be sufficient.

    3. Sequential Dependencies: If the file upload operation depends on the completion of other synchronous tasks or operations in your application, a synchronous approach can simplify the coordination between these steps. For example, if the file upload is tightly linked with specific data processing or validation steps that must occur sequentially, synchronous file uploads can ensure the proper order of execution.

    4. Simultaneous Blocking: In some cases, blocking the user interface during the file upload might be desired. For instance, in certain security-conscious applications where it is crucial to ensure that no other actions can be performed while the file is being uploaded, synchronous file uploads can be employed.

    It’s important to note that synchronous file uploads may not be suitable for scenarios involving large file sizes, complex operations, or situations where multiple users are simultaneously uploading files. In such cases, asynchronous file uploads are generally preferred to maintain a responsive user interface and better scalability.

    Multiupload multiple files one by one in SAP UI5 (Sync Multiple Files Upload)

    View Code

    <mvc:View controllerName="TestProject.TestProject.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m">
    <Shell id="shell">
    <App id="app">
    <pages>
    <Page id="page" title="My Project Ideas: Multiupload multiple files one by one in UI5 (Sync Multiple Upload files)">
    <content>
    <UploadCollection id="idMultiUploader" maximumFilenameLength="55" maximumFileSize="3" multiple="true" sameFilenameAllowed="false"
    instantUpload="false" noDataDescription="{i18n>noDataDescriptiont}" change="onChangeEmailUpload" fileDeleted="onFileDeleted"
    filenameLengthExceed="onFilenameLengthExceed" fileSizeExceed="onFileSizeExceed" typeMissmatch="onTypeMissmatchMultiUpload"
    uploadComplete="onUploadComplete" beforeUploadStarts="onBeforeUploadStarts"/>
    <Button text="{i18n>Upload}" press="onMultiUploadSubmit"/>
    <Button id="messagePopoverBtn" icon="sap-icon://message-popup" type="{popoverModel>/type}" text="{popoverModel>/messagesLength}"
    press="handleMessagePopoverPress"/>
    </content>
    </Page>
    </pages>
    </App>
    </Shell>
    </mvc:View>

     

    Controller Code

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/ui/core/BusyIndicator",
        "sap/m/MessageBox",
        "sap/m/MessagePopover",
        "sap/m/MessagePopoverItem",
        "sap/m/Button"
    ], function (Controller, BusyIndicator, MessageBox, MessagePopover, MessagePopoverItem, Button) {
        "use strict";
        var oMessageTemplate;
        var oMessagePopover;
        return Controller.extend("TestProject.TestProject.controller.Main", {
            onInit: function () {
                var headerButton = new sap.m.Button({
                    text: "Clear",
                    type: sap.m.ButtonType.Reject,
                    press: function () {
                        that.onClearNotification();
                    }
                });
                oMessageTemplate = new MessagePopoverItem({
                    type: '{T}',
                    title: '{S}',
                });
                oMessagePopover = new MessagePopover({
                    items: {
                        path: '/',
                        template: oMessageTemplate
                    },
                    headerButton: headerButton
                });
                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);
                // Uploader Files
                this.contentFiles = [];
                this.contentSize = 0;
            },
    
            /**
             * onUploadContentTable is invoked on click from UI. 
             * Input: Excel Data
             * Output: Excel Preview
             * Excel upload is implemented in BaseController.js
             */
    
            onUploadContentTable: function (oEvent) {
                BusyIndicator.show();
                this.file = oEvent.getParameter("files")[0];
                this.UploadUrl = "/DataManager/masterData/contentTable";
                this.getExcelPreview(this.file, oEvent);
                this.byId("uploadContentTableTemplate").setValue("");
                BusyIndicator.hide();
            },
    
            /**
             * onMultiUploadCancel is invoked on click from UI. 
             * Input: oEvent
             * Output: Deletion of all Items of Dialog Box and Dialog Box closes
             */
    
            onMultiUploadCancel: function (oEvent) {},
    
            /**
             * onChangeEmailUpload is invoked on drag and drop of files. 
             * Input: Single or Multiple Excel Data
             * Output: All files are added within an array and used during submit
             */
    
            onChangeEmailUpload: function (oEvent) {
                var that = this;
                if (oEvent.getParameters("files").files[0]) {
                    // if files added via add button
                    var allData = Object.values(oEvent.getParameters("files").files);
                    allData.forEach(function (data) {
                        that.contentFiles = that.contentFiles.concat(data);
                    });
                } else {
                    // if files added via drag and drop
                    this.contentFiles = this.contentFiles.concat(oEvent.getParameter("files"));
                }
            },
    
            /**
             * onMultiUploadSubmit is invoked on click from UI. 
             * Input: Single or Multiple Excel Data
             * Output: Messages in Popover
             * Table rebind is implemented in BaseController.js
             * It is a recurring function that uploads file on every succcess of previous one
             */
    
            onMultiUploadSubmit: function (oEvent, index) {
                var that = this;
                var formData;
                var sPercentage;
                this.UploadUrl = "/DataManager/masterData/contentTable";
                BusyIndicator.show(0);
                if (!index) {
                    index = 0;
                    // Progress Bar to show upload in percentage
                    if (!that._oProgressDialog) {
                        that._oProgressDialog = sap.ui.xmlfragment("TestProject.TestProject.fragment.progressIndicator", that);
                        that.getView().addDependent(that._oProgressDialog);
                    }
                    that._oProgressDialog.open();
                }
                if (that.contentFiles.length > 0 && index < that.contentFiles.length) {
                    formData = that.contentFiles[index];
                    var form = new FormData();
                    form.append("file", formData);
                    return $.ajax({
                        method: "PUT",
                        url: "/DataManager/masterData/contentTable",
                        data: form,
                        async: true,
                        processData: false,
                        mimeType: "multipart/form-data",
                        headers: {
                            "X-Csrf-Token": "<Get token from Data Model>"
                        },
                        contentType: false,
                    }).done((response) => {
                        var successData = [];
                        successData.push({
                            T: "Success",
                            S: that.contentFiles[index].name + " : " + response
                        });
                        // Updating the Message Popover
                        var previous = oMessagePopover.getModel().getData();
                        if (previous.length === undefined)
                            previous = [];
                        var updated = previous != "" ? previous.concat(successData) : successData;
                        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);
                        // Updating the progress Indicator
                        sPercentage = parseInt(((index + 1) / that.contentFiles.length) * 100, 0);
                        that.getOwnerComponent().getModel("appConfigModel").setProperty("/uploadPercentage", sPercentage);
                        that.onMultiUploadSubmit(oEvent, index + 1);
                    }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
                        // Updating the Message Popover
                        var sErrorMsg = that.getErrorMsg(XMLHttpRequest, textStatus, errorThrown);
                        if (sErrorMsg) {
                            var errorData = [];
                            errorData.push({
                                T: "Error",
                                S: that.contentFiles[index].name + " : " + sErrorMsg
                            });
                            var previous = oMessagePopover.getModel().getData();
                            if (previous.length === undefined)
                                previous = [];
                            var updated = previous != "" ? previous.concat(errorData) : errorData;
                            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);
                            // Updating the progress Indicator
                            sPercentage = parseInt(((index + 1) / that.contentFiles.length) * 100, 0);
                            that.getOwnerComponent().getModel("appConfigModel").setProperty("/uploadPercentage", sPercentage);
                            that.onMultiUploadSubmit(oEvent, index + 1);
                        }
                    });
                } else {
                    that.contentFiles = [];
                    BusyIndicator.hide();
                    // Updating the progress Indicator
                    sPercentage = parseInt(((index + 1) / that.contentFiles.length) * 100, 0);
                    that.getOwnerComponent().getModel("appConfigModel").setProperty("/uploadPercentage", sPercentage);
                    that._oProgressDialog.close();
                }
            },
    
            /**
             * handleMessagePopoverPress is invoked on click from UI. 
             * Input: oEvent
             * Output: Message Popover opens up or closes
             */
    
            handleMessagePopoverPress: function (oEvent) {
                oMessagePopover.toggle(oEvent.getSource());
            },
    
            /**
             * onFileSizeExceed is invoked on click of Upload in UI. 
             * Input: Size of file
             * Output: Error Message
             */
    
            onFileSizeExceed: function (oEvent) {
                // read msg from i18n model
                var sMsg = this.oBundle.getText("MultiUploadCondition");
                MessageBox.error(sMsg);
            },
    
            /**
             * onTypeMissmatchMultiUpload is invoked click of Upload in UI. 
             * Input: Type of file
             * Output: Error Message
             * The type miss match generic function is available in base controller
             */
    
            onTypeMissmatchMultiUpload: function (oEvent) {
                // this.onTypeMissmatch();
            },
    
            /**
             * onClearNotification is invoked on click of Clear from UI. 
             * Input: Message Model
             * Output: Empty Message Model
             */
    
            onClearNotification: function (oEvent) {
                // Clear Popover Messages
                this.getView().getModel("popoverModel").setData({
                    "messagesLength": "",
                    "type": "Default"
                });
                this.getView().getModel("popoverModel").refresh(true);
                oMessagePopover.getModel().setData("");
                oMessagePopover.getModel().refresh(true);
            },
    
            /**
             * onResetForms is invoked from a function. 
             * Input: array, object or string
             * Output: Input field value is cleared
             */
    
            getErrorMsg: function (XMLHttpRequest, textStatus, errorThrown) {
                var sCommonErrorMsg = "An error caught";
                var sTimeOutErrorMsg = "Time out";
                var sErrorMsg;
                if (XMLHttpRequest.responseJSON) {
                    if (XMLHttpRequest.responseJSON.message) {
                        if (Array.isArray(XMLHttpRequest.responseJSON.message)) {
                            sErrorMsg = XMLHttpRequest.responseJSON.message.join("\n");
                        } else {
                            sErrorMsg = XMLHttpRequest.responseJSON.message;
                        }
                    } else {
                        sErrorMsg = XMLHttpRequest.responseJSON.error;
                    }
                } else if (XMLHttpRequest.responseText) {
                    if (XMLHttpRequest.responseText == "Unauthorized") {
                        sErrorMsg = sTimeOutErrorMsg;
                        window.location.href = '../logout';
                    } else {
                        sErrorMsg = XMLHttpRequest.responseText;
                    }
                } else {
                    sErrorMsg = sCommonErrorMsg;
                }
                return sErrorMsg;
            }
        });
    });

     

    progressIndicator.fragment.xml Code

    <core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml">
        <Dialog id="idProgresIndicatorDialog" title="{i18n>UploadinProgress}" titleAlignment="Center" showHeader="true"
            class="sapUiResponsivePadding">
            <ProgressIndicator id="idProgresIndicator" class="sapUiSmallMarginBottom" displayValue="{appConfigModel>/uploadPercentage}%"
                percentValue="{appConfigModel>/uploadPercentage}" state="Information" displayOnly="true"/>
        </Dialog>
    </core:FragmentDefinition>

     

    Model Code

    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;
            },
            
            createAppConfigData: function () {
                var oAppConfigModel = {
                    "uploadPercentage": 0
                };
                return oAppConfigModel;
            }
    
        };
    });

     

    Component.js Code

    sap.ui.define([
        "sap/ui/core/UIComponent",
        "sap/ui/Device",
        "TestProject/TestProject/model/models",
        "sap/ui/model/json/JSONModel",
    ], function (UIComponent, Device, models, JSONModel) {
        "use strict";
    
        return UIComponent.extend("TestProject.TestProject.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 AppConfigModel
                this.setModel(new JSONModel(models.createAppConfigData()), "appConfigModel");
            }
        });
    });

     

    Output

    Before Upload

    Multiupload multiple files one by one in SAP UI5 Before Upload

    Progress Indicator

    Progress Indicator

    After Upload

    Sync Multiple Files Upload

     

    Note: Update i18n wherever you see the wrong texts, they are intended to be shown like that in the absence of i18n files

  • 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
  • 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