Category: UI5

  • Google Firebase Setup

    Introduction

    Welcome to the ultimate guide for setting up Google Firebase! Whether you’re a beginner or an experienced developer, this comprehensive tutorial will walk you through the process of setting up Firebase for your project. Firebase provides a suite of powerful services and tools that can help you build, improve, and scale your applications with ease.

    In this step-by-step tutorial, we will cover all the necessary steps to get your Firebase project up and running. We’ll start by creating a Firebase project and selecting the services that best fit your application’s needs. Whether you want to incorporate user authentication, real-time data storage, cloud storage, or even hosting, Firebase has got you covered.

    We’ll guide you through the process of configuring Firebase Authentication to secure your app and allow users to log in using various methods. You’ll also learn how to integrate the Realtime Database or Cloud Firestore to store and synchronize data in real-time across multiple devices. If you need to handle file uploads or downloads, we’ll show you how to set up Firebase Cloud Storage. And if you’re building a web app, we’ll explore the process of deploying your app using Firebase Hosting.

    No matter the platform you’re developing for, whether it’s web, mobile, or even desktop, Firebase offers SDKs and resources to support your development needs. We’ll provide platform-specific guidance to help you seamlessly integrate Firebase into your app.

    By the end of this tutorial, you’ll have a fully functional Firebase setup, ready to power your application with robust features and services. Get ready to unlock the full potential of Google Firebase and take your project to new heights.

    Let’s dive in and begin the journey of setting up Google Firebase for your next groundbreaking application!

    Steps to Google Firebase Setup

    To set up Google Firebase, follow these steps:

    1. Create a Firebase project: Visit the Firebase website (firebase.google.com) and sign in with your Google account. Click on “Go to Console” and then select “Add project.” Provide a name for your project and choose your desired region.

    2. Set up Firebase services: Once your project is created, you can select the Firebase services you want to use. Firebase offers a wide range of services, including Authentication, Realtime Database, Cloud Firestore, Cloud Storage, Hosting, and more. Enable the services you need for your project.

    3. Configure Firebase Authentication (optional): If you want to add user authentication to your app, navigate to the Authentication section in the Firebase console. Follow the instructions to configure the authentication providers you want to support, such as email/password, Google Sign-In, or Facebook Login.

    4. Set up Firebase SDK: To connect your app with Firebase, you need to add the Firebase SDK to your project. Depending on your platform (web, Android, iOS, etc.), Firebase provides specific SDKs and instructions. For web projects, you typically need to include a script tag with the Firebase SDK initialization code in your HTML file.

    5. Integrate Firebase into your app: Follow the integration instructions provided by Firebase for your specific platform. This may involve adding initialization code, configuring Firebase services, and setting up the necessary API keys or credentials. Firebase provides comprehensive documentation and guides for each platform to help you with the integration process.

    6. Test your Firebase setup: Once you have integrated Firebase into your app, it’s essential to test the functionality. You can use Firebase’s emulator suite or run your app on a real device to ensure that the Firebase services are working correctly. Test features such as authentication, database access, storage, and any other Firebase services you’ve incorporated into your app.

    7. Deploy your app (if applicable): If you’re building a web app and using Firebase Hosting, you can deploy your app directly from the Firebase console. Follow the hosting setup instructions to configure your hosting settings and deploy your app to Firebase Hosting. This allows you to serve your app’s static assets and content from Firebase’s global CDN.

    By following these steps, you can successfully set up Google Firebase for your project and begin leveraging its powerful suite of services. Remember to consult the Firebase documentation for detailed instructions specific to your chosen platform. Happy Firebase development!

  • Connecting a UI5 Web App with Google Firebase

    [et_pb_section admin_label=”section”] [et_pb_row admin_label=”row”] [et_pb_column type=”4_4″][et_pb_text admin_label=”Text”]

    Introduction

    Are you looking to connect your UI5 web application with the powerful capabilities of Google Firebase? Look no further! In this comprehensive tutorial, we will guide you through the process of seamlessly integrating your UI5 web app with Google Firebase, allowing you to leverage Firebase’s robust features for authentication, real-time database, cloud storage, and more.

    Connecting a UI5 web app with Google Firebase opens up a world of possibilities for enhancing your application’s functionality and user experience. With Firebase’s easy-to-use APIs and intuitive interfaces, you can effortlessly incorporate features like user authentication, allowing your users to securely log in and access personalized content. Additionally, Firebase’s real-time database empowers you to create dynamic, collaborative applications by enabling instant data synchronization across multiple devices.

    But that’s not all! By integrating Firebase’s cloud storage, you can effortlessly store and retrieve files, images, and other media assets, ensuring a seamless experience for your users. And with Firebase’s powerful hosting capabilities, deploying and scaling your UI5 web app becomes a breeze.

    In this tutorial, we will provide you with a step-by-step guide, complete with code examples and best practices, to ensure a smooth and successful integration process. Whether you’re a UI5 developer looking to enhance your app’s functionality or an aspiring developer eager to learn about the power of Firebase, this tutorial is perfect for you.

    Unlock the true potential of your UI5 web app by connecting it with Google Firebase. Join us on this exciting journey and take your application development to new heights!

    Steps for Connecting a UI5 Web App with Google Firebase

    To connect a UI5 web app with Google Firebase set up a Firebase project. Visit the Firebase console (console.firebase.google.com) and create a new project. Provide a name for your project and choose the desired Firebase services you want to use, such as Authentication, Realtime Database, Cloud Storage, and Hosting.

    Step 01: Create an App in Firebase

    Step 02: Create a new UI5 App, and add these firebase scripts within 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>

     

    Step 03: Create a new file Firebase.js in js folder and given code:

    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: "<your API Key>",
                    authDomain: "<your authDomain>",
                    projectId: "<your projectId>",
                    storageBucket: "<your storageBucket>",
                    messagingSenderId: "<your messagingSenderId>",
                    appId: "<your appId>",
                    measurementId: "<your measurementId>"
                };
                // 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;
            }
        };
    });

    Step 04: Set Firebase Model in component.js as shown below:

    sap.ui.define([
        "sap/ui/core/UIComponent",
        "sap/ui/Device",
        "Healthbridge-admin/Healthbridge-admin/model/models",
        "Healthbridge-admin/Healthbridge-admin/js/Firebase"
    ], function (UIComponent, Device, models, Firebase) {
        "use strict";
    
        return UIComponent.extend("Healthbridge-admin.Healthbridge-admin.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");
    
            }
        });
    });

    Step 05: Check if you can fetch Authentication details by using the below code in onInit or _handleRouteMatched or onAfterRendering

    var fireAuth = this.getView().getModel("fbModel").getData().fireAuth;
    console.log(fireAuth);

     

     

     [/et_pb_text][/et_pb_column] [/et_pb_row] [/et_pb_section]

  • SAP Fiori Launchpad Extensibility

    Introduction

    Unlock the full potential of your SAP Fiori Launchpad with seamless extensibility. Discover the power of customizing and enhancing your Fiori Launchpad to cater to your unique business needs. SAP Fiori Launchpad Extensibility allows you to tailor the user interface, personalize tiles, and integrate additional applications effortlessly. Maximize productivity and user satisfaction by optimizing your Fiori Launchpad to align with your organization’s processes and workflows. Unleash innovation and empower your users with a tailored and intuitive Fiori Launchpad experience through SAP Fiori Launchpad Extensibility.

    Steps for ‘SAP Fiori Launchpad Extensibility’ using WebIDE

    Here are the steps to perform SAP Fiori Launchpad Extensibility using WebIDE:

    1. Launch SAP WebIDE: Open SAP Web Integrated Development Environment (WebIDE) in your browser. Log in with your credentials and navigate to the development environment.

    2. Create or Open a Project: Create a new project or open an existing project in WebIDE that is associated with the SAP Fiori Launchpad you want to extend.

    3. Locate the “Extensibility” Folder: In your project structure, locate the “Extensibility” folder. This folder contains the necessary files and configurations for Fiori Launchpad extensibility.

    4. Configure the “Extensibility” Files: Within the “Extensibility” folder, you will find files such as “manifest.json” and “Component.js”. These files define the settings and behavior of your Fiori Launchpad extension. Customize these files to meet your requirements.

    5. Define the Extensions: Identify the areas or components of the Fiori Launchpad that you want to extend or modify. This can include adding custom tiles, enhancing existing tiles, or integrating new applications. Use the appropriate extension points defined in the “manifest.json” file to define the desired extensions.

    6. Develop the Extensions: Implement the required logic and UI changes for your Fiori Launchpad extensions. This involves developing new UI views, controllers, and models as per your customization needs. Leverage the Fiori development guidelines and best practices during this process.

    7. Test and Validate: Once the extensions are implemented, test them thoroughly to ensure they work as expected. Validate the behavior and appearance of your custom tiles, application integrations, and any other modifications made to the Fiori Launchpad.

    8. Deploy and Activate: Once you are satisfied with the extensions and they have been successfully tested, deploy the changes to your SAP Fiori Launchpad environment. Activate the extensions to make them visible and accessible to the users.

    9. Monitor and Maintain: Continuously monitor and maintain your Fiori Launchpad extensions to ensure their optimal performance and compatibility with future updates or changes in your SAP landscape. Regularly review and update the extensions based on evolving business requirements.

    By following these steps, you can effectively perform SAP Fiori Launchpad extensibility using SAP WebIDE, enabling you to tailor and enhance the Fiori Launchpad to meet your organization’s specific needs.

    Steps for ‘SAP Fiori Launchpad Extensibility’ using SAP BAS

    Here are the steps to perform SAP Fiori Launchpad Extensibility using SAP Business Application Studio (BAS):

    1. Launch SAP BAS: Open SAP Business Application Studio in your browser. Log in with your credentials and navigate to the development environment.

    2. Create or Open a Project: Create a new project or open an existing project in SAP BAS that is associated with the SAP Fiori Launchpad you want to extend.

    3. Configure the Launchpad Descriptor (lpd_cust): Locate the “lpd_cust” folder in your project structure. This folder contains the configuration files for Fiori Launchpad extensibility. Open the “lpd_cust” file and customize it to define your Launchpad’s behavior and extensions.

    4. Define the Extensions: Identify the areas or components of the Fiori Launchpad that you want to extend or modify. Use the “lpd_cust” file to define the desired extensions, such as adding custom tiles, modifying existing tiles, or integrating new applications. Follow the provided guidelines and syntax to specify the extensions accurately.

    5. Develop the Extensions: Implement the required logic and UI changes for your Fiori Launchpad extensions. This involves developing new UI views, controllers, and models as per your customization needs. Leverage the Fiori development guidelines and best practices during this process.

    6. Test and Validate: Thoroughly test your Fiori Launchpad extensions to ensure they function correctly. Validate the behavior and appearance of your custom tiles, application integrations, or any other modifications made to the Launchpad. Use the available testing tools and techniques to validate the extensions.

    7. Deploy and Activate: Once you are satisfied with the extensions and they have been successfully tested, deploy the changes to your SAP Fiori Launchpad environment. Activate the extensions to make them visible and accessible to the users.

    8. Monitor and Maintain: Continuously monitor and maintain your Fiori Launchpad extensions to ensure their optimal performance and compatibility with future updates or changes in your SAP landscape. Regularly review and update the extensions based on evolving business requirements.

    By following these steps, you can leverage SAP Business Application Studio (BAS) to perform SAP Fiori Launchpad extensibility effectively. Customize and enhance your Fiori Launchpad to align with your organization’s requirements and provide an intuitive user experience for your users.

    How to Create a Basic Extension Plugin for Fiori Launchpad

    Step 01: Enable ‘SAP Fiori Launchpad Extensibility’ on WebIDE as shown below:

    SAP Fiori Launchpad Extensibility

    Step 02: Click on Create New Project –> Project from Template

    Step 03: Choose the ‘SAP Fiori Launchpad Plugin’ template and click Next.

    Step 04: Enter the Project Name, click Next

    Step 05: Provide Plugin ID, and Plugin Title, and click Finish

    Step 06: Edit the Component.js file

    Step 07: Run the plugin by clicking “Run as SAP Fiori Launchpad Sandbox”

  • Graph API Integration with SAP UI5

    Introduction

    Welcome to our comprehensive guide on Graph API integration with SAP UI5! In this article, we will explore the seamless integration of Graph API, a powerful data query and manipulation tool from Microsoft, with SAP UI5 applications. Discover how combining the capabilities of Graph API and SAP UI5 can enhance data connectivity, streamline business processes, and deliver a superior user experience. We will delve into the key features, implementation strategies, and best practices for integrating Graph API with SAP UI5. Unleash the potential of data-driven applications by harnessing the power of Graph API and SAP UI5 integration. Let’s embark on a journey that empowers your application with efficient data access, advanced analytics, and real-time collaboration. Join us as we explore the boundless possibilities of Graph API integration with SAP UI5!

    What is Microsoft Graph API

    Microsoft Graph API is a comprehensive RESTful API provided by Microsoft that allows developers to access a wide range of Microsoft 365 services and data, including Office 365, Azure Active Directory, SharePoint, OneDrive, Outlook, and more. It serves as a unified gateway to access and interact with various Microsoft services and their underlying data.

    With Microsoft Graph API, developers can build applications that leverage the rich functionality and data available across Microsoft 365 services. It provides a consistent and efficient way to retrieve, create, update, and delete data in a standardized manner, simplifying the development process and reducing the need for multiple API calls.

    Through Graph API, developers can access resources such as users, groups, files, calendars, contacts, messages, and other entities within Microsoft 365. They can perform tasks like retrieving user profiles, accessing documents, sending emails, creating events, managing permissions, and more.

    Graph API supports a variety of authentication mechanisms, including Azure Active Directory (Azure AD), OAuth 2.0, and Microsoft account authentication. This ensures secure access to Microsoft 365 resources and protects user data.

    By integrating Microsoft Graph API with SAP UI5, developers can unlock powerful capabilities, such as retrieving and manipulating data from Microsoft 365 services, enabling collaboration features, accessing user information, and integrating with various business workflows. It provides seamless connectivity between SAP applications and Microsoft services, facilitating enhanced productivity and enriched user experiences. Read more here.

    Steps to Create Authorization Key of Graph API

    To create an authorization key (also known as an access token) for Microsoft Graph API, you need to follow these steps:

    1. Register your application: Start by registering your application in the Azure portal. This registration enables your application to authenticate and authorize access to Microsoft Graph API. Navigate to the Azure portal (https://portal.azure.com/) and sign in with your Azure account.

    Microsoft Azure Portal

    2. Create an Azure AD application: In the Azure portal, go to the “Azure Active Directory” section and select “App registrations” (or “App registrations (Legacy)” for older versions). Click on the “New registration” (or “New application registration”) button to create a new application.

    Create Azure AD User

    3. Provide application details: Fill in the required details for your application, such as a name, supported account types, and redirect URI (if applicable). The redirect URI is the URL where users are redirected after authentication.

    New Application

    Certificate & Secrets

    4. Configure API permissions: In the application settings, navigate to the “API permissions” (or “Required permissions”) section. Click on the “Add a permission” button and select the Microsoft Graph API.

    5. Select required permissions: Choose the required permissions based on the operations your application needs to perform. For example, if you need to read user profiles, select the appropriate User.Read scope. Click on the “Grant admin consent” button to grant these permissions for your application (if you have the necessary permissions).

    6. Obtain the authorization code: To obtain an authorization code, construct the authorization URL by specifying the appropriate scopes and redirect URI. Users will be prompted to sign in and grant consent to your application. After successful authentication and consent, the authorization code will be included in the redirected URL.

    7. Exchange authorization code for an access token: Using the authorization code, make a POST request to the token endpoint of Microsoft Graph API. Include the necessary parameters like client ID, client secret (if applicable), redirect URI, and authorization code. The response will contain an access token, which is the authorization key you can use to make authenticated requests to Microsoft Graph API.

    Note: The specific implementation details may vary based on your programming language and platform. You can refer to the official Microsoft Graph API documentation for more detailed instructions and code examples specific to your scenario.

    Remember to handle the authorization key securely and refresh it as needed, following the recommended practices to ensure the security of your application and user data.

    Steps to integrate Graph API using JavaScript

    You can download Microsoft Graph API Postman Collection here.

    Microsoft API Postman Collection

    To integrate Microsoft Graph API using JavaScript, you can follow these steps:

    1. Set up authentication:
    – Register your application in the Azure portal and obtain the necessary client ID and client secret (or client credentials) for authentication.
    – Install the required JavaScript libraries, such as the Microsoft Authentication Library (MSAL) or adal.js, which provide the necessary functions for authentication.

    2. Obtain an access token:
    – Use the authentication library to initiate the authentication process and obtain an access token for Microsoft Graph API.
    – Configure the required scopes and authentication parameters, such as client ID, redirect URI, and permissions, in your authentication code.

    3. Make API requests:
    – Once you have obtained an access token, you can use it to make API requests to Microsoft Graph API.
    – Use AJAX or fetch API to send HTTP requests to the appropriate API endpoints. Include the access token in the Authorization header of the request.
    – Refer to the Microsoft Graph API documentation for the specific endpoints and data you want to interact with.

    4. Handle API responses:
    – Parse and process the responses received from Microsoft Graph API.
    – Use JavaScript functions to extract the required data from the response objects and display or manipulate it as needed in your application.

    5. Implement error handling:
    – Handle potential errors that may occur during the API integration process, such as authentication failures, invalid requests, or API rate limits.
    – Implement appropriate error handling and display error messages to the user when necessary.

    6. Test and debug:
    – Test your integration by running your application and verifying that the API requests and responses function as expected.
    – Use browser developer tools or debugging tools to identify and resolve any issues or errors that may arise during the integration.

    Remember to follow best practices for securely handling access tokens, implementing proper authentication flows, and handling user consent and permissions when working with Microsoft Graph API.

    Please note that the specific implementation details may vary depending on the JavaScript libraries or frameworks you are using and the specific requirements of your application. Consult the documentation and resources provided by Microsoft for more detailed instructions and code examples for integrating Microsoft Graph API using JavaScript.

    Steps to integrate Graph API in SAP UI5

    To integrate Microsoft Graph API in SAP UI5, you can follow these steps:

    1. Obtain the necessary authorization and authentication:
    – Register your application in the Azure portal and obtain the required client ID and client secret (or client credentials) for authentication.
    – Set up the necessary authentication mechanisms, such as OAuth 2.0 or Azure Active Directory, to authenticate your application and obtain an access token for Microsoft Graph API.

    2. Create a service or utility class:
    – In your SAP UI5 application, create a service or utility class responsible for making HTTP requests to Microsoft Graph API.
    – Use SAP UI5’s built-in AJAX or OData libraries, such as `jQuery.ajax` or `sap.ui.model.odata.v2.ODataModel`, to handle HTTP requests and responses.

    3. Configure the API endpoint:
    – Define the API endpoint URLs for the specific Microsoft Graph API operations you want to perform, such as retrieving user profiles, accessing messages, or managing calendars.
    – Include the necessary headers, such as the Authorization header with the access token, in your API requests.

    4. Make API calls:
    – Use the defined API endpoint URLs and the configured headers to make HTTP requests to Microsoft Graph API within your service or utility class.
    – Leverage the appropriate AJAX or OData functions provided by SAP UI5 to send the requests and handle the responses.
    – Parse and process the responses received from Microsoft Graph API and extract the required data for use within your SAP UI5 application.

    5. Implement error handling:
    – Handle potential errors and exceptions that may occur during the API integration process, such as authentication failures, invalid requests, or API rate limits.
    – Implement appropriate error handling mechanisms, such as displaying error messages or triggering fallback actions, to handle any errors or exceptions gracefully.

    6. Integrate the service in your SAP UI5 application:
    – Use the created service or utility class within your SAP UI5 application to access and utilize the Microsoft Graph API functionality.
    – Integrate the API calls and the retrieved data with the relevant UI components, models, or controllers in your SAP UI5 application to provide a seamless user experience.

    View.xml

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:ndc="sap.ndc" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Graph API Integration in SAP UI5">
                        <content>
                            <Button id="button" text="Show User Details" press="onFetchUser"/>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox",
        "sap/m/MessageToast",
        "sap/ui/model/json/JSONModel",
    
    ], function (Controller, MessageBox, MessageToast, JSONModel) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            onInit: function () {},
    
            onFetchUser: function (oEvent) {
                var settings = {
                    "url": "https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/9ff78c75-dbce-4557-83b0-36953dc9a017/oauth2/v2.0/token",
                    "method": "POST",
                    "timeout": 0,
                    "headers": {
                        "Content-Type": "application/x-www-form-urlencoded",
                        "SdkVersion": "postman-graph/v1.0",
                        "Cookie": "fpc=AmXUYBpiSB1Onw0A3xawYrYYPDVEAQAAADZ1-dsOAAAAQ7i_kAIAAABnc_nbDgAAAJzET7QBAAAA1nP52w4AAAA; stsservicecookie=estsfd; x-ms-gateway-slice=estsfd"
                    },
                    "data": {
                        "grant_type": "client_credentials",
                        "client_id": "ba945c3f-8687-4a6a-a95b-1aaad7323872",
                        "client_secret": "SW58Q~YxPf86UZhGYfhzTE7ZXKHOm.eKZ4bH4cd0",
                        "scope": "https://graph.microsoft.com/.default"
                    }
                };
    
                $.ajax(settings).done(function (response) {
                    console.log(response.access_token);
    
                    var settings = {
                        "url": "https://graph.microsoft.com/v1.0/users/d3f7739f-55f4-41e1-bc3a-2a36e31922f0",
                        "method": "GET",
                        "timeout": 0,
                        "headers": {
                            "Content-Type": "application/json",
                            "SdkVersion": "postman-graph/v1.0",
                            "Authorization": "Bearer " + response.access_token
                        },
                    };
    
                    $.ajax(settings).done(function (response) {
                        console.log(response);
                    });
                });
            }
        });
    });

     

    Output Screen

    Graph API UI5

    Output Generated via Graph API

    Graph API output

    7. Test and debug:
    – Test the integration by running your SAP UI5 application and verifying that the API requests and responses function as expected.
    – Use SAP UI5’s debugging tools or browser developer tools to debug any issues or errors that may arise during the integration.

    Ensure that you handle access token management securely, implement proper error handling, and follow best practices for integrating external APIs within SAP UI5 applications.

    Please note that the specific implementation details may vary based on the SAP UI5 version, architecture, and the specific requirements of your application. Consult the SAP UI5 documentation and resources for more detailed instructions and code examples for integrating Microsoft Graph API in SAP UI5.

    Testing Graph API

    Test your APIs using Graph API Explorer here. You can test all the available APIs here, using your login. Like I have tried to run the first basic API to fetch my own user details:

    Graph API Explorer

  • Google Maps Integration in SAP UI5

    Introduction

    Welcome to our comprehensive guide on Google Maps integration in SAP UI5! In this article, we will explore the seamless integration of these two powerful technologies to enhance the user experience and unlock a world of geospatial possibilities. Discover how the integration of Google Maps and SAP UI5 can revolutionize your application by providing intuitive and interactive mapping functionalities. We will delve into the key features, implementation strategies, and best practices to ensure a successful integration. Get ready to embark on a journey that combines the strength of SAP UI5 with the versatility of Google Maps, resulting in an unparalleled user experience and improved business outcomes. Let’s dive in and explore the limitless potential of Google Maps integration in SAP UI5!

    When we need Google Maps Integration in SAP UI5

    Google Maps integration in SAP UI5 becomes essential in various scenarios where geospatial information and mapping capabilities are required within SAP applications. Here are a few instances when integrating Google Maps with SAP UI5 can be beneficial:

    1. Location-Based Services: When you need to incorporate location-based services into your SAP UI5 application, such as displaying customer locations, tracking shipments, or finding the nearest store or service center.

    2. Geographical Data Visualization: If you have large volumes of geographical data that need to be visualized effectively, Google Maps integration can help you present the information in a user-friendly and interactive manner.

    3. Route Planning and Optimization: When your SAP application involves route planning, delivery management, or field service operations, integrating Google Maps allows you to calculate optimized routes, estimate travel distances and durations, and provide real-time traffic information.

    4. Geolocation Tracking: If you require real-time tracking of assets, vehicles, or personnel within your SAP application, Google Maps integration enables you to track and display their positions on a map, facilitating monitoring and decision-making processes.

    5. Address Validation and Geocoding: When it’s necessary to validate and standardize addresses entered by users or perform geocoding (converting addresses into geographic coordinates), integrating Google Maps can ensure accurate and reliable data.

    6. Location Intelligence and Analytics: If you want to leverage location-based insights to enhance business intelligence and analytics, integrating Google Maps with SAP UI5 enables you to overlay geographical data with other business data, facilitating data-driven decision-making.

    By integrating Google Maps with SAP UI5, you can unlock a wide range of geospatial functionalities, enrich your application with interactive maps, and provide a more intuitive and engaging user experience.

    How to generate a Google Map API Key

    To generate a Google Maps API key, follow these steps:

    1. Go to the Google Cloud Platform Console: Visit the Google Cloud Platform Console at https://console.cloud.google.com/.

    2. Create a new project: If you don’t have a project already, create a new one by clicking on the “Select a project” drop-down menu at the top of the page and selecting “New Project.” Give your project a name and click “Create.”

    3. Enable the Maps JavaScript API: In the Cloud Platform Console, click on the “Enable APIs and Services” button. Search for “Maps JavaScript API” and select it from the results. Click on the “Enable” button to enable the API for your project.

    4. Set up API credentials: From the left sidebar, click on “Credentials” and then click on the “Create Credentials” button. Select “API key” from the dropdown menu.

    5. Restrict your API key (optional): For security purposes, it’s recommended to restrict your API key to only allow requests from specific websites or mobile apps. You can set up restrictions by clicking on the “Restrict key” button.

    6. Configure your API key: Give your API key a name for easy reference and configure any additional settings or restrictions as needed.

    7. Get your API key: Once you have configured your API key, it will be generated. Copy the API key and securely store it.

    Congratulations! You have successfully generated a Google Maps API key. Make sure to include this API key in your SAP UI5 application when making requests to the Google Maps API services.

    Types of Google Maps Integration in SAP UI5

    iFrame based Integration

    To perform iFrame-based integration in SAP UI5, you can follow these steps:

    1. Create an XML View: Define an XML view in your SAP UI5 application where you want to integrate the iFrame. This XML view will contain the iFrame control.
    2. Add iFrame control: Inside the XML view, add the iFrame control by using the <core:HTML> or <html:iframe> tag. Set the src attribute to specify the URL of the webpage or content you want to display within the iFrame.

      Example:

      <core:HTML content="<iframe src='https://www.example.com' width='100%' height='100%'></iframe>" />
      

       

    3. Adjust iFrame properties: Customize the iFrame by setting attributes such as width, height, scrolling, frameborder, etc., based on your requirements. These attributes define the appearance and behavior of the iFrame.
      <core:HTML content="<iframe src='https://www.example.com' width='800' height='600' scrolling='auto' frameborder='0'></iframe>" />
      

       

    4. Bind iFrame properties dynamically (optional): If you need to dynamically change the URL or other properties of the iFrame based on your application logic, you can bind the properties using data binding techniques provided by SAP UI5.
      <core:HTML content="<iframe src='{path>/iframeUrl}' width='100%' height='100%'></iframe>" />
      

       

    5. Style and position the iFrame: Apply CSS classes or inline styles to the iFrame or its parent containers to control the appearance, positioning, and responsiveness of the iFrame within your SAP UI5 application.
      <core:HTML content="<iframe src='https://www.example.com' width='100%' height='100%' class='myIframe'></iframe>" />
      

      In the CSS file:

      .myIframe {
          border: 1px solid #ccc;
          border-radius: 5px;
      }
      

       

    For Google Maps, first, get the source URL from here: https://www.maps.ie/create-google-map/

    And then add the following in the view file:

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:ndc="sap.ndc" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Google Map Integration in SAP UI5">
                        <content>
                            <!--Fixed Google Map without API Key and without serch functionality-->
                            <html:iframe width="100%" height="600"
                                src="https://maps.google.com/maps?width=100%25&amp;height=600&amp;hl=en&amp;q=Noida+(My%20Project%20Ideas)&amp;t=&amp;z=14&amp;ie=UTF8&amp;iwloc=B&amp;output=embed"></html:iframe>
                        
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

    Output

    Google Maps Integration using iFrame in UI5

    Google API-based Integration

    To perform Google API-based integration in SAP UI5, you can follow these steps:

    1. Obtain a Google Maps API Key: Generate a Google Maps API key by following the steps outlined in the previous response titled “How to generate a Google Map API Key.” This key will be required to access and use Google Maps API services.
    2. Load the Google Maps API library: In your SAP UI5 application, include the Google Maps JavaScript library by adding the following script tag to the HTML view or index.html file of your application.
      <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
      

      Replace YOUR_API_KEY with the API key you obtained in Step 1.

    3. Create a UI5 control for Google Maps integration: In your SAP UI5 application, create a control (such as a custom control or an extension of an existing control) that encapsulates the Google Maps functionality. This control will be responsible for rendering the map and interacting with the Google Maps API.
    4. Initialize the map: Within your UI5 control, initialize the Google Map by calling the appropriate JavaScript functions provided by the Google Maps API. This includes specifying the map container element, setting the initial center coordinates, zoom level, and any additional options you want to apply to the map.
      var map = new google.maps.Map(mapContainer, {
        center: { lat: 37.7749, lng: -122.4194 },
        zoom: 12,
      });
      

      Here, mapContainer represents the HTML element where the map will be rendered.

    5. Utilize Google Maps API services: You can now leverage various Google Maps API services within your UI5 control. These services include displaying markers, drawing shapes, geocoding, reverse geocoding, route calculation, and more. Refer to the Google Maps API documentation for details on each service and how to use them.
      // Example: Add a marker to the map
      var marker = new google.maps.Marker({
        position: { lat: 37.7749, lng: -122.4194 },
        map: map,
        title: 'San Francisco',
      });
      

      This example creates a marker at the specified coordinates and displays it on the map.

    6. ustomize and interact with the map: You can customize the map’s appearance, add event listeners for user interactions, and apply other styling and functionality as per your application requirements. Use the available Google Maps API functions and options to achieve this.
      // Example: Add a click event listener to the map
      map.addListener('click', function(event) {
        console.log('Clicked on the map at coordinates:', event.latLng);
      });
      

      This example logs the clicked coordinates to the console when the user clicks on the map.

      By following these steps, you can integrate Google Maps API functionality into your SAP UI5 application and leverage its powerful mapping capabilities to enhance the user experience and add geospatial functionality to your application.

    HTML code

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <!--<meta name="viewport" content="width=device-width, initial-scale=1.0">-->
            <title>My Project Ideas</title>
             <link rel="icon" type="image/x-icon" href="https://myprojectideas.com/wp-content/uploads/2021/08/cropped-Screenshot-2021-07-26-at-1.39.04-PM-32x32.png">
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"Test.Test": "./"}'
                data-sap-ui-compatVersion="edge"
                data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
                data-sap-ui-async="true"
                data-sap-ui-frameOptions="trusted">
            </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBXMbsWFS5fKJD7IX7-E__5ZWKFgZTNeqs&libraries=places" type ="text/javascript"> 
    </script>
    <style>
    .myMap {                   
    height: 100%;
    width: 100%  ;
    }
    </style>
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="Test.Test" data-id="container" data-settings='{"id" : "Test"}'></div>
        </body>
    </html>

     

    View Code

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:ndc="sap.ndc" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Google Map Integration in SAP UI5">
                        <content>
                            <VBox fitContainer="true" justifyContent="Center" alignItems="Center">
                                <HBox fitContainer="true" justifyContent="Center" alignItems="Center">
                                    <Input id="bntSearch" class="controls" type="text" placeholder="Search Box"/>
                                    <Button id="button" text="search" press="onAfterRendering"/>
                                    <Button id="Distance" text="Distance" press="onDistancePress"/>
                                </HBox>
                                <HBox fitContainer="true" justifyContent="Center" alignItems="Center">
                                    <Input id="FromDis" placeholder="From" visible="false"/>
                                    <Input id="ToDis" placeholder="To" visible="false"/>
                                    <Button id="Okay" text="Ok" visible="false" press="onOkayPress"/>
                                </HBox>
                                <HBox id="map_canvas" fitContainer="true" justifyContent="Center" alignItems="Center"></HBox>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller Code

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox",
        "sap/m/MessageToast",
        "sap/ui/model/json/JSONModel",
    
    ], function (Controller, MessageBox, MessageToast, JSONModel) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            onInit: function () {
                this.getView().byId("map_canvas").addStyleClass("myMap");
            },
    
            onAfterRendering: function () {
                if (!this.initialized) {
                    this.initialized = true;
                    this.geocoder = new google.maps.Geocoder();
                    window.mapOptions = {
                        center: new google.maps.LatLng(28.5706333, 77.3272147),
                        zoom: 8,
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    };
                    //This is basically for setting the initial position of the map, ie. Setting the coordinates, for the place by default
    
                    var map = new google.maps.Map(this.getView().byId("map_canvas").getDomRef(), mapOptions);
                    var infowindow = new google.maps.InfoWindow;
                    var geocoder = new google.maps.Geocoder();
                    var marker = new google.maps.Marker({
                        map: map,
                    });
    
                    google.maps.event.addListener(map, "click", function (e) {
                        var lolatitude = e.latLng.lat(); //calculates latitude of the point of click
                        var lolongitude = e.latLng.lng() //calculates longitude of the point of click
                        jQuery.sap.require("sap.m.MessageToast");
                        sap.m.MessageToast.show("Lat" + lolatitude + "\n Lng" + lolongitude);
                        var latlng = new google.maps.LatLng("latlng", lolatitude, lolongitude);
                        var text1 = new sap.m.Text({
                            text: lolatitude
                        });
                        var text2 = new sap.m.Text({
                            text: lolongitude
                        });
                        window.point1 = lolatitude;
                        window.point2 = lolongitude;
                        geocodeLatLng(geocoder, map, infowindow, text1, text2);
    
                    });
                    //This function is for what should happen if a user left clicks on the map
                    function geocodeLatLng(geocoder, map, infowindow, text1, text2) {
                        var markers = [];
                        var input1 = text1.mProperties.text;
                        var input2 = text2.mProperties.text;
                        var latlng = {
                            lat: parseFloat(input1),
                            lng: parseFloat(input2)
                        };
    
                        geocoder.geocode({
                            'location': latlng
                        }, function (results, status) {
                            if (status === google.maps.GeocoderStatus.OK) {
                                if (results[1]) {
                                    //Here result will consist of many result, but we have to take fist result //itself, since that would be the appropriate one
                                    map.setZoom(11);
    
                                    function addMarker(location) {
                                        var marker = new google.maps.Marker({
                                            position: location,
                                            map: newmap1
                                        });
                                        markers.push(marker); // A marker is added to the point where it was clicked
                                    }
                                    var address1 = results[1].formatted_address;
    
                                    infowindow.setContent(results[1].formatted_address);
                                    infowindow.open(map, marker);
                                } else {
                                    window.alert('No results found');
                                }
                            } else {
                                window.alert('Geocoder failed due to: ' + status);
                            }
    
                        });
                    }
    
                    ////////////////////Distance//////////////////////
    
                } else if (this.initialized === true) {
                    this.actSearch()
                }
    
            },
    
            actSearch: function () {
                var newmap = new google.maps.Map(this.getView().byId("map_canvas").getDomRef(), mapOptions);
                var address = this.getView().byId("bntSearch").getValue();
                this.geocoder.geocode({
                    'address': address
                }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        newmap.setCenter(results[0].geometry.location);
                        newmap.setZoom(12);
                        var marker = new google.maps.Marker({
                            map: newmap,
                            position: results[0].geometry.location
                        });
                        //This function is for search. Here when a place is searched a marker is //applied and the map is zoomed to the particular position.
    
                    } else {
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });
                return;
            },
            onDistancePress: function () {
                var loFrom = this.getView().byId("FromDis");
                var loTo = this.getView().byId("ToDis");
                var loOk = this.getView().byId("Okay");
                loOk.setVisible(true);
                loFrom.setVisible(true);
                loTo.setVisible(true);
            },
            //This function is triggered on click of distance button.
    
            onOkayPress: function () {
                //This function calculates approx. distance between the two places, since I //haven’t used Google Maps Distance API, therefore this ain’t the proper way //to calculate distance among the places
                var newmap1 = new google.maps.Map(this.getView().byId("map_canvas").getDomRef(), mapOptions);
                var address1 = this.getView().byId("FromDis").getValue();
                var address2 = this.getView().byId("ToDis").getValue();
                this.geocoder.geocode({
                    'address': address1
                }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        window.lolatitude1 = results[0].geometry.location.lat();
                        window.lolongitude1 = results[0].geometry.location.lng();
                        window.add1 = results[0].formatted_address.split(",", 1)[0]
                        newmap1.setCenter(results[0].geometry.location);
                        newmap1.setZoom(12);
                        var marker = new google.maps.Marker({
                            map: newmap1,
                            position: results[0].geometry.location
                        });
                    } else {
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });
                this.geocoder.geocode({
                    'address': address2
                }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        window.lolatitude2 = results[0].geometry.location.lat();
                        window.lolongitude2 = results[0].geometry.location.lng();
                        window.add2 = results[0].formatted_address.split(",", 1)[0]
                        newmap1.setCenter(results[0].geometry.location);
                        newmap1.setZoom(10);
                        var marker = new google.maps.Marker({
                            map: newmap1,
                            position: results[0].geometry.location
                        });
                        sap.m.MessageToast.show("Approx. Distance Between" + " " + window.add1 + " " + "and" + " " + window.add2 + " " + "is" + " " +
                            getDistanceFromLatLonInKm(window.lolatitude1, window.lolongitude1, window.lolatitude2, window.lolongitude2) + "KM", {
                                width: "30em",
                                duration: 10000
                            });
    
                    } else {
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });
    
                function getDistanceFromLatLonInKm(lolatitude1, lolongitude1, lolatitude2, lolongitude2) {
                    var R = 6371; // Radius of the earth in km
                    var dLat = deg2rad(window.lolatitude2 - window.lolatitude1); // deg2rad below
                    var dLon = deg2rad(window.lolongitude2 - window.lolongitude1);
                    var a =
                        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                        Math.cos(deg2rad(window.lolatitude1)) * Math.cos(deg2rad(window.lolatitude2)) *
                        Math.sin(dLon / 2) * Math.sin(dLon / 2);
                    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
                    var d = R * c; // Distance in km
                    return d.toLocaleString();
                }
    
                function deg2rad(deg) {
                    return deg * (Math.PI / 180)
                }
                var flightPlanCoordinates = [{
                        lat: window.lolatitude1,
                        lng: window.lolongitude1
                    }, {
                        lat: window.lolatitude2,
                        lng: window.lolongitude2
                    }
    
                ];
                var flightPath = new google.maps.Polyline({
                    path: flightPlanCoordinates,
                    geodesic: true,
                    strokeColor: '#FF0000',
                    strokeOpacity: 1.0,
                    strokeWeight: 2
                });
    
                flightPath.setMap(newmap1);
    
            }
    
        });
    });

     

    Output

    Google Maps Integration using API Key in UI5

  • Google Analytics Integration in SAP UI5

    Introduction

    There are multiple ways to trace page views and user activity. Among them, SAP provides SAP Analytics Cloud (SAC). Google Analytics is another way that can be integrated with SAP UI5. In this article, we will learn Google Analytics Integration in SAP UI5.

    What is Google Analytics

    Google Analytics is a web analytics service offered by Google that helps website owners and marketers understand how users interact with their websites and mobile apps. It provides detailed insights into user behavior, including page views, clicks, bounce rates, session duration, and more. With Google Analytics, website owners can measure the performance of their website, identify areas for improvement, and make data-driven decisions to optimize their online presence.

    Google Analytics works by placing a small piece of tracking code on the website, which collects data about user behavior and sends it to Google’s servers for analysis. The service offers a wide range of features and tools, including customizable reports, real-time data, audience segmentation, goal tracking, and more. It is widely used by businesses of all sizes and industries to improve their online marketing strategies, optimize their website performance, and drive conversions.

    How to configure Google Analytics

    To configure Google Analytics so that you can integrate it later with SAPUI5, you can follow these steps:

    1. Sign up for a Google Analytics account if you don’t already have one.
    2. Once you’re logged in, click on the Admin button in the lower left corner of the screen.
    3. In the Admin panel, click on the “Create Property” button to create a new property for your website.
    4. Follow the prompts to enter information about your website, such as the website name, URL, and time zone.
    5. On the next screen, select “Website” as the type of property and enter your website’s URL.
    6. Under “Advanced Options,” make sure that the “Create a Universal Analytics property” option is selected. This will enable you to use the latest version of Google Analytics, which supports more advanced features and reporting.
    7. Follow the remaining prompts to complete the setup process and obtain your tracking ID. This ID will be in the format “UA-XXXXX-Y” where “XXXXX” represents your account number and “Y” represents the property number.
    8. Once you have your tracking ID, you can integrate Google Analytics with SAPUI5 by adding the tracking code to your application, as described in the previous answer. Make sure to replace “GA_MEASUREMENT_ID” with your actual tracking ID.

    How to Integrate Google Analytics in SAP UI5

    To implement Google Analytics tracking using SAPUI5, you can follow these steps:

    1. Add the Google Analytics tracking code to your SAPUI5 application. You can do this by creating a new JavaScript file and adding the tracking code to it. Make sure to replace “GA_MEASUREMENT_ID” with your actual tracking ID.
      sap.ui.define([], function() {
        "use strict";
        return {
          trackPageView: function() {
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', 'GA_MEASUREMENT_ID');
          },
          trackEvent: function(category, action, label, value) {
            window.gtag('event', action, {
              'event_category': category,
              'event_label': label,
              'value': value
            });
          }
        };
      });
      

       

    2. Include the JavaScript file in your SAPUI5 application by adding it to the manifest.json file.
      {
        "sap.ui5": {
          "resources": {
            "js": [{
              "uri": "path/to/tracking.js"
            }]
          }
        }
      }
      

       

    3. Call the trackPageView method in your SAPUI5 application’s controller or component.
      sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "path/to/tracking"
      ], function(Controller, tracking) {
        "use strict";
        return Controller.extend("your.namespace.controller.App", {
          onInit: function() {
            tracking.trackPageView();
          }
        });
      });
      

       

    4. Call the trackEvent method to track specific user actions in your SAPUI5 application.
      sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "path/to/tracking"
      ], function(Controller, tracking) {
        "use strict";
        return Controller.extend("your.namespace.controller.App", {
          onPressButton: function() {
            tracking.trackEvent("Button", "Click", "Submit", 1);
          }
        });
      });
      

       

      That’s it! With these steps, you can implement Google Analytics tracking in your SAPUI5 application and start collecting valuable data about your users’ actions.

       

    Google Analytics Integration in SAP UI5

    Index.html

    <script src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXX-Y"></script>

    Tracking.js

    sap.ui.define([], function() {
      "use strict";
      return {
        trackPageView: function() {
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', 'UA-63143188-5');
        },
        trackEvent: function(category, action, label, value) {
          window.gtag('event', action, {
            'event_category': category,
            'event_label': label,
            'value': value
          });
        }
      };
    });

     

    Main.view

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:ndc="sap.ndc" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Google Analytics Integration in SAP UI5">
                        <content>
                            <Button icon="sap-icon://area-chart" text="Track Page View using Google Analytics" press="onPressButton"/>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

    Main.controller

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox",
        "sap/m/MessageToast",
        "sap/ui/model/json/JSONModel",
        "Test/Test/js/tracking"
    
    ], function (Controller, MessageBox, MessageToast, JSONModel, tracking) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            onInit: function () {
                
            },
    
            onPressButton: function () {
                tracking.trackPageView();
            }
        });
    });

    Manifest.json

            "resources": {
                "js": [{
                    "uri": "js/tracking.js"
                }]
    }

    Output

    Google Analytics Integration in SAP UI5

    Google Analytics

    Before

    Google Analytics Before Integration in SAP UI5

    After

    Google Analytics After Integration in SAP UI5

  • Encrypting Data in SAP UI5 using SHA256

    Introduction

    After implementing hashing via AES 256 (read here), one can conclude that since we can hash and unhash data, hence the encrypted data can be decrypted anyhow, and our data can be stolen. In a special scenario, where you don’t need decryption and just need hashing of data, we use SHA256 Encryption. It has a very important role in Blockchain. In this article, we will learn Encrypting Data in SAP UI5 using SHA256.

    What is SHA 256?

    The full form of SHA is the Secure Hash Algorithm, and SHA 256 is part of the series SHA Encryption. SHA256 always give result in the form of 256 characters for any type of input.

    Can we decrypt the data of SHA 256?

    SHA 256 are one-way of encryption, and the encrypted values cannot be decrypted. In case you find some online portals decrypting your hash, then it would mean that they have saved some hashes in their db and just returning the values that they have saved with it.

    How to Implement Encryption in SAP UI5 using SHA256

    To implement SHA 256 in SAP UI5, you need to include the given scripts in Index.html

    <script src=”https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/core.min.js”></script>
    <script src=”https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/sha256.js”></script>

    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-32x32.png">
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"Test.Test": "./"}'
                data-sap-ui-compatVersion="edge"
                data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
                data-sap-ui-async="true"
                data-sap-ui-frameOptions="trusted">
            </script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/core.min.js"></script>
        	<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/sha256.js"></script>
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="Test.Test" data-id="container" data-settings='{"id" : "Test"}'></div>
        </body>
    </html>

    View.xml

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:ndc="sap.ndc" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Encrypting Data in SAP UI5 using SHA256">
                        <content>
                            <VBox>
                                <Text text="Enter your text for SHA Encryption"/>
                                <Input id="idText"/>
                                <Button text="Encrypt" press="onPressEncrypt"/>
                                <Text text="Encrypted Text"/>
                                <Input editable="false" id="idEncrypted"/>
                                <Title text="Verify Hash"/>
                                <Input id="idTextVerify"/>
                                <Button id="idButtonVerify" enabled="false" text="Verify" press="onPressVerify"/>
                                <Input editable="false" id="idNewhHash"/>
                                <Text id="idStatus" text=""/>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox",
        "sap/m/MessageToast",
        "sap/ui/model/json/JSONModel",
        "sap/ndc/BarcodeScanner"
    
    ], function (Controller, MessageBox, MessageToast, JSONModel, BarcodeScanner) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
            onPressEncrypt: function (oEvent) {
                var text = this.byId("idText").getValue();
                var payload = this.encrypt(text);
                this.byId("idButtonVerify").setEnabled(true);
                this.byId("idTextVerify").setEnabled(true);
                this.byId("idEncrypted").setValue(payload);
            },
    
            onPressVerify: function (oEvent) {
                var text = this.byId("idTextVerify").getValue();
                var payload = this.encrypt(text);
                this.byId("idNewhHash").setValue(payload);
                var oldHash = this.byId("idEncrypted").getValue();
                var newHash = this.byId("idNewhHash").getValue();
                if (newHash === oldHash) {
                    this.byId("idStatus").setText("Hash is same!");
                } else {
                    this.byId("idStatus").setText("Hash is different!");
                }
            },
    
            encrypt: function (input) {
                var passhash = CryptoJS.SHA256(input);
                return passhash;
            }
    
        });
    });

     

    Output

    Success

    Encrypting Data in SAP UI5 using SHA256

    Error

    Encrypting Data in SAP UI5 using SHA256 Mismatch

  • PHP & SQL Integration in SAP UI5

    Introduction

    We can use SAP UI5 and integrate it with any backend technologies available in the market. In this article, we will learn simple steps related to PHP & SQL Integration in SAP UI5.

    How to Integrate PHP & SQL with SAP UI5

    To Integrate PHP & SQL with SAP UI5, follow this simple flow:

    Steps to follow for PHP

    • Install XAMPP
    • Run PHP My Admin (to see database): http://localhost:80/phpmyadmin/
    • Create a db with a few tables
    • Create a notepad file, save it as process.php
    • Add these configurations:
      • $servername = “localhost”;
      • $username = “root”;
      • $dbname = “<your db name>”;
    • Add these line to start connection:
      • $conn = new mysqli($servername, $username,””, $dbname);
      • if ($conn->connect_error) {
      • die(“Connection failed: ” . $conn->connect_error);
    • At the top of php file, add:
      • header(“Access-Control-Allow-Origin:*”);
      • echo $_POST[“method”]();

    How to Connect a PHP File with SQL

    Steps to Integrate PHP & SQL in SAP UI5

    Step 01: Download, Install, and Run XAMPP

    XAMPP for SAP UI5

    Step 02: Once the server is up and running, open up php my admin using this URL: http://localhost:80/phpmyadmin/

    Step 03: Create a database and few tables within it

    Step 04: Create a PHP file, do the configuration of SQL connection as mentioned above and then save it within htdocs folder, preferably plan to save it within the UI5 folder

    Step 05: Within the PHP file, write CRUD operation code within different functions. Learn PHP coding here.

    Step 06: Configure PHP with UI5, as discuss in upcoming section

    Step 07: Write code in UI5 to perform CRUD Operation

    Step 08: Download the zip of UI5 folder and save with the htdocs folder. Now, you can run your code without the internet, just using XAMPP. And you data would be saved with the SQL table.

    How to Connect UI5 with PHP file

    To connect UI5 with PHP, you just need to provide the URL pointing to the PHP file. In our use case, we have stored the PHP file in the default location provided by the XAMPP server i.e., htdocs. Within that folder, we have our UI5 App i.e. Hisab; within that, we have a folder for PHP by the name php where we have saved our php file by the name process.php.
    Hence the URL pointing the same will be: http://localhost:80/Hisab/php/process.php

    And the code in UI5 will be:

    this.http = "http://";
    this.uri = this.http + "localhost:80/Hisab/php/process.php";

     

    How to perform CRUD operation from UI5 using PHP in SQL Database

    We will use AJAX call to call our code in the PHP file.

    PHP file: process.php

    <?php 
    header("Access-Control-Allow-Origin:*");
    // header('Content-Type: application/json');
    echo $_POST["method"]();
    
    function getClientTransaction(){
    $servername = "localhost";
    $username = "root";
    $dbname = "hisabkitab";
    // Create connection
    $conn = new mysqli($servername, $username,"", $dbname);
    // Check connection
        if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
        }
    // Get Filters
        $obj = json_decode($_POST["data"]);
        $Client = $obj->Client;
        $month = $obj->month;
        $year = $obj->year;
        $machineType = $obj->machineType;
        $officeType = $obj->officeType;
        $machineClause = "machineType = '".$machineType."'";
        $officeClause = "cc = '".$officeType."'";
        $clientClause = "client = '".$Client."'";
        if($machineType == "All")
        {
            $machineClause = "machineType != ''";
        }
        if($officeType == "All")
        {
            $officeClause = "cc != ''";
        }
        if($Client == "All")
        {
            $clientClause = "client != ''";
        }
    
        if ($result = $conn -> query("SELECT * FROM transaction WHERE ".$machineClause." AND ".$officeClause." AND ".$clientClause." AND month = '{$month}' AND year = '{$year}' ORDER by date DESC")) {
            if($result->num_rows > 0) {
                $i = 0;
                while($row = $result->fetch_assoc()){
                    $dataArray[$i] = $row;
                    $i = $i + 1;
                }
                echo json_encode($dataArray);
            }
        }
    }
    
    function onCreateATransaction(){
    $servername = "localhost";
    $username = "root";
    $dbname = "hisabkitab";
    // Create connection
    $conn = new mysqli($servername, $username,"", $dbname);
    // Check connection
        if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
        }
        $timestamp = date('Y-m-d H:i:s');
        $obj = json_decode($_POST["data"]);
        $client = $obj->client;
        $labour = $obj->labour;
        $date = $obj->date;
        $time=strtotime($date);
        $month = $obj->month;
        $year=$obj->year;
        $cc = $obj->cc;
        $rate = $obj->rate;
        $quantity = $obj->quantity;
        $machineType = $obj->machineType;
        $total = $obj->total;
        $sql = "INSERT INTO transaction(date,client,labour,cc,rate,quantity,machineType,total, month, year) VALUES ('$date','$client','$labour','$cc','$rate','$quantity','$machineType','$total','$month','$year')";
        if(mysqli_query($conn,$sql)){
        $dataArray[0] = 'Insertion successful';
        echo json_encode($dataArray);
        }
        else{
        $dataArray[0] = 'Insertion failed';
        echo json_encode($dataArray);
        }
    }
    ?>

    View Code

    1. Create Transaction

    <mvc:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="Hisab.Hisab.controller.TransactionShaving"
        xmlns:html="http://www.w3.org/1999/xhtml">
        <Page title="Create a new Shaving Transaction" showNavButton="true" navButtonPress="onpressBack" titleAlignment="Center">
            <content>
                <HBox class="sapUiSmallMargin">
                    <VBox class="sapUiSmallMarginEnd">
                        <Label text="Select Office" design="Bold" required="true"/>
                        <ComboBox id="idOffice" >
                            <core:Item key="Main Office" text="Main Office"/>
                            <core:Item key="Nauri Ram" text="Nauri Ram"/>
                            <core:Item key="Maidan" text="Maidan"/>
                        </ComboBox>
                    </VBox>
                    <VBox class="sapUiSmallMarginEnd">
                        <Label text="Enter the Labour Name" design="Bold" required="true"/>
                        <ComboBox id="idLabor" items="{ComboModel>/Labour_results}" change="onChangeCountry">
                            <items>
                                <core:Item key="{ComboModel>Labor}" text="{ComboModel>Labor}"/>
                            </items>
                        </ComboBox>
                    </VBox>
                </HBox>
                <VBox id="idcTxBox" class="sapUiMediumMarginEnd">
                    <!--Table to get User Inputs-->
                    <Table id="idTable" headerText="Add Records" sticky="ColumnHeaders" growing="true" growingThreshold="10" class="sapUiSizeCompact"
                        >
                        <headerToolbar>
                            <OverflowToolbar design="Transparent">
                                <Title text="Add Records"/>
                                <ToolbarSpacer/>
                                <!-- <Button text="Add New" icon="sap-icon://add" tooltip="Add New" press="onAddRow"/> -->
                                <!-- <Button text="Submit" icon="sap-icon://refresh" tooltip="Refresh" press="onSaveTransaction"/> -->
                            </OverflowToolbar>
                        </headerToolbar>
                        <columns>
                            <Column  hAlign="Left">
                                <Label text="Date" required="true"/>
                            </Column>
                            <Column hAlign="Left">
                                <Label text="Client" required="true"/>
                            </Column>
                            <Column hAlign="Left">
                                <Label text="Quantity" required="true"/>
                            </Column>
                            <Column hAlign="Left">
                                <Label text="Rate" required="true"/>
                            </Column>
                            <Column  hAlign="Left">
                                <!-- <Label text="Rate" required="true"/> -->
                            </Column>
                        </columns>
                        <items>
                            <ColumnListItem>
                                <cells>
                                    <DatePicker id="datePicker" displayFormat="dd-MM-yyyy" valueFormat="dd/MM/yyyy" value="{/Date}" />
                                    <Input  value="{/Client}" placeholder="Enter Client Name" showSuggestion="true" suggestionItems="{ComboModel>/Clients_results}">
                                        <suggestionItems>
                                            <core:Item text="{ComboModel>client}"/>
                                        </suggestionItems>
                                    </Input>
                                    <Input  value="{/Quantity}" type="Number" submit="onSumbit"/>
                                    <Input  value="{/Rate}" type="Number" submit="onSumbit"/>
                                    <!-- <Input value="{Rate}" type="Number" submit="onSumbit"/> -->
                                    <Button type="Accept" text="{i18n>Submit}" press="onSaveTransaction"/>
                                </cells>
                            </ColumnListItem>
                        </items>
                    </Table>
                </VBox>
            </content>
        </Page>
    </mvc:View>

     

    2. View Transaction

    <mvc:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="Hisab.Hisab.controller.ViewTransaction"
        xmlns:html="http://www.w3.org/1999/xhtml">
        <Page title="View Transactions" showNavButton="true" navButtonPress="onpressBack" titleAlignment="Center">
            <content>
                <HBox class="sapUiSmallMargin">
                    <VBox class="sapUiSmallMarginEnd">
                        <Label text="Select Office" design="Bold" required="true"/>
                        <ComboBox id="idOffice" selectionChange="onChangeSelection" selectedKey="All">
                            <core:Item key="All" text="All"/>
                            <core:Item key="Main Office" text="Main Office"/>
                            <core:Item key="Nauri Ram" text="Nauri Ram"/>
                            <core:Item key="Maidan" text="Maidan"/>
                        </ComboBox>
                    </VBox>
                    <VBox class="sapUiSmallMarginEnd">
                        <Label text="Select Client" design="Bold" required="true"/>
                        <ComboBox id="idClient" items="{ path: 'ComboModel>/Clients_results', sorter: { path: 'cc', descending: false, group: true } }">
                            <core:Item key="{ComboModel>client}" text="{ComboModel>client}"/>
                        </ComboBox>
                    </VBox>
                    <VBox class="sapUiSmallMarginEnd">
                        <Label text="Operation" design="Bold" required="true"/>
                        <ComboBox id="idOperation" selectionChange="onChangeSelection" selectedKey="All">
                            <core:Item key="All" text="All"/>
                            <core:Item key="Shaving" text="Shaving"/>
                            <core:Item key="Buffing" text="Buffing"/>
                            <core:Item key="Softening" text="Softening"/>
                            <core:Item key="Milling" text="Milling"/>
                            <core:Item key="Tangan" text="Tangan"/>
                            <core:Item key="Thokai" text="Thokai"/>
                        </ComboBox>
                    </VBox>
                    <VBox class="sapUiSmallMarginEnd">
                        <Label text="Select Month" design="Bold" required="true"/>
                        <ComboBox id="idMonth" selectionChange="onChangeSelection" selectedKey="01">
                            <core:Item key="01" text="January"/>
                            <core:Item key="02" text="February"/>
                            <core:Item key="03" text="March"/>
                            <core:Item key="04" text="April"/>
                            <core:Item key="05" text="May"/>
                            <core:Item key="06" text="June"/>
                            <core:Item key="07" text="July"/>
                            <core:Item key="08" text="August"/>
                            <core:Item key="09" text="September"/>
                            <core:Item key="10" text="October"/>
                            <core:Item key="11" text="November"/>
                            <core:Item key="12" text="December"/>
                        </ComboBox>
                    </VBox>
                    <VBox class="sapUiSmallMarginEnd">
                        <Label text="Select Year" design="Bold" required="true"/>
                        <ComboBox id="idYear" selectionChange="onChangeSelection" selectedKey="2020">
                            <core:Item key="2020" text="2020"/>
                            <core:Item key="2021" text="2021"/>
                            <core:Item key="2022" text="2022"/>
                            <core:Item key="2022" text="2023"/>
                        </ComboBox>
                    </VBox>
                    <VBox>
                        <Label/>
                        <Button text="Get Transactions" press="onGetTransaction"/>
                    </VBox>
                </HBox>
                <VBox id="idClientTx" visible="false">
                    <VBox class="sapUiMediumMarginEnd">
                        <!-- Table to get User Inputs -->
                        <Table id="idTable" headerText="Client Transactions" sticky="ColumnHeaders" growing="true" mode="SingleSelectLeft" growingThreshold="20"
                            class="sapUiSizeCompact" items="{detailsModel>/results}">
                            <headerToolbar>
                                <OverflowToolbar>
                                    <Title id="idTableHeader" text="All Transactions" level="H2"/>
                                    <ToolbarSpacer/>
                                    <Button text="Delete" icon="sap-icon://delete" press="onDelete"/>
                                </OverflowToolbar>
                            </headerToolbar>
                            <columns>
                                <Column hAlign="Left">
                                    <Label text="Date"/>
                                </Column>
                                <Column hAlign="Left">
                                    <Label text="Office"/>
                                </Column>
                                <Column hAlign="Left">
                                    <Label text="Labour"/>
                                </Column>
                                <Column hAlign="Left">
                                    <Label text="Operation"/>
                                </Column>
                                <Column hAlign="Left">
                                    <Label text="Quantity/Hours"/>
                                </Column>
                                <Column hAlign="Left">
                                    <Label text="Rate"/>
                                </Column>
                                <Column hAlign="Left">
                                    <Label text="Amount"/>
                                </Column>
                            </columns>
                            <items>
                                <ColumnListItem type="Navigation" selected="onClickTransaction">
                                    <cells>
                                        <Text text="{detailsModel>date}"/>
                                        <Text text="{detailsModel>cc}"/>
                                        <Text text="{detailsModel>labour}"/>
                                        <Text text="{detailsModel>machineType}"/>
                                        <Text text="{detailsModel>quantity}"/>
                                        <Text text="{detailsModel>rate}"/>
                                        <Text text="{detailsModel>total}"/>
                                    </cells>
                                </ColumnListItem>
                            </items>
                        </Table>
                    </VBox>
                </VBox>
            </content>
        </Page>
    </mvc:View>

     

    Controller Code

    1. Create Transaction

    sap.ui.define(
      [
        "sap/ui/core/mvc/Controller",
        "sap/ui/model/json/JSONModel",
        "sap/m/MessageBox",
      ],
      function (Controller, JSONModel, MessageBox) {
        "use strict";
    
        return Controller.extend("Hisab.Hisab.controller.TransactionShaving", {
          /**
           * 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 Hisab.Hisab.view.TransactionShaving
           */
          onInit: function () {
            this.oRouter = sap.ui.core.UIComponent.getRouterFor(this);
            this.http = "http://";
            this.uri = this.http + "localhost:81/Hisab/php/process.php";
            this.oRouter
              .getRoute("TransactionShaving")
              .attachPatternMatched(this._handleRouteMatched, this);
          },
    
          _handleRouteMatched: function (oEvent) {
            this.updateValues();
            // get First Row
            this.getFirstRow();
          },
    
          onpressBack: function (oEvent) {
            this.oRouter.navTo("Main");
          },
          updateValues: function () {
            var that = this;
            // Get Labour's Data
            $.ajax({
              url: this.uri,
              type: "POST",
              data: {
                method: "getAllLabours",
                data: JSON.stringify({}),
              },
              dataType: "json",
              success: function (dataLabour) {
                // Get Labour's Data
                $.ajax({
                  url: that.uri,
                  type: "POST",
                  data: {
                    method: "getAllClients",
                    data: JSON.stringify({}),
                  },
                  dataType: "json",
                  success: function (dataClient) {
                    that.ClientList = [];
                    var ComboObj = {
                      Labour_results: dataLabour,
                      Clients_results: dataClient,
                    };
                    dataClient.forEach(function (Client) {
                      that.ClientList.push(Client.Client);
                    });
                    that.getView().setModel(new JSONModel(ComboObj), "ComboModel");
                  },
                  error: function (request, error) {},
                });
              },
              error: function (request, error) {},
            });
          },
          getFirstRow: function (oEvent) {
            // Empty Model
            var data = {
              Date: "",
              Client: "",
              Quantity: "",
              Rate: "",
            };
            // Add Data
            var oModel = new sap.ui.model.json.JSONModel(data);
            // Set Model
            this.byId("idTable").setModel(oModel);
          },
    
          onAddRow: function (oEvent) {
            var flag = true;
            var tableData = this.byId("idTable").getModel().getData();
            tableData.results.forEach(function (temp) {
              if (!temp.Date && !temp.Client && !temp.Quantity && !temp.Rate) {
                flag = false;
              }
            });
            if (flag === true) {
              var cuurentModel = this.byId("idTable").getModel().getData().results;
              cuurentModel.push({
                Date: "",
                Client: "",
                Quantity: "",
                Rate: "",
              });
              this.byId("idTable").getModel().refresh();
            } else {
              MessageBox.error("All fields are mandatory!");
            }
          },
          onRefresh: function () {
            this.byId("idTable").getModel().setData({
              Date: "",
              Client: "",
              Quantity: "",
              Rate: "",
            });
            this.byId("idTable").getModel().refresh();
          },
          onSaveTransaction: function () {
            var that = this;
            var sLaborName = this.byId("idLabor").getValue();
            var sOffice = this.byId("idOffice").getSelectedKey();
            if (sOffice && sLaborName) {
              var temp = this.byId("idTable").getModel().getData();
              if (!temp.Date || !temp.Client || !temp.Quantity || !temp.Rate) {
                alert("Fill all details");
              } else {
                var dataLabor = {
                  id: sLaborName.toLowerCase().replace(/ /g, ""),
                  Labor: sLaborName,
                };
                $.ajax({
                  url: that.uri,
                  type: "POST",
                  data: {
                    method: "onCreateLabor",
                    data: JSON.stringify(dataLabor),
                  },
                  dataType: "json",
                  success: function (dataClient) {
                    console.log("success");
                  },
                  error: function (request, error) {
                    console.log(error);
                  },
                });
                var data = JSON.stringify({
                  client: temp.Client,
                  labour: sLaborName,
                  date: temp.Date,
                  month: parseInt(temp.Date.substring(3, 5), 0),
                  cc: sOffice,
                  rate: temp.Rate,
                  quantity: temp.Quantity,
                  machineType: "Shaving",
                  total: temp.Rate * temp.Quantity,
                  year: parseInt(temp.Date.substring(6), 0),
                });
                $.ajax({
                  url: that.uri,
                  type: "POST",
                  data: {
                    method: "onCreateATransaction",
                    data: data,
                  },
                  crossDomain: true,
                  dataType: "json",
                  success: function (sData) {
                    var messages = sData[0] + "\n";
                    // that.onRefresh();
                    that.getView().byId("datePicker").focus();
                    that.updateValues();
                    // that._handleRouteMatched();
                    // MessageBox.success(messages);
                  },
                  error: function (request, error) {
                    MessageBox.error(request.responseText);
                    // if (i === results.length && messages.length > 0) {
                    //   MessageBox.success(messages);
                    //   that._handleRouteMatched();
                    // }
                  },
                });
                that.saveClient(temp.Client);
              }
            } else {
              alert("Labor ka naam nhi hai");
            }
          },
         
    
          onResetTransaction: function (oEvent) {
            this.getFirstRow();
            this._handleRouteMatched();
          },
    
          saveClient: function (client) {
            var that = this;
            var dataClient = {
              id: client.toLowerCase().replace(/ /g, ""),
              Client: client,
            };
            // Save Labour's Data
            $.ajax({
              url: that.uri,
              type: "POST",
              data: {
                method: "onCreateClient",
                data: JSON.stringify(dataClient),
              },
              dataType: "json",
              success: function (success) {},
              error: function (request, error) {},
            });
          },
        });
      }
    );
    

     

    2. View Transaction

    sap.ui.define([
            "sap/ui/core/mvc/Controller",
            "sap/ui/model/json/JSONModel"
        ],
        function (Controller, JSONModel) {
            "use strict";
    
            return Controller.extend("Hisab.Hisab.controller.ViewTransaction", {
                /**
                 * 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 Hisab.Hisab.view.ClientPayment
                 */
                onInit: function () {
                    this.oRouter = sap.ui.core.UIComponent.getRouterFor(this);
                    this.http = "http://";
                    this.uri = this.http + "localhost:81/Hisab/php/process.php";
                    this.oRouter.getRoute("ViewTransaction").attachPatternMatched(this._handleRouteMatched, this);
                    this.getView().byId("idMonth").setSelectedKey(new Date().getMonth().toString());
                },
    
                _handleRouteMatched: function (oEvent) {
                    var that = this;
                    $.ajax({
                        url: that.uri,
                        type: "POST",
                        data: {
                            method: "getAllClients",
                            data: JSON.stringify({}),
                        },
                        dataType: "json",
                        success: function (dataClient) {
                            var data = [{
                                id: "All",
                                client: "All"
                            }];
                            data = data.concat(dataClient);
                            var ComboObj = {
                                Clients_results: data,
                            };
                            that.getView().setModel(new JSONModel(ComboObj), "ComboModel");
                        },
                        error: function (request, error) {
                            // console.log("fhfj");
                        },
                    });
                },
    
                onpressBack: function (oEvent) {
                    this.oRouter.navTo("Main");
                },
                onChangeSelection: function () {
                    var that = this;
                    var data = {};
                    this.byId("idClient").setSelectedKey("");
                    data.month = this.byId("idMonth").getSelectedKey();
                    data.year = this.byId("idYear").getSelectedKey();
                    data.machineType = this.byId("idOperation").getSelectedKey();
                    data.officeType = this.byId("idOffice").getSelectedKey();
                    $.ajax({
                        url: that.uri,
                        type: "POST",
                        data: {
                            method: "getAllClientsWithParam",
                            data: JSON.stringify(data),
                        },
                        dataType: "json",
                        success: function (dataClient) {
                            var data = [{
                                id: "All",
                                client: "All"
                            }];
                            data = data.concat(dataClient);
                            var ComboObj = {
                                Clients_results: data,
                            };
                            that.getView().setModel(new JSONModel(ComboObj), "ComboModel");
                        },
                        error: function (request, error) {
                            // console.log("fhfj");
                            var ComboObj = {
                                Clients_results: [],
                            };
                            that.getView().setModel(new JSONModel(ComboObj), "ComboModel");
                        },
                    });
                },
    
                onGetTransaction: function (oEvent) {
                    var that = this;
                    this.byId("idClientTx").setVisible(true);
                    var Client = this.byId("idClient").getSelectedKey();
                    var month = this.byId("idMonth").getSelectedKey();
                    var year = this.byId("idYear").getSelectedKey();
                    var machineType = this.byId("idOperation").getSelectedKey();
                    var officeType = this.byId("idOffice").getSelectedKey();
    
                    var data = {
                        Client: Client,
                        month: month,
                        year: year,
                        machineType: machineType,
                        officeType: officeType,
                    };
                    $.ajax({
                        url: that.uri,
                        type: "POST",
                        data: {
                            method: "getClientTransaction",
                            data: JSON.stringify(data),
                        },
                        dataType: "json",
                        success: function (dataClient) {
                            var detailsModel = {
                                results: dataClient
                            };
                            var sum = 0;
                            var count = dataClient.length;
                            dataClient.forEach(function (amount) {
                                sum = sum + parseInt(amount.total, 0);
                            });
                            that
                                .byId("idTableHeader")
                                .setText("All Transactions (" + count + ")");
                            that
                                .getView()
                                .byId("idTable")
                                .setModel(new JSONModel(detailsModel), "detailsModel");
                        },
                        error: function (request, error) {
                            that
                                .getView()
                                .byId("idTable")
                                .setModel(new JSONModel({
                                    results: []
                                }), "detailsModel");
                            that.byId("idTableHeader")
                                .setText("All Transactions (0)");
                        }
                    });
                },
    
                onResetTransaction: function (oEvent) {
                    this.byId("idClientTx").setVisible(false);
                }
            });
        });

    Output

    1. Create Transaction

    Create a transaction using PHP in SAP UI5

    2. View Transaction

    View a transaction using PHP in SAP UI5

  • I am using bar code scanner in SAP UI5. In case the camera doesn’t open up or if the scan fails, the bar code scanner shows an Input box. I want to disable that. How can I do that?

    Case 1: XML

    To disable the input box in the barcode scanner in SAP UI5, you can set the property showInputBar of the barcode scanner control to false. This will hide the input box and prevent it from being displayed even if the camera fails to open or the scan fails.

    Here’s an example code snippet showing how to disable the input box in a SAP UI5 barcode scanner control:

    var oScanner = new sap.ndc.BarcodeScanner();
    oScanner.showInputBar = false;
    

    You can also set the showInputBar property directly in the XML view definition of the barcode scanner control, like this:

    <ndc:BarcodeScanner showInputBar="false" />
    

    By setting the showInputBar property to false, the input box in the barcode scanner will be disabled and hidden from the user interface.

    Case 2: Controller

    To disable the input box in the barcode scanner in SAP UI5 via the controller using the sap.ndc.BarcodeScanner.scan method, you can modify your code as shown below:
    sap.ndc.BarcodeScanner.scan(
      function(oScanData) {
        console.log("Scanning Success: " + oScanData);
        var n = oScanData.text;
        if (n.length > 0) {
          var scannedText = oScanData.text;
        }
      },
      function(e) {
        console.log("Scanning failed: " + e);
      },
      {
        showInputBar: false // Disable the input box in the barcode scanner
      }
    );
    

    In the sap.ndc.BarcodeScanner.scan method, we have added an options parameter as the third argument, which is an object containing the options for the barcode scanner. We have set the showInputBar property of the options object to false to disable the input box in the barcode scanner.

    By setting the showInputBar property to false, the input box in the barcode scanner will be disabled and hidden from the user interface even if the camera fails to open or the scan fails.

  • Create a Simple Chat bot in SAP UI5

    Introduction

    A chatbot is an important function and has become part of all front-end applications nowadays. In this article, we will Create a Simple Chat bot in SAP UI5.

    What is Chat Bot?

    A Chat Bot is an application via which any person can interact with a system or computer. The answers generated by the computers may be hardcoded based on the questions or can be real-time generated with the help of Artificial intelligence.

    How to Implement Chatbot in SAP UI5?

    In this article, we will develop a simple chat bot where the answers are hardcoded in the UI itself. You can always replace those responses by sending the inputs to your APIs and showing the result of the APIs as output.

    Steps to Create a Simple Chat Bot in SAP UI5

    Steps to Create a Simple Chat bot in SAP UI5

    Flow of Chat Bot

    Flow of Chat Bot

    View.xml

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core"
        xmlns:html="http://www.w3.org/1999/xhtml">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="Simple Chat Bot using SAP UI5">
                        <content></content>
                        <footer>
                            <OverflowToolbar>
                                <ToolbarSpacer/>
                                <Button text="Click to Chat" icon="sap-icon://message-popup" press="handleMessagePopoverPress"/>
                            </OverflowToolbar>
                        </footer>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox",
        "sap/m/MessageToast",
        "sap/ui/model/json/JSONModel"
    
    ], function (Controller, MessageBox, MessageToast, JSONModel) {
        "use strict";
    
        return Controller.extend("Test.Test.controller.Main", {
    
            handleMessagePopoverPress: function (oEvent) {
    
                // create popover
                if (!this._oPopover) {
                    this._oPopover = sap.ui.xmlfragment("Test.Test.fragment.Bot", this);
                    this.getView().addDependent(this._oPopover);
                }
                if (this._oPopover.isOpen()) {
                    this._oPopover.close();
                } else {
                    this._oPopover.openBy(oEvent.getSource());
                }
            },
            ask: function (oEvent) {
                var input = sap.ui.getCore().byId("query").getValue();
                var fBox = new sap.m.FlexBox({
                    alignItems: "Start",
                    justifyContent: "End"
                });
                var text = new sap.m.Text({
                    text: input
                });
                text.addStyleClass("chat2");
                fBox.addItem(text);
                fBox.addStyleClass("sapUiSmallMarginTop");
                sap.ui.getCore().byId("chat").addItem(fBox);
                sap.ui.getCore().byId("query").setValue("");
                this.answer(input);
            },
            answer: function (query) {
                var greetings = ["hi", "hello", "what's up", "wassup"];
                var greetings_response = ["Hello", "Nice to meet you", "Hmm mm"];
                var job = ["what can you do for me?", "what can you do for me", "what can you do", "what can you do?"];
                if (query) {
                    if (greetings.indexOf(query.toLowerCase()) != -1) {
                        var item = greetings_response[Math.floor(Math.random() * greetings_response.length)];
                        var a = this.createText(item);
                        this.reply(a);
                    } else if (query.toLowerCase().match(/what.*you.*do/g)) {
                        var a = this.createText("What do you want me to do? XD");
                        var b = this.createButton("Show you your Questionnaire");
                        var c = this.createButton("Show you user details");
                        var d = this.createButton("Delete users");
                        var e = this.createButton("Do something naughty");
                        var vbox = new sap.m.VBox();
                        vbox.addItem(a);
                        vbox.addItem(b);
                        vbox.addItem(c);
                        vbox.addItem(d);
                        vbox.addItem(e);
    
                        this.reply(vbox);
                    } else {
                        this.reply();
                    }
                }
            },
            reply: function (ans) {
                if (ans) {
                    var fBox = new sap.m.FlexBox({
                        alignItems: "Start",
                        justifyContent: "Start"
                    });
                    ans.addStyleClass("chat1");
                    ans.addStyleClass("sapUiSizeCompact");
                    fBox.addItem(ans);
                    fBox.addStyleClass("sapUiSmallMarginTop");
                    sap.ui.getCore().byId("chat").addItem(fBox);
                } else {
                    var fBox = new sap.m.FlexBox({
                        alignItems: "Start",
                        justifyContent: "Start"
                    });
                    var text = new sap.m.Text({
                        text: "Did not recognize you. Come again"
                    });
                    text.addStyleClass("chat1");
                    fBox.addItem(text);
                    fBox.addStyleClass("sapUiSmallMarginTop");
                    sap.ui.getCore().byId("chat").addItem(fBox);
                }
                $("#pop-cont").scrollTop($("#pop-cont")[0].scrollHeight - $("#pop-cont").height());
    
            },
            onClear: function (oEvent) {
                sap.ui.getCore().byId("chat").removeAllItems();
            },
    
            onScroll: function () {
                $("#pop-cont").scrollTop($("#pop-cont")[0].scrollHeight - $("#pop-cont").height());
            },
    
            createText: function (text) {
                var text = new sap.m.Text({
                    text: text
                });
                return text;
            },
            buttonPress: function (btext) {
                var that = this;
                var naughty = ["I just did.\n I was being naughty by giving you the option of being naughty :D", "You should not ask for that ;)",
                    "Its rude to ask for it", "Gotcha :P ", "That was a character test, you failed"
                ];
                var btext = btext.toLowerCase();
                if (btext.match(/show.*ques/g)) {
                    var Input = new sap.m.Input({
                        submit: function (oEvent) {
                            that.onTestPress(oEvent, oEvent.getParameter("value"));
                        }
                    });
                    var a = this.createText("Provide the SET NAME-SET ID  and hit Enter");
                    var vbox = new sap.m.VBox();
                    vbox.addItem(a);
                    vbox.addItem(Input);
                    this.reply(vbox);
                } else if (btext.match(/show.*user/g)) {
                    var Input = new sap.m.Input({
                        submit: function (oEvent) {
                            that.onUserPress(oEvent, oEvent.getParameter("value"));
                        }
                    });
                    var a = this.createText("Provide the USER_ID  and hit Enter");
                    var vbox = new sap.m.VBox();
                    vbox.addItem(a);
                    vbox.addItem(Input);
                    this.reply(vbox);
                } else if (btext.match(/delete.*user/g)) {
                    var a = this.createText("Sorry the function is not yet available");
                    this.reply(a);
                } else if (btext.match(/naughty/g)) {
                    var item = naughty[Math.floor(Math.random() * naughty.length)];
                    var a = this.createText(item);
                    this.reply(a);
                }
            },
            createButton: function (text) {
                var that = this;
                var link = new sap.m.Button({
                    text: text,
                    type: sap.m.ButtonType.Accept,
                    press: function (oEvent) {
                        that.buttonPress(text);
                    }
                });
                link.addStyleClass("sapUiSmallMarginTop");
                return link;
            },
    
        });
    });

     

    Bot.fragment.xml

    <core:FragmentDefinition id="fragment23" xmlns="sap.m" xmlns:core="sap.ui.core">
        <Popover id="pop" title="Welcome to UI5 Chat Bot" class="sapUiContentPadding" resizable="true" verticalScrolling="true" contentHeight="200px"
            placement="Top" initialFocus="query">
            <footer>
                <Toolbar>
                    <ToolbarSpacer/>
                    <Input submit="ask" id="query" type="text" width="200px" value="" class="sapUiSmallMargin"/>
                    <Button text="Clear" press="onClear"/>
                </Toolbar>
            </footer>
            <VBox id="chat">
                <FlexBox class="sapUiSmallMarginTop" alignItems="Start" justifyContent="Start">
                    <items>
                        <Text class="chat1" text="How may I help you?"/>
                    </items>
                </FlexBox>
            </VBox>
        </Popover>
    </core:FragmentDefinition>

    Output

    Simple Chat Bot using SAP UI5