Category: SAP CAP

  • How to create and deploy UI5 App based upon CAPM using BAS

    Preface – This post is part of the SAP CAPM series.

    Introduction

    SAP CAPM is the new and most efficient way to develop SAP Cloud Applications. SAP Business Application Studio is the appropriate IDE that should be used for CAP Application creation. In this article we will explore SAP BAS, CAP Development and CAP Deployment over SAP BTP. Let us explore how to create and deploy UI5 App based upon CAPM using BAS.

    Steps to get started with BAS

    Step 01: The very first step is to visit Business Application Studio using SAP BTP.

    Step 02: Create a Dev Space by clicking the button as shown below:

    Create a Dev Space

    Step 03:  Give a suitable name for your space and choose Full Stack Cloud Application

    Full Stack Cloud Application

    A CAPM space will be created as shown below. Click it.

    CAPM space

    It will open the Business Application Studio Editor (BAS).

    Business Application Studio Editor

    Steps to create a CAPM Project

    1. Click “Start from template” in welcome screen
      Start from template CAP
    2. Select CAP Project and click Start
      CAP Project Start
    3. Provide a name of the project and choose the one shown below:
      CAP Project Configuration
    4. Click Finish. This will generate a project and will open up the same.
    5. In case you get a popover to install recommended extension, click install.

     

    Steps to add Approuter in your CAPM

    The very next thing after CAPM App creation is to add an approuter. You can read more about it here. Follow below steps to create an App Router. You can create both standalone app router as well as SAP Managed App Router (needs additional subscription).

    How to add Standalone Approuter using BAS?

    To add a standalone approuter using BAS, follow the given steps:

    Step 01: Create a MTA or CAPM Application such that your project has a MTA.yaml file (We did this above).

    Step 02: Right click on the MTA file and click “Create MTA Module from Template”

    Open MTA Module from Template

    Step 03: Click “Approuter configuration” from the wizard

    Approuter configuration

    Step 04: Enter the details as shown below:

    App Router Details

    That’s it, an approuter will be added in your project with configuration in MTA file.

    How to add Managed Approuter using BAS?

    The creation of SAP Managed approuter is almost similar to Standalone approuter until step 03.
    In step 04, you need to choose “Managed Approuter” from the drop down, followed by a unique name for the approuter. That’s it, an approuter will be added in your project with configuration in MTA file. Read more about it here.

    Once deployed, you can visit HTML5 Applications under your subaccount. In case you see the given screen:

    Managed Approuter

    In this case you need to subscribe any of the above, then you will be able to see your Applications as shown below:

    HTML5 Applications

    How to add a UI5 project in CAPM

    Once you have a CAPM project with basic module, you will have a folder called app. This folder is meant for UI5 applications. In this use case it is empty. Now we will add MTA modules to create UI5 App.

    Step 01: Create a MTA or CAPM Application such that your project has a MTA.yaml file (We did this above).

    Step 02: Right click on the MTA file and click “Create MTA Module from Template”

    Open MTA Module from Template

    Step 03: Click “SAP Fiori application” from the wizard

    SAP Fiori application

    Step 04: Now, click the filter to choose “SAPUI5 freestyle” (In case you want a Fiori Elements based app, you can keep the first one)

    SAPUI5 freestyle

    Then choose “SAPUI5 Application”:

    SAPUI5 Application

    Step05: Now in next section, either choose your data source if you have or select “None” as below:

    data source for UI5

    Step 06: Now enter the name of the initial view (It can be changed later too):

    View of UI5

    Step 07: This is an important step, choose the folder “app” via project folder path and mark Yes against “Add deployment configuration to MTA project”. This will add all required deployment related configurations in MTA file.
    Deployment configuration of UI5

    Root folder of UI5

    That’s it. Once clicked on Finish will add a UI5 application within app folder.

    Steps to test and deploy whole CAPM project on SAP Cloud foundry (or SAP BTP)

    1. Open Terminal from the menu bar
    2. To test the App locally, write cds watch. You will see a pop up, press “Expose and Open”. You will see a new tab:
      local test of App in CAP
    3. Click on Web Applications link. It will open a blank UI5 App as shown below:
      local run ui5 app in BAS
      This confirms that the UI5 app is working fine.
      If you click the services endpoints link, then you will see an OData as shown below:
      Service in CAP
      This confirms even our services are working fine. This is a green signal for deployment.
    4. Now open a new terminal and write mbt build. This will generate a new folder “mta_archives” with a mtar file
      The above step will also generate new folders
      MTAR generation CAP
    5. Before we deploy to SAP Cloud foundry, we have to login in our environment. In terminal write cf login
      Enter API endpoint: https://api.cf.eu10.hana.ondemand.com/ (or whatever it is for you)
      followed by your login email and password
      You will be logged into your respective environment. In case you have multiple subaccount, then you might be asked to choose one of them (using a number)
    6. Now right click on the mtar file generated and click “Deploy MTA Archive”
      SAP CAP Deployment in BAS

    This will deploy the app in cloud foundry or SAP BTP. In the terminal you will get successful message that all the services were deployed.

    1. To test the deployed UI5 App, go to SAP BTP and reach your respective subaccount -> space. Here list of applications will appear, search for your approuter.
      Run UI5 using App Router
      Open it. You will find a link. You can even find it within the terminal after deployment, e.g.:
    2. Opening only App Router will give error “Not Found”. So, append your approuter as mentioned below:
      Extend the URL with the application ID “/<app ID>”:
      https://ps-scp-<space name>-mta-<app name>-approuter.cfapps.<region>.hana.ondemand.com/<app ID>Note! If the “<app ID>” contains dots e.g. “<app ID>” is “test2.test.1.test0”, dots should be ingnored and the URL should look as:https://ps-scp-<space name>-mta-<app name>-approuter.cfapps.<region>.hana.ondemand.com/test2test1test0

    In our use case the url will be: <app router>/nscap-test/index.html

    1. After login, you will see the below link:
      UI5 deployed App test

    Congratulations, you have successfully created your CAPM UI5 App and deployed the same. You can also check other ways to create a UI5 CAPM App.

  • AppRouter in SAP BTP

    Preface – This post is part of the SAP Multi-Target Application (MTA)  series.

    Introduction

    In the era of cloud applications, a single project has multiple UI5 applications and multiple microservices. In this use case either we can have individual urls to access these or a single url that can act as an entry point. An approuter helps developers to get a single url to access all their apps and microservices. In this article we will learn more about AppRouter in SAP.

    What is App Router in SAP?

    SAP Cloud Foundry provides a nodeJs library in the form of BTP instance that acts as a single point-of-entry for an application or microservice running in the Cloud Foundry. It is known as Application Router or App Router or AppRouter.

    We can perform following operations using App Router:

    • Serve static data: The index.html file within App Router can be used to display static content or welcome page of an application
    • Authenticate users: A user can be authenticated at approuter level, even before accessing any application
    • Rewrite URLs: It can be used to integrate destination, integrate business services and even perform logout for an application
    • Request to other microservices within same project

    Types of App Router in SAP

    SAP provides two types of approuter, they are:

    1.      Standalone Approuter

    A standalone approuter is a custom approuter that is created and maintained by developer. A developer has to update the xs-app.json and MTA.yaml files according to the project needs.

    2.      SAP Managed Approuter

    A SAP Managed Approuter enables a developer to execute HTML5 applications in SAP Cloud Platform. It is completely managed by SAP, hence you are not required to update any details further, once created.
    To use managed application router, SAP provides three options:

    • SAP Work Zone
    • SAP Launchpad service
    • SAP Cloud Portal

    Once the application is deployed, the apps are available under the tab HTML5Repository within sub-account.

    How to add Standalone Approuter using BAS?

    To add a standalone approuter using BAS, follow the given steps:

    Step 01: Create a MTA or CAPM Application such that your project has a MTA.yaml file.

    Step 02: Right click on the MTA file and click “Open MTA Module from Template”

    Open MTA Module from Template

    Step 03: Click “Approuter configuration” from the wizard

    Approuter configuration

    Step 04: Enter the details as shown below:

    App Router Details

    That’s it, an approuter will be added in your project with configuration in MTA file. Read more about it here.

    How to add Managed Approuter using BAS?

    The creation of SAP Managed approuter is almost similar to Standalone approuter until step 03.
    In step 04, you need to choose “Managed Approuter” from the drop down, followed by a unique name for the approuter. That’s it, an approuter will be added in your project with configuration in MTA file. Read more about it here.

    Once deployed, you can visit HTML5 Applications under your subaccount. In case you see the given screen:

    Managed Approuter

    In this case you need to subscribe any of the above, then you will be able to see your Applications as shown below:

    HTML5 Applications

  • How to create and deploy CAPM using BAS Extensions

    Preface – This post is part of the SAP CAPM series.

    Introduction

    SAP CAPM is the new and most efficient way to develop SAP Cloud Applications. SAP Business Application Studio is the appropriate IDE that should be used for CAP Application creation. In this article we will explore SAP BAS, CAP Development and CAP Deployment over SAP BTP. Let us explore how to create and deploy CAPM using BAS Extensions.

    Steps to get started with BAS

    Step 01: The very first step is to visit Business Application Studio using SAP BTP.

    Step 02: Create a Dev Space by clicking the button as shown below:

    Create a Dev Space

    Step 03:  Give a suitable name for your space and choose Full Stack Cloud Application

    Full Stack Cloud Application

    A CAPM space will be created as shown below. Click it.

    CAPM space

    It will open the Business Application Studio Editor (BAS).

    Business Application Studio Editor

    Extensions in BAS

    In this article we will learn how to use Extensions in BAS for application creation.

    1. Click on View -> Find command
      Find Command in BAS
    2. Search “Generators” and click on “Explore and Install Generators”
      Explore and Install Generators in CAP
    3. From the search shortcut, filter SAP UI5 and install “generator-sap-ui5-app”, “generator-easy-ui5” and “generator-ui5_to_mta” and other UI5/Fiori extensions.
      UI5 Generators in CAP

    The above will be helpful in creating UI5 projects and auto generate codes for us.

    Steps to create a CAPM Project

    1. Click “Start from template” in welcome screen
      Start from template CAP
    2. Select CAP Project and click Start
      CAP Project Start
    3. Provide a name of the project and choose the one shown below:
      CAP Project Configuration
    4. Click Finish. This will generate a project and will open up the same.
    5. In case you get a popover to install recommended extension, click install.

    How to add a UI5 project in CAPM using Extension

    The newly created CAP project will have empty app folder as shown below:

    CAP Project Structure

    1. Open View-> Find command (or ctrl+shift+P)
    2. Find “Run Generator”
      Run Generator in BAS
    3. Now find “fiori-module:app”. This will only appear if you install all the extensions that we have mentioned above.
      fiori module in BAS
    4. This will open a wizard. Choose the App folder and click Next
      UI5 wizard in BAS
    5. Enter Module name, it will be the name of your UI5 App, and click Next
      ui5 module in BAS
    6. Choose SAPUI5 Application and click Next
      UI5 template in BAS
    7. Choose the App Router
      App Router Configuration in BAS
    8. Choose Authentication option.
      Authentication for CAPM
    9. Choose View name
      View in UI5
    10. Now, you will see both UI5 and App router is generated
      UI5 app router cap

    Even in MTA you can see these added:
    cap-test-approuter
    cap-test_html_repo_runtime
    cap-test_ui_deployer
    ui5-test

    With all other important files that are mandatory for UI5 module deployment over BTP. Now we are ready to test it locally and deploy it over BTP.

    Steps to test and deploy whole CAPM project on SAP Cloud foundry (or SAP BTP)

    1. Open Terminal from the menu bar
    2. To test the App locally, write cds watch. You will see a pop up, press “Expose and Open”. You will see a new tab:
      local test of App in CAP
    3. Click on Web Applications link. It will open a blank UI5 App as shown below:
      local run ui5 app in BAS
      This confirms that the UI5 app is working fine.
      If you click the services endpoints link, then you will see an OData as shown below:
      Service in CAP
      This confirms even our services are working fine. This is a green signal for deployment.
    4. Now open a new terminal and write mbt build. This will generate a new folder “mta_archives” with a mtar file
      The above step will also generate new folders

    MTAR generation CAP

    1. Before we deploy to SAP Cloud foundry, we have to login in our environment. In terminal write cf login
      Enter API endpoint: https://api.cf.eu10.hana.ondemand.com/ (or whatever it is for you)
      followed by your login email and password
      You will be logged into your respective environment. In case you have multiple subaccount, then you might be asked to choose one of them (using a number)
    2. Now right click on the mtar file generated and click “Deploy MTA Archive”

    SAP CAP Deployment in BAS

    This will deploy the app in cloud foundry or SAP BTP. In the terminal you will get successful message that all the services were deployed.

    1. To test the deployed UI5 App, go to SAP BTP and reach your respective subaccount -> space. Here list of applications will appear, search for your approuter.Open it. You will find a link. You can even find it within the terminal after deployment, e.g.:
      Run UI5 using App Router
    2. Opening only App Router will give error “Not Found”. So, append your approuter as mentioned below:
      Extend the URL with the application ID “/<app ID>”:
      https://ps-scp-<space name>-mta-<app name>-approuter.cfapps.<region>.hana.ondemand.com/<app ID>Note! If the “<app ID>” contains dots e.g. “<app ID>” is “test2.test.1.test0”, dots should be ingnored and the URL should look as:https://ps-scp-<space name>-mta-<app name>-approuter.cfapps.<region>.hana.ondemand.com/test2test1test0

    In our use case the url will be: <app router>/nscap-test/index.html

    1. After login, you will see the below link:
      UI5 deployed App test

    Congratulations, you have successfully created your CAPM UI5 App and deployed the same. You can also check other ways to create a UI5 CAPM App.

  • Consuming Services in SAP CAP

    Preface – This post is part of the SAP CAPM series.

    Introduction

    In previous articles we have defined modeling in CAP, learnt Defining Services in SAP CAP and performing operations on SAP CAP Services. In this article we will learn Consuming Services in SAP CAP.

    Consuming Services in SAP CAP

    To keep the consumption of services uniform irrespective of the type of service being consumed, CAP provides a generic paradigm.

    const srv = cds.connect.to('some-service')
    
    // could be any of...
    
    // - local service
    
    // - remote service client
    
    // - database client
    
    let query = SELECT.from(Books).where({ID:111})
    
    let books = await srv.run (query)

     

    The above code snippets can be demonstrated as following:

    Consuming Services in SAP CAP

    Note: CAP treats even Database as a service which eventually enhances the database interaction with the help of generic event handlers.

    Types of Service Consumption

    • Event-Based Consumption

    The local services can be accessed by Node.js event emitter asynchronously and directly. But to access the external service, we will have to configure the package.json or .cdsrc.json file. We can also enable the Enterprise messaging1 by setting the property kind as “enterprise-messaging”.

    Example:

    { 
    
    "cds":
    
        {   
    
        "requires":
    
            {     
    
            "my.external.Service":
    
                {       
    
                "kind": "enterprise-messaging",       
    
                 "credentials": {       
    
                   "namespace": "my/custom/namespace"    
    
                     }  
    
               }   
    
         } 
    
      }
    
    }
    
    In case we want to enable Enterprise Messaging for all the external and internal services, then we will define the configuration under “messaging” section, the same is shown below:
    
    { 
    
    "cds":
    
    { 
    
       "requires":
    
    {
    
          "my.external.Service":
    
    {
    
            "kind": "odata"     
    
    },
    
          "messaging":
    
    {       
    
    "kind": "enterprise-messaging",
    
            "credentials":
    
    {
    
              "namespace": "my/custom/namespace" 
    
           }
    
          }
    
        }
    
      }
    
    }

    In case, you just want the local service to be enabled for Enterprise Messaging, it should be mentioned under the section cds.provides.

    Example:

    {  "cds": 
     {    
       "provides": 
     {      
        "my.own.Service": 
     {        
       "kind": "enterprise-messaging"
          }
        }
      }
    }

     

    • HTTP-Based Consumption

    To consume external service in SAP CAP, we need to define it under Destination Service2.

    In the package.json or in the .cdsrc.json the consumed service needs to be configured with the following:

    • Destination:Name of the destination (optional)
    • requestTimeout: ms until a request times out Default is 60,000 ms (optional)
    • model:The CSN3 model of the external service
    • poolConnections to the external service are pooled to prevent DOS-Attacks (optional)

     

    Example:

    {  "cds": {    "requires": {      "externalService": {        "kind": "rest/odata",        "model": "path/to/model",        "credentials": {          "destination": "destinationName",          "requestTimeout": 30000        },        "pool": {          "min": 1,          "max": 10        }      }    }  }}

    If the external service is further extended to used by some other application, then its parameters can be mentioned under credentials section, as below:

    {  "destination": "destinationName",  "url": "...",  "username": "...",  "password": "..",  "requestTimeout": 30000}

    Sending Requests

    Simple examples for reading data (works also for create, update, and delete):

    // Connect to external serverconst srv = cds.connect.to('my.external.service')const { Authors } = srv.entities // share request context with the external service// inside a custom handlerconst tx = srv.transaction(req) // url string inputconst response = await tx.get('/Authors?$select=name') // CSN entity input and fluent query APIconst response = await tx.read(Authors).where('ID', 1) // CQN input from fluent query APIconst cqn = SELECT.from(Authors)const response = await tx.run(cqn)

     

    Adding Event Handlers

    We can add event handlers while consuming a service. This will help us to perform specific tasks on success and failure of the service consuming operation. To handle errors, you can register an .on.error(() => {…}) handler.

    There are two ways to handle the events:

    1. By specifying the event name

    Example:

    const srv = cds.connect.to('my.external.service')srv.on('myEvent', msg => console.log(msg.data))srv.on(['myEvent', 'myOtherEvent'], msg => console.log(msg.data))srv.on('myBoundEvent', 'myEntity', msg => { 
       if (msg.data.age < 18) 
    {
          throw new Error('Cannot handle this event.')    
    }
    })
    1. By specifying the topic directly

    Example:

    const srv = cds.connect.to('my.external.service')srv.on.error(err => { // handle error})

    Emitting Events

    To emit events, you can use the .emit method described in srv.emit.

    There are two ways to create Emits:

    1. By specifying the event name
    2. By specifying the topic directly

    Example:

    const srv = cds.connect.to('my.external.service') srv.emit('myEvent', {some: 'payload'})srv.emit('myBoundEvent', 'myEntity', {some: 'payload'})srv.emit('my/custom/namespace/my/custom/topic', {some: 'payload'})srv.emit('topic:myCustomTopic', {some: 'payload'})srv.emit('myEvent', {some: 'payload'}, {some: 'headers'})

    Best Practises related to Service Consumption:

    • Make sure, that destination configurations for deployment aren’t shared on any file shares
    • There are different types of messaging instances, use only enterprise-messaging for production environment
    • It is good to provide the destination name, else the runtime will look for the name of the configured data source i.e. externalService in previous example
    • To connect to an external service, connect.to should be used
    • As of now only CRUD operations can be performed using send requests. And only Read all, read single can be performed using send requests. No query like filtering or ordering is supported for send request operations
    • An Enterprise Messaging service creates a queue4 for every request and in case it is unused, it must be removed from the SAP Cloud Platform manually
  • Operations on Services in SAP CAP

    Preface – This post is part of the SAP CAPM series.

    Introduction

    In previous article we have explored the ways to define services in SAP CAP. In this article we will learn about the operations on Services in SAP CAP.

    Operations on Services in SAP CAP

    1. Ignoring fields from Services: We can ignore fields using annotation @cds.api.ignore
    2. Adding Action and Functions: We can directly call a function/action, like we have used cancelLeave above, by mentioning it in node.js while calling the service. This can be done in two ways:
      1. Unbound action: For this type of actions, we mention the action in the service itself
    srv.on('cancelLeave', (req) => {
    
    // do something ...
    
    })

     

    1. Bound action: For this type of actions, we mention the action at entity level. It means, we will have to mention the name of the entity during the call
    srv.on('getEmployeeCount', 'Employees', (req) => {
    
    // do something ...
    
    })

     

     

  • Defining Services in SAP CAP

    Preface – This post is part of the SAP CAPM series.

    Introduction

    A service or a metadata service is used to define the data and its structure. It includes all the data models with annotation as well as associations and navigations. In this article we will explore more about Defining Services in SAP CAP.

    Defining Services in SAP CAP

    In CAP, we have already defined multiple entities with association. Later we have added annotations too using Aspects. In service definition, we write all the entities within another entity and give it the name of a service. Here we have created a service in file “service.cd”.

    entity EmployeeService {
    
    enity Employee {
    
    key ID : UUID;
    
    name  : String;
    
    Role : Association to Manager;
    
    }
    
    entity Manager {
    
    key ID : UUID;
    
    name   : String;
    
    Role  : Association to many Role on Employee.Manager = $self;
    
    }
    
    }

     

    To separate the entity sets from the service, unlike the example mentioned above, we will call the domain modals in our services. Hence, all the models will be as usual defined within a model cds e.g.  schema.cds and then it would be called from a Service using CQL (CAP Query Language).

    Example:

    using { empInfo as info } from 'db/schema';
    
    
    
    
    entity EmployeeService{
    
    
    
    
    entity Employee as SELECT from info.Employees{ *,
    
    Employees.firstname ||' '|| Employees.lastname as name : String,
    
    manager.name as manager,
    
    } excluding { salary, currency};
    
    entity Manager as projection on empInfo.Manager
    
    where Manager.Department = 'IT'
    
    order by name;
    
    }

     

    It is recommended to use one service per use case. It helps us to maintain proper authentication and checks.

    Example:

    using { empInfo as info } from './db/schema';
    
    /** Serves end users browsing Employee and Insert Employee Details */ 
    
    service EmployeeService{
    
    @readonly  entity Employee as SELECT from info.Employees{ *,
    
    firstName, lastname
    
    };
    
    @requires: 'authenticated-user'@insertonly entity Salary as projection on info.Salary;
    
    
    
    
    }
    
    /** Serves registered users managing their salary and leave */
    
    service UsersService {
    
    @readonly entity Salary as projection on info.Salary
    
    where EmployeeID = $user; // limit to own ones
    
    action cancelLeave ( ID: Salary.ID, reason:String );
    
    }
    
    
    
    
    /** Serves administrators managing everything */
    
    @requires: 'authenticated-user'
    
    service AdminService {  entity Employee   as projection on info.Employees;
    
    entity Salary as projection info.Salary;
    
    }

     

  • Domain Modelling in SAP CAP

    Preface – This post is part of the SAP CAPM series.

    Introduction

    A Domain Model in SAP CAP is a model which describes the static, data-related aspects of a problem domain in terms of entity-relationship models. In this article we will study the Domain Modelling in SAP CAP in detail.

    Domain Modelling

    In simple words, a CDS in SAP CAP produces domain model in such a way that it defines the business problem in terms of keys, fields and annotations. The code to generate a domain model is written in a CDS schema (db/schema.cds). These domain models can be used in Service Definitions, Persistence Models, Databases or even reused within another domain model.

    Sample Example:

    Namespace empInfo;
    
    using {Currency, managed} from '@sap/cds/common';
    
    
    
    
    entity Employees: managed {
    
    key ID: Integer;
    
    firstName: localized String (111);
    
    lastName: localized String (1111);
    
    manager: Association to Managers;
    
    dateofJoining: Integer;
    
    salary: Decimal (9,2);
    
    currency: Currency;
    
    }

     

    In this example we have created a file schema.cds where we have created an entity Employees which includes basic details of an Employee

    This whole schema has been given a namespace i.e. empInfo

    This schema uses a standard data type i.e. Currency. Using the standard data type like this helps us to bring all the predefined value helps related to it.

    We use CDS to create a Model. In that CDS, we use

    1. Entities to represent set of unique objects e.g.:
      1. Employee Basic Information
      2. Employee Communication Information
      3. Employee Salary Information
    2. Associations to define relationships
      1. Manager association to another entity Manager which will have all the Managers list

    Naming Convention & Recommendations

    1. The name of entity should start with a capital letter and it should be human readable and self-explanatory – for example, Employees
    2. Start elements with a lowercase letter – for example, firstName
    3. It is recommended to use plural form of entities – for example, Employees
    4. It is recommended to use singular form of types – for example, Currency
    5. don’t repeat contexts – for example, Employees.name instead of Employees.EmployeeName
    6. prefer one-word names – for example, salary instead of salaryAmount
    7. use ID for technical primary keys – for example, ID for Employee ID
    8. You can use Namespace to make your entities unique. It is like client concept in SAP where you can have duplicate schemas (cds files) with unique Namespace to differentiate them. Namespaces are optional, use namespaces if your models might be reused in other projects. At the end of the day they’re just prefixes, which are automatically applied to all relevant names in a file. – for example,

    namespace laptop;entity Dell {}

    ..… is equivalent to:

    entity laptop.Dell {}

    1. You can use contexts for nested namespace sections. – for example,

    namespace laptop;entity Dell {}           //> laptop.Dellcontext Apple {      entity MacBookPro {}       //> laptop.Apple.MacBookPro     entity MacBookAir {}         }

     

    Entities

    Entities are like tables with primary keys. We can perform CRUD operation using these Entities. Keep it as flat as possible. Do not over Normalize it. Do not use non-reusable types. This section is only for modelling, only annotation related to individual fields should be added and no technical details (logics) should be added.

    Types

    Types are like Domain in SAP ABAP, it used to define the typed of Data elements.

    Aspects

    Aspects are the extensions of the Models and are mainly used to extend the existing definitions and annotations. Once a model is defined, we can use different cds files (Aspect) to add annotations on top of them for specific task.

    For example-

    • cds– your core domain model, kept clean, simple and understandable
    • audit-model.cds– adds additional fields required for auditing in a file
    • auth-model.cds– adds annotations for authorization.

    Primary Keys

    Like tables & CDS in SAP ABAP, we maintain Primary keys for Entity using keyword key.

    A primary key can be reused across the model by using the methodology of common definitions.

    We can create a common.cds Model where all the common definitions can be stored.

    // common definitions

    entity StandardEntity {
    
    key ID : UUID;
    
    }
    
    Now these  common definitions can be reused as below:
    
    using { StandardEntity } from './common';
    
    entity Employee : StandardEntity {
    
    name : String;
    
    ...
    
    }
    
    entity Manager : StandardEntity {
    
    name : String;
    
    ...
    
    }

     

    The common file is already created by default with a predefined entity named cuid.

    Mapping UUIDs to OData

    CDS maps UUIDs to Edm.Guid, by default, in all of the OData models. However, the OData standard puts up restrictive rules for Edm.Guid values – for example, only hyphenated strings are allowed – which may conflict with existing data. Therefore, we allow the default mapping to be overridden as follows:

    entity Books {

    key ID : UUID @odata.Type:’Edm.String’;

    }

    If necessary, you can also add the annotation @odata.MaxLength to override the corresponding property, too.

    Association

    It is used to define relationship between two entities. Like ABAP CDS, here too we use the word Association. Here, the keyword many indicates a 0..* cardinality. The restrictions for cardinality can be added as a constraint (where condition) – for example, using not null.

    Compositions

    Unlike Association where we associate a field of entity with the objects of an entire entity, the compositions just refer to specific field of another entity. It has extra advantage of self-managed deep operations(Insert/Update) and cascaded deletion(Multi Dependent table deletion).

    // Define Orders with contained OrderItemsentity Orders {  key ID   : UUID;  Items    : Composition of many Order_Items on Items.parent=$self;}entity Order_Items { // shall be accessed through Orders only  key parent : Association to Orders;  key book   : Association to Books;  quantity   : Integer;}

    Best Practises

    1. Don’t add technical details in Models, we use Aspectsfor that
    2. Use short names and simple flat models
    3. Don’t over Normalize the entities in Models
    4. Use local integer sequences if you really deal with high loads and volumes. Otherwise, prefer UUIDs

    Till now what we have learned: Creation of Model and Aspects on top of it .

    Domain Modelling in SAP CAP

  • Difference between SAP MTA and SAP CAP

    Preface – This post is part of the SAP Multi-Target Application (MTA) and SAP CAPM series.

    Introduction

    SAP has recently introduced two different package based development modules: SAP MTA and SAP CAP (or CAPM). It is getting tough for developers and architects to choose the best among them. In this article we will try to explain the difference between SAP MTA and SAP CAP.

    SAP MTA

    A Multi-Target Application (SAP MTA) is a package comprised of multiple libraries, application and resource modules. These have been created using different technologies and deployed to different runtimes but have a common life-cycle. You can bundle different modules together, describe them along with their inter-dependencies to other modules, services, and interfaces, and package them in a Multi-Target Application(MTA) .

    SAP CAP

    SAP Cloud Application Programming Model, also known as SAP CAP is a framework of tools, languages and libraries (both open source and SAP tools and technologies) designed efficiently with SAP best practices to help developers to minimize coding efforts, develop reusable peace of codes in form of micro services and to focus on designing and implementing business/enterprise specific logic.

    Difference between SAP MTA and SAP CAP

    Following are the differences between SAP MTA and SAP CAP:

    SAP MTA SAP CAP
    All the UI5/Fiori Apps are deployed now as MTA Even CAP is deployed as MTA
    MTA includes given modules:

    ·         HTML5(UI5/Fiori)

    ·         Node.js

    ·         Java

    ·         SAP Hana DB Module

    ·         SAP Cloud Platform Service

    CAP includes given modules:

    ·         HTML5(UI5/Fiori)

    ·         Node.js

    ·         Java

    ·         SAP Hana DB Module

    ·         SAP Cloud Platform Service

    ·         CDS Modelling

    MTA doesn’t support CDS Modelling CAP supports CDS Modelling
    MTA is good for creating cloud applications with DB already in place either at ABAP or HANA XS CAP is a single bundle to write data modelling, maintain Authorization, interact with various internal, external and DB services
    MTA is a subset of CAP CAP is an extension of MTA
    SAP MTA is older and more stable. SAP CAP is new, only CAP Cookbook is there for reference
    With only MTA, we will miss CAP capabilities With only CAP, we will have MTA as well as other extended capabilities
  • What is SAP Cloud Application Programming Model

    Preface – This post is part of the SAP CAPM series.

    Introduction

    We have been writing codes in different languages (such as ABAP, CDS, UI5/FIori and OData) at different platform (SAP NetWeaver, SAP Editor, HANA Studio, and SAP Web IDE) to achieve CRUD operation on business data. These all have their own limitation such as source independent development, platform independent development, etc. To remove dependency on multiple platforms and to combine SAP and open-source tools at a single platform, SAP came with Cloud Application Programming Model. In this article we will explore it in detail.

    SAP Cloud Application Programming Model

    SAP Cloud Application Programming Model, also known as SAP CAP is a frameworks of tools, languages and libraries (both open source and SAP tools and technologies) designed efficiently with SAP best practices to help developers to minimize coding efforts, develop reusable peace of codes in form of micro services and to focus on designing and implementing business/enterprise specific logic.

    Architecture of SAP Cloud Application Programming Model

    In this section we will talk about two different architectures. The first one will be the high level architecture provided by SAP. The other one will emphasize more on the flow of development.

    SAP Cloud Application Programming Model

    According to the architecture attached above, we can conclude that in this programming model we will be using:

    1. Web IDE and other development tools such as Visual Studio Code.
    2. To model our data we will be using the annotation power of HANA CDS.
    3. To write business logic we will be using Service SDKs such as Node.js or Java
    4. To deploy our node module, java module, UI5 Module we will have Cloud Foundry as Paas.
    5. To save our business data we will be using HANA or other database
    6. To develop our user Interface we will be using SAP Fiori and other UI tools
    7. The whole tool and framework will be utilizing on SAP Cloud Platform Infrastructure

    Now to understand the architecture in a better way, we can redesign it as below:

    SAP CAP Architecture

    In the architecture shown above we have illustrated the flow of development in terms of CAP development.

     

    Technologies and Tools Involved in SAP Cloud Application Programming Model

    Tool/Technology Purpose Description
    Hana Data Base Store Business Data This can be any database
    Core Data Services Model Data Service It mainly uses HANA CDS Artifacts
    Java/ Node.js Add Business logic In place of ABAP, business logic will be written here
    UI5/Fiori UI Design Like convention Fiori Application, the UI will be developed in same uniform manner
    SAP Cloud Foundry CAP Deployment The CAP application is deployed in to SAP Cloud Foundry as a MTA application

     

    Why and When to choose SAP Cloud Application Programming Model

    Everyone after looking the CAP framework wonders about its implementation in real life business use case. This framework is best suited for the development of applications for the enterprise having Cloud Infrastructure. Since this Application framework can consume both Hana Database as well on premise based OData exposed database, thus it is suitable for all types of enterprises.

    Even implementation of SAP Cloud Platform Integration is best supported by SAP CAP framework.