Showing posts with label associations. Show all posts
SAPUI5 and OData: Choosing between v2 and v4 for Optimal Performance and Functionality

SAPUI5 and OData: Choosing between v2 and v4 for Optimal Performance and Functionality

Sanjo Thomas•11:28:00

In the world of SAPUI5 development, the integration of OData (Open Data Protocol) is crucial for seamless data communication between the front-end and back-end systems. OData comes in two major versions - OData v2 and OData v4, each offering distinct features and capabilities. As a SAPUI5 developer, understanding when to use OData v2 and when to opt for OData v4 is essential for creating efficient, performant, and future-proof applications. In this blog, we will explore the differences between these two versions and provide examples of consuming both OData v2 and OData v4 in SAPUI5 applications.


OData v2: The Robust and Mature Option

OData v2 is the older, more mature version of the protocol. It is based on RESTful principles and supports features like filtering, sorting, paging, and batch processing. One of the significant advantages of OData v2 is its widespread adoption and comprehensive support across SAP systems. Many SAP back-end services, including SAP Gateway, primarily use OData v2.


Use Cases for OData v2 in SAPUI5:

  • When your SAP back-end system exclusively supports OData v2.
  • For applications where real-time data updates are not a critical requirement.
  • When the data model is relatively simple and doesn't require complex navigation properties.

Example of Consuming OData v2 in SAPUI5:

// Create a new ODataModel for OData v2
const oModel = new sap.ui.model.odata.v2.ODataModel("/sap/opu/odata/sap/Your_OData_Service/", {
    useBatch: false // Set this to true for batch processing support
});
// Bind data to a table
const oTable = new sap.ui.table.Table({
    visibleRowCount: 10,
    selectionMode: sap.ui.table.SelectionMode.Single,
    rows: "{/EntitySet}"
});
oTable.addColumn(new sap.ui.table.Column({
    label: new sap.ui.commons.Label({ text: "ID" }),
    template: new sap.ui.commons.TextView().bindProperty("text", "ID"),
    sortProperty: "ID",
    filterProperty: "ID"
}));
// ... other columns ...
oTable.setModel(oModel);


OData v4: The Modern and Efficient Approach

OData v4, as the more recent version, is designed with a focus on performance, simplicity, and compatibility with modern web standards. It introduces several improvements over v2, such as improved query handling and server-driven paging. OData v4 is the recommended choice for new SAPUI5 applications, especially if your back-end supports it.

Use Cases for OData v4 in SAPUI5:

For new applications or when planning a major overhaul of existing ones.
When your SAP back-end system supports OData v4 or offers a more extensive OData v4 service.
Applications requiring advanced features like deep insert, transient entities, or server-driven paging.

Example of Consuming OData v4 in SAPUI5:

// Create a new ODataModel for OData v4
const oModel = new sap.ui.model.odata.v4.ODataModel("/sap/s4hana/sap/opu/odata/sap/Your_OData_Service/", {
    synchronizationMode: "None" // Set this to "None" for better performance
});

// Bind data to a table
const oTable = new sap.ui.table.Table({
    visibleRowCount: 10,
    selectionMode: sap.ui.table.SelectionMode.Single,
    rows: {
        path: "/EntitySet",
        parameters: {
            $$groupId: "group1", // Use $$groupId for separate group processing
            $$ownRequest: true // Set this to true for individual server requests per table
        }
    }
});

oTable.addColumn(new sap.ui.table.Column({
    label: new sap.ui.commons.Label({ text: "ID" }),
    template: new sap.ui.commons.TextView().bindProperty("text", "ID"),
    sortProperty: "ID",
    filterProperty: "ID"
}));

// ... other columns ...

oTable.setModel(oModel);

Using OData v4 in CAPM Apps:

OData v4 is a modern version of the Open Data Protocol, and it plays a significant role in CAPM (Centralized Application Lifecycle Management) applications. CAPM apps are designed to streamline the process of managing applications throughout their lifecycle, from development to deployment and maintenance. Here's a short note on using OData v4 in CAPM apps:

  • Improved Performance: OData v4 offers better performance compared to its predecessor, v2. It supports server-driven paging, enabling efficient data retrieval, which is crucial in CAPM apps that deal with a large volume of application-related data.
  • Advanced Query Handling: OData v4 introduces several enhancements in query handling, making it easier to retrieve specific data sets and perform complex filtering and sorting operations. This feature simplifies data processing in CAPM apps, allowing developers to fetch relevant information effectively.
  • Compatibility with Modern Web Standards: OData v4 aligns well with modern web standards and technologies. This compatibility makes it suitable for building CAPM apps that can interact seamlessly with various front-end frameworks and platforms.
  • Support for Transient Entities: In CAPM apps, there are instances where entities may exist temporarily for processing and then discarded. OData v4 supports transient entities, which allows developers to work efficiently with temporary data, simplifying the app's overall design.
  • Simplified Code: OData v4's improved syntax and more streamlined URL conventions lead to simpler and cleaner code. This results in easier maintenance and development of CAPM apps, reducing the risk of errors and improving code readability.
  • Scalability: CAPM apps often deal with multiple applications and their respective data sets. OData v4's scalability ensures that the apps can handle growing data demands without compromising performance or stability.
  • Support for Associations and Navigation Properties: OData v4 allows developers to model associations between different entities and utilize navigation properties. In CAPM apps, this feature enables easy navigation through related data, enhancing the user experience.
  • Security Considerations: When working with CAPM apps, security is of utmost importance. OData v4 supports industry-standard authentication and authorization mechanisms, ensuring that data is accessed only by authorized users.

Choosing the right version of OData is vital for creating efficient and high-performing SAPUI5 applications. OData v2 offers a robust and mature option with comprehensive support, while OData v4 provides modern features and better performance. By understanding the unique use cases and advantages of each version, SAPUI5 developers can make informed decisions and build applications that align perfectly with their requirements and the capabilities of their SAP back-end systems.

Read more
Association and Navigation in OData

Association and Navigation in OData

Sanjo Thomas•23:47:00
In this blog we will be covering the concept of association and navigation in OData. 

In this tutorial, we will take example of navigating from one Sales Order to the related Sales Order line items, by using a link instead of manually putting a filter together. Moreover, it also allows us to use the $expand statement to fetch the Sales Order together will all the Sales Order line items in one call.

Lets say, we already have created an OData service in SEGW named ZGW100_XX_SO. Double click on Associations.
Press Create button.

Now, Enter the following values for association and press enter:
   

Name

SalesOrderSalesOrderItems

Principal Entity*

SalesOrder

Principal Entity Cardinality*

1

Dependent Entity*

SalesOrderItem

Dependent Entity Cardinality*

M


Now, create a referential constraint for the association
1) Expand the Associations node and the SalesOrderSalesOrderItems node and double-click Referential Constraints:















2) Choose the Create pushbutton:






3) Enter the following values and choose Enter:

Principal Key*

SoId

Dependent Property*

SoId

* This field has an Input Help




Now we create an association set for the association

1. Double-click Association Sets:


2. Choose the Create pushbutton:


3. Enter the values and choose Enter:

Name

SalesOrderSalesOrderItems

Association*

SalesOrderSalesOrderItems


And finally we create a navigation property based on the referential constraint

1. Expand Data Model > Entity Types > SalesOrder and double-click Navigation Properties:


2. Choose the Create pushbutton:

3. Enter the following values and choose Enter:

Name

SalesOrderItems

Relationship Name*

SalesOrderSalesOrderItems

Now we need to re-generate the runtime objects and we’re then ready to test the service

1. Choose the Generate pushbutton:

2. Verify that the runtime objects have been generated successfully:

3. Start the Gateway Client (Transaction /IWFND/GW_CLIENT) in a separate window to run the service. Provide the following URI to get the metadata for the service: 

/sap/opu/odata/sap/ZGW100_XX_SO_SRV/$metadata


The Sales Order collection now includes a navigation property.

4. When you now select a sales order entry using

/sap/opu/odata/sap/ZGW100_XX_SO_SRV/SalesOrderCollection(‘0500000001’), for example, you can simply add the navigation link /SalesOrderItems to navigate to the line items without having to set a filter yourself:


5. And finally you can use $expand to read all sales order items for a given sales order in a single http call.

Simply provide the following URI:

/sap/opu/odata/sap/ZGW100_XX_SO_SRV/SalesOrderCollection(‘0500000001’)/?$expand=SalesOrderItems


The $expand statement is handled by the framework (no additional implementation is required). Since the framework does not know that both entities can be obtained using a single RFC call, it executes two calls to the underlying BAPI. This can be improved by manually implementing (re-defining) the GET_EXPANDED_ENTITY method.

So we are done. The Service is up and running.


























Read more
Speech Recognition Custom Control

Speech Recognition Custom Control

Sanjo Thomas•08:48:00


Custom Control in sap ui5

In this blog, I will be taking about what is a Custom control in sapui5, how to develop it and how to use it once its implemented.  The idea is simple, we will create a simple custom control apart from what already exists in sapui5 framework.

SapUi5 offers us many built in controls like table, list, and different kinds of forms and so on, which helps to develop almost any type of required application. What if we have a requirement, apart from what already exist in sapui5? The best probable solution might be to create a custom control.

How a Custom Control works

Basically, the parent class of all the sap ui5 control is sap.ui.core which extends from sap.ui.core.Element. A control defines appearance and behavior.

Take a look at the structure of a control:


  1. Properties. Allows define its appearance and behavior on initialization.
  2. Aggregations. It lets group controls, variables, etc. It lets define some kind of containers inside a control. For example sap.m.ListBase has different aggregations items, swipeContent, headerToolBar etc.
  3. Associations. Controls can be associated with others that are not part of them. For example if we want to render a collection with next/prev functionality we could develop a previousItem / nextItem associations.
  4. Events. Control events should be related to higher level events more than standard DOM events (click, mouseover, etc). For example sap.m.ListBase has some events like select, delete, swipe etc.
  5. Appearance. Definition of our control in screen area. Every control has a render method in order to be rendered in HTML code.

This might give a better understanding if you have come across with sap.m.ListBase control.
So this was the basic understanding of what a custom control is. Now, with an example let’s just try to implement a custom control.

Requirement – Speech Recognition Custom Control

Sapui5 doesn’t offer us any control, which can be used for speech recognition. Here, I will create an inputControl and a button. The inputControl will be our custom control. So just lets start:

First, create a project in eclipse:

 
Here, I have made the project structure. Have a look at the project structure tutorial in my blog here: http://www.sapui5tutors.com/2016/03/sapui5-application-project-structuring.html
This project structuring is according to the best practices, so I would suggest to follow this.

In the view folder create a view named CustomControlView.  Now, the Best practice would suggest that there should be a separate folder for controller, but for the sake of simplicity, I have collected both view and controller in the same folder itself.

 
In the view, define the inputControl and the button

CustomControlView.view.xml

<core:View xmlns:custom="custom.controls.demo.control"
xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m"
controllerName="custom.controls.demo.view.CustomControlView">
<Page navButtonPress="onNavBack" showNavButton="false"
title="Cordova Speech recognition custom control (SAPUI5)" id="thisPage">
<content>
<Button text="Add Speech recognition control" id="__button0"
icon="sap-icon://add" type="Emphasized" press="onButtonPress" width="100%" />
<custom:SpeechRecognitionInputControl
width="70%" id="spoken1"></custom:SpeechRecognitionInputControl>
</content>
</Page>
</core:View>


CustomControlView.controller.js

sap.ui.localResources('control');
jQuery.sap.require("control.SpeechRecognitionInputControl");
sap.ui.controller("custom.controls.demo.view.CustomControlView", {
onButtonPress: function(evt){
var x = new control.SpeechRecognitionInputControl();
var oLayout = this.getView().byId("thisPage");
oLayout.addContent(x);
}
});

Now Create a new folder in the webcontent named as control and create a new js file. You can name it accordingly, here I have named it SpeechRecognitionInputControl.js.


This is the main file, where the coding is to be done

SpeechRecognitionInputControl.js

jQuery.sap.declare("custom.controls.demo.control.SpeechRecognitionInputControl");
jQuery.sap.require("sap.m.Button");
jQuery.sap.require("sap.ui.core.Icon");
sap.m.Input.extend("custom.controls.demo.control.SpeechRecognitionInputControl", { //inherit Input definition
metadata: {
properties:{
width: {type : "string", defaultValue: "70%"},   /// setting default width
value: {type : "string", defaultValue: ""},
recognition: { type:"any" }   //// for Cordova plug-in recognition object
},
aggregations : {
_buyButton      : {type : "sap.m.Button", multiple : false, visibility: "hidden"}   // Agregate button
}
},
init : function(){   /// init the control
var oControl = this;
var oBuyBtn   = new sap.m.Button({
text:"", width:"40px",  icon:"sap-icon://microphone", type:"Default",
press: function (oEvent) {    //////// Handle press event
if ( oControl.recognition !== undefined){
oControl.recognition.start();  //// Start recognition
var _oBuyBtn = oControl.getAggregation("_buyButton");
_oBuyBtn.setType(sap.m.ButtonType.Emphasized);  /// Change button color
}
}
});
this.setAggregation("_buyButton", oBuyBtn);  /// Add aggregation control
if (sap.hybrid !== undefined ){  ///// hybrid library defined ?
var isCompanionApp = sap.hybrid.getUrlParameterName("companionbuster");
if (window.cordova || sap.hybrid.Cordova || isCompanionApp) {   //// Verifying if it is a Cordova app
document.addEventListener("deviceready", function() {
// load odata library
oControl.recognition = new SpeechRecognition();  /// Load Speech recognition librar
oControl.recognition.onnomatch = function(event) {         /// Add event handlers
var _oBuyBtn = oControl.getAggregation("_buyButton");
_oBuyBtn.setType(sap.m.ButtonType.Default);
};
oControl.recognition.onerror = function(event) {          /// Add event handlers
var _oBuyBtn = oControl.getAggregation("_buyButton");
_oBuyBtn.setType(sap.m.ButtonType.Default);
};
oControl.recognition.onresult = function(event) {      /// Add event handlers for result
if (event.results.length > 0) {       /// If there is a success
oControl.setValue(this.value = event.results[0][0].transcript);  /// Set value with voice recognition
}
var _oBuyBtn = oControl.getAggregation("_buyButton");
_oBuyBtn.setType(sap.m.ButtonType.Default);  /// Get back the button to original state
};
}, false);
}else{
oBuyBtn.setType(sap.m.ButtonType.Default);
oBuyBtn.setEnabled(false);   //// Disable button if there is no cordova app
}
}else{
/////////////// hybrid not defined
oBuyBtn.setType(sap.m.ButtonType.Default);
oBuyBtn.setEnabled(false);   //// Disable button if there is no cordova app
}
},
renderer : {
render : function(oRm, oControl) {   /////// Render the control
oRm.write("<div");
oRm.writeControlData(oControl);       ////// Render control data
oRm.writeStyles();
oRm.write(">");
sap.m.InputRenderer.render(oRm, oControl);  //// pass the control to base renderer
oRm.renderControl(oControl.getAggregation("_buyButton"));  /// pass aggregated control for rendering
oRm.write("</div>");
}
}
});

Output would look like something like this:
 

Even though the speech functionality wont work, unless cordova plugin is installed and https://github.com/macdonst/SpeechRecognitionPlugin.git is integrated into the eclipse.Still, we learned how to implement custom control in sap ui5 application.

That’s all for now, Stay tuned for next post!!!
Read more