Quantcast
Channel: SAPUI5 Developer Center
Viewing all 789 articles
Browse latest View live

SAP UI5 Application is connected to 3rd party System (SQL Database) Using EJB & REST Service

$
0
0


I'm writing this blog post to share my experience on a specific development task on SAP NetWeaver Portal 7.3.I developed SAPUI5 application is connected to 3rd party systems (SQL) by using EJB and REST web application.


Pre-Requirements:-

SAP Enterprise Portal 7.3

Development Tool: NWDS 7.3 SP07

SAPUI5 Development Skills: HTML5, JavaScript, CSS3, AJAX/JSON and JQuery.

Connect Back-end Systems: EJB & REST Service (3rd Party Systems).


STEP 1:- I have installed SAPUI5 Plug-Ins in NWDS 7.3 SP07 using the block post


Developing SAP UI5 applications in SAP NetWeaver Developer Studio  - Part 1/2

 

Developing SAP UI5 applications in SAP NetWeaver Developer Studio  - Part 2/2

 

STEP 2:- I created “JDBC Custom Data Source” connection between Portal and SQL Database in NWA.


  1. Downloaded the required (ojdbc6.jar) jars from the google.
  2. In NWA, Configuration Management ---> Infrastructure --->Application Resources Select Create New Resource -> Deploy new JDBC driver

          1.PNG

           2.PNG

   3. Again, Select Create new resource -> New JDBC Custom DataSource.

       3.PNG

4. Created Custom data source alias in Dependent DataSource Aliases tab:

          4.PNG

5.  Finally we have custom DataSource and a DataSource Aliases tab.


STEP 3:-

I created EJB application called “rest/ejb”, web application called “REST/Web” and ear application (for deploy ejb/web applications) under J2EE perspective.

5.PNG

I created Session Beanwith@StatelessManager.java


Note: - Mainly my application is follows CURD methods, in this blog I include only search the data from the SQL System using REST Service. Same way will follow any methods like Insert/Delete/Update etc…


           1. Connected SQL System by using below code in “Manager.JAVA”. PFB code for your Reference.

                              6.PNG

               2. Code for Search the data from SQL Data Base. PFB code for your Reference            

 

@WebMethod(operationName="Manager", exclude=false)

    public List<PtnerGroup> querySearchManager(

                @WebParam(name="groupName") String groupName,

                @WebParam(name="countryName") String countryName

       List<PtnerGroup> pgList = new LinkedList<PtnerGroup>();

        Connection connection = null;

        Statement st = null;

        ResultSet rs = null;

        try{

  connection = this.getConnection(null);

  String sql = "select * from TABLENAME_GROUPS where";

  if (!"*".equalsIgnoreCase(groupName) && groupName != null

  && groupName.trim().length() > 0) {

 

 

  sql = sql + " (LOWER(name) like LOWER('%" + groupName

  + "%') OR group_id like '%" + groupName + "%') AND";

  }

  if (!"*".equalsIgnoreCase(countryName) && countryName != null

  && countryName.trim().length() > 0) {

 

 

  sql = sql + " (LOWER(country_name) like LOWER('%" + countryName

  + "%') OR COUNTRY_ID LIKE '%" + countryName + "%') ";

  }

  if (sql.endsWith("where")) {

 

 

  sql = sql.replace("where", "");

  }

  if (sql.endsWith("AND")) {

 

 

  sql = sql.replace("AND", " ");

  }

  if (!sql.contains("order by")) {

 

 

  sql = sql + "order by GROUP_ID";

  }

  //System.err.println("SQL Query:"+sql);

  st = connection.createStatement();

  rs = st.executeQuery(sql);

  while (rs.next()) {

  PtnerGroup pg = new PtnerGroup(rs.getString("GROUP_ID"), rs.getString("NAME"),

  rs.getString("COMMENTS"), rs.getString("COUNTRY_ID"), rs.getString("COUNTRY_NAME"),

  rs.getString("BRAND_ID"), rs.getString("BRAND_NAME"));

  pgList.add(pg);

  }

  return pgList;

   

        } catch (SQLException e) {

            logger.traceThrowableT(Severity.ERROR, null, e);

      } finally {

            try {

                  if (st != null)

                        st.close();

 

 

                  if (connection != null)

                        connection.close();

            } catch (SQLException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

            }

      }

    return null;

 

    }

 

       3. Now go the REST/Web application creates “ManagerGroupRest.Java”. PFB code for your Reference.

              

@Path("/manager")

public class ManagerGroupRest {

 

 

  final String JNDI_NAME = "demo.sap.com/b2b~rest~ear/LOCAL/Manager/com.manager.ejb.ManagerLocal";

  public ManagerGroupRest(){

  super();

  }

  private static final Location _location = Location

  .getLocation(ManagerGroupRest.class);

  @Path("search")

  @POST

  @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON,MediaType.TEXT_PLAIN })

  @Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })

 

  public Response queryPrtGroup(ManagerGroupSearch search){

  _location.infoT("in method queryPrtGroup");

  String groupName = search.getGroupName();

  String countryName = search.getCountryName(); 

  //System.err.println("Group Name:"+groupName);

  //System.err.println("grpManagerLocal:"+grpManagerLocal);

  try

  {

  InitialContext jndiContext = new javax.naming.InitialContext();

  GroupManagerLocal inventoryMgr = (GroupManagerLocal) jndiContext.lookup(JNDI_NAME);

  List<PtnerGroup> list = inventoryMgr.querySearchGroupManager(groupName, countryName);

  System.err.println("list:"+list);

  if (list == null) {

  System.err.println("null");

  return Response.status(Status.INTERNAL_SERVER_ERROR).build();

 

 

  } else {

  GenericEntity<List<PtnerGroup>> entity = new GenericEntity<List<PtnerGroup>>(list) {};

  System.err.println("entity:"+entity);

  return Response.ok(entity).build();

  }

  }

 

  catch(NamingException e)

  {

  e.printStackTrace();

  }

 

 

  return null;

  }

}



By using REST application I will generate REST URL like(http://hostname:50000/demo.sap.com~b2b~rest~web/rest/manager/search)


4.  Now test your rest URL is working or not in Mozilla Firefox. Install REST Plug-ins in Mozilla Firefox.

     7.PNG

5. After test the REST application Firefox the data will display in “Response Body(Preview)” and if will have any error/issues will get the status in “Response Header

 

STEP 4:-

Created SAP UI5 Application or Create Web application (under“WebContent” we have to create all required (HTML5, JavaScript, CSS3, AJAX/JSON and JQuery) and deploy the application in Server) in NWDS

 

          11.PNG


When we click on Submit Query. wewill read the data from  INPUT FIELDS and send to the REST Service by using below code

8.PNG

Once we received the data from SQL System, same data we are going to bind to the table by using below code

9.PNG

Code for Model.Js file

     12.PNG

 

Output of the SAPUI5 Application

10.PNG


STEP 5:- Same scenario we will develop the Update/Create/Delete etc… functionalities.



  Hope this is help full


Regards


Vijay Kalluri


Disable Authentication pop up and CSRF token for OData calls (using SAP Netweaver Gateway)

$
0
0

Hi,

 

I have seen loads of threads with the same topic but none of them specify the complete solution. They all give solutions in bits and pieces. After struggling for the past couple of days, I managed to crack it.

 

Issue:

You have developed a application(which is used to modify data in the backend)  using SAP UI5 as front end (deployed in Netweaver Portal) with NetWeaver Gateway OData services as backend. You want OData calls from UI to not show login pop-ups when the request is sent to the SAP Gateway server.

 

Solution:

An obvious one, set up the user credentials in 'Logon tab' of the SICF service.

 

Test it. Hey it works!! No authentication pop up. But you are too quick. Test the complete cycle until the data is saved in your UI5 application. You will find that you are getting 'CSRF token invalid' or 'CSRF token undefined' or a error message similar to this (along with HTTP status code 403 (Forbidden)) in the console. This error goes away as soon as you remove the user credentials from the logon tab of the SICF service.

 

Issue:

You want both the features - there must not be any authentication pop ups when application is accessed AND application should be able to save/modify data without any issue.

 

What happens:

According to the link Cross-Site Request Forgery Protection - SAP Gateway Foundation (SAP_GWFND) - SAP Library, the framework checks for all modifying requests the validity of the CSRF token in the request. The validation is done by the ICF runtime that checks against the token from the "anti-XSRF cookie". If the validation fails an HTTP status code 403 (Forbidden) is sent back.


When you provide logon details in the ICF node, you will not be getting CSRF token from the system. This is because CSRF will work only for services that require authentication. But when you send a modifying request to the framework, it expects CSRF token by default and hence the save fails.

 

Solution:

The only way is to disable the CSRF protection mechanism. The above CSRF link mentions how to disable it in the SICF service node. But that alone will not disable the CSRF token. You have to add the header('X-Requested-With' with a value of 'X')  in the ODATA request to disable the CSRF token completely.

 

Steps

 

1. Set the value of ~CHECK_CSRF_TOKEN=0 in the GUI_CONFIGURATION of your service (steps given in the link - Cross-Site Request Forgery Protection - SAP Gateway Foundation (SAP_GWFND) - SAP Library towards the end)

2. Maintain User credentials in the 'Logon Data' tab of your service - Remember this is needed to avoid authentication pop up.

3. Now depending on which route you use to update data, add the headers

 

a. If you use OData Model to update data, make sure that you give the following lines BEFORE the create/put/delete call.


var oEntry = {};

  oEntry.Empid = sap.ui.getCore().byId("Id").getValue();

  oEntry.Empname = sap.ui.getCore().byId("Name")

  .getValue();

  oEntry.Empadd = sap.ui.getCore().byId("Address")

  .getValue();

  oEntry.Empdes = sap.ui.getCore().byId("Role")

  .getValue();

  oModelSav.setHeaders({"X-Requested-With" : "X"});

  oModelSav.create('/EmployeeSet', oEntry, null, function(){

      alert("Employee Created Successfully -  "); 

  },function(){

  alert("Employee Creation Failed   ");

  }

  );

 

 

b. if you are using POST operation, use the code below.

Important Note:There is no need to issue a GET call before this since we do not want to use the CSRF token.

   var oHeaders = {  'X-Requested-With': 'X',  'Accept' : 'application/json',  };
OData.request({ requestUri : "http://<server>:<port>/sap/opu/odata/sap/ZMM_EMPLOYEE_SRV/EmployeeSet",                method : "POST",                         headers : oHeaders,                data:oEntry                },                function(data,request) {                  alert("Employee Created Successfully  ");                         location.reload(true);                  },                         function(err) {                      alert("Employee Creation Failed  ");                    });

Launching UI5 apps with additional URL parameters in WebIDE

$
0
0

I recently came across the issue of testing a UI5 app in the WebIDE that required URL parameters on launch and although this could be achieved easily on a local server setup, when deployed onto HCP the WebIDE seemed to provide few options for testing.

 

The WebIDE provides a nice size adjustable Frame layout to test code changed however the URL provided is run from a HCP server and so contains non standard URL parameters.

 

scn1.jpg

 

On a recent project I was required to launch my app with URL parameters after the index.html with a hash followed by multiple parameters.

e.g. https://account.hanaondemand.com/myapp/index.html/#/urlparam1/one/urlparam2/two

 

This can be particularly useful when running apps within environments that pass information into your UI5 app on launch, e.g. custom C4C apps. Or even to test routing mechanisms within HCP without having to commit your untested code to HCP with a version number or push it to HCP with a git tag for versioning.

 

As it happens, looking closer at the WebIDE settings you can customise how it runs web applications for testing purposes.

 

 

Under Run » Run Configurations » New Run Configuration you can specify how you would like to run your app.

 

scn2.jpg

 

Here you can specify settings such as which version of the SAPUI5 SDK you would like to load. You can even provide standard URL parameters which are in turn translated into ASCII characters as standard in your web browser.


Un-ticking the ‘Open with frame’ tick box will force WebIDE to load your app in full screen mode when the 3.jpg button is pressed, you may have to select the 'Run' menu and click on your test configuration.


4.jpgscn3.jpg

Now that your app has opened you can manipulate the browsers URL and test your code without having to deploy to HCP.

scn4.jpg

SAPUI5 FeedTile Control, HOW TO STOP date NULL Error in Console !!!

$
0
0

When You use FeedTile control in sapui5 and when you try remove Date from Feedtile control , for every image change in console you get date null error.

To avoid that Please Follow the below code:

 

//*****************************************IN VIEW********************************************//

var oImage1 = new sap.suite.ui.commons.FeedItem({

  title: "We Are Here To Connect !!!",

  image: "imgs/4i.jpg",

  publicationDate: new Date()

  });

 

var articles = new Array();

  articles.push(oImage1);

 

var oFeedTile = new sap.suite.ui.commons.FeedTile({

  items: articles,

  }).addStyleClass("oFeedTile");

 

 

  // Create a container for the FeedTile with a specified height and width

  var oBorderLayout = new sap.ui.commons.layout.BorderLayout({width: "450px", height: "300px"}).addStyleClass("oBorderLayout");

 

// Add the FeedTile to the container

  oBorderLayout.createArea(sap.ui.commons.layout.BorderLayoutAreaTypes.top, oFeedTile );

  oBorderLayout.setAreaData(sap.ui.commons.layout.BorderLayoutAreaTypes.top, {

  size : "100%",

  visible : true

  });

 

 

//*****************************************IN CSS********************************************//

.oFeedTile .sapSuiteUiCommonsFeedTileAge

{

  display:none!important ;

}

Share Your Experiences with OpenUI5 at SAP TechEd Pre-Conference in Barcelona

$
0
0

Only a few months left, then the time has come: SAP TechEd opens its doors again!

Whereas SAP TechEd Las Vegas can look back upon a long pre-conference day tradition this component has its premiere in this year's Barcelona schedule. All SAP TechEd Barcelona pre-conference sessions will be on Monday, November 9, 2015.


Now the actual news:

We are planning a half-day workshop about OpenUI5 at this pre-conference and willing to sponsor two individual sessions (each 60 minutes) as contribution to it. And there is more to it than that: As presenter you will receive a full Conference Ticket for SAP TechEd Barcelona on top to the complimentary registration for the workshop!


Want to be a part of this first edition of an OpenUI5 meet-up?

If you work or play in OpenUI5, we want to hear from you. Let us know what you are use OpenUI5 for. All customers and partners are welcome to submit.

Send me your proposal and share your idea for an item on the agenda. Write down as much as possible about your topic/project, including a working title, description, speaker name, and contact data. You will receive an email confirming receipt.

If you have any further question, you can also drop me a personal note.

Deadline for submitting proposals isFriday, August 28, 2015.


Any topic you would like to find on the agenda of this workshop?

Leave a comment and we're definitely going to see if we can squeeze it in.


I look forward to seeing your great contributions!

How to use drag and drop to sort a SAPUI5 list

$
0
0

In this tutorial I'll explain how you can make a sap.m.List sort-able by letting the user drag and drop the list items. For a demo of what this looks like, have a look at this video:

 

 

In Eclipse, create a new SAPUI5 project. In your index page, the following code is important:

 

index.jpg

Jquery UI provides an easy way to implement sorting, dragging, dropping,... By importing these libraries we can make use of these functionalities in our SAPUI5 project.

 

In our view we create our list, don't forget to give your list an ID, we need this in the controller:

view1.JPG

In our controller we do the following:

controller1.JPG

 

We access our list and we need to put the sort-able function specifically on the <UL> element of the list.

 

And that's it, with this short peace of code you can make your sap.m.list sort-able by using drag and drop.

How to use drag and drop between two SAPUI5 UI elements

$
0
0

In this tutorial I will explain how you can implement drag and drop in SAPUI5. We'll create a list from which we can drag the list items into a table. The details of the list item will be added as a row in the table. For a demo, look at the following video:

 

 

JQuery UI provides easy functionalities to implement drag and drop. To access these functionalities we need to import these libraries to our project. To to so, add the following code to your index page:

index.jpg

 

My code in my view is the following:

view2.JPG

In an HBox I added the list and the table. Make sure you give both the list and the table an ID, we need this in the controller.

 

In our controller, we will implement our code in the onInit() function. First part is general coding where I define my variables and set my model:

onInit1.JPG

 

The first step we need to do is make the list drag-able, you can do this with the following code:

onInit2.JPG

 

When you implemented this code you'll see that you can drag the list items, but when you drop them, nothing happens. For that we need to make our table drop-able:

onInit3.JPG

 

When the drop event is triggered, we can access the ID of our list item which we have dropped on the table. With this ID we can access the list item, retrieve the binding context and the path. And with this path we can read out the correct line from our material data. We then add this data as an item to our table.

 

And that's how easy it is to implement drag and drop functionalities in SAPUI5.

 

Remark: it does seem that the two elements need to be in the same element (in this case the HBox). I tested to see if it is for example possible to drag in a splitapp from the master view to the detail view but this doesn't seem to be possible. So there are some limitations.

A beginner’s guide to skilling up for SAP Fiori and UI5

$
0
0

New to UI5 and Fiori?  You've come to the right place!


This year has been a tough one for me having to “get with the times” to evolve my technical skillset beyond the ABAP world.  Luckily there’s plenty of freely available information and courses to help you make the jump.  Don’t wait for someone to send you on training – make time to skill yourself up!

 

 

Learning web technology skills

HTML, CSS, Javascript and JQuery form the basis of UI5 and it’s a good idea to know the basics so you understand the underlying behaviour of custom UI5 and SAP Fiori applications.  Codecademy and codeschool has a great series of courses to quickly understand the syntax and behaviour of these technologies if you’re not familiar.  I would suggest completing the following tracks:

 


Once you’ve understood the mechanics of these languages, I would recommend building a personal website to showcase your skills to potential employers.  Maybe a website resume about yourself?

 

 

Know how to use browser debuggers

If you’ve spent a lot of time using SAP’s great ABAP debugger, you’ll want to familiarise yourself with the wonderful web debuggers available.  I have a slight preference to Google Chrome dev tools however it doesn’t hurt to explore one of the following if your workplace has multiple browsers:


I can’t live without my browser debugger!



Understand how RESTful APIs work

If you’re not familiar with the basics of RESTful API’s, this page has a good overview and tutorial.

 

 

Get hands on with OData

  1. OData is a type of RESTful protocol and the main page has some great information worth reading too.
  2. I would recommend getting hands on with OData by downloading the Postman extension and installing in Google Chrome
  3. Once you have Postman you can do the basic OData tutorial.
  4. Once you’re done with this I would then look to SCN for some guides on how to build these in your SAP Netweaver Gateway system.



Learn about git, github, gists and jsbin

  • Git is a great open source code repository that all SAP developers should put on their “to learn” lists.
  • Codeschool has some great free interactive courses you can get hands on with.
    1. Try Git
    2. Git Real
    3. Git Real 2


If you get really good at UI5, feel free to contribute back to the community and share your examples on Github or jsbin.  DJ Adams has a great article about github and gists - Help Us To Help You - Share Your Code.  There's also discussion in the comments about how it compares with jsbin.  Either way - sharing is caring.


A hands on course you can learn about github is Mastering Github by codeschool.



Learn about SAP Fiori and UI5

The following SAP courses are great and will bring you up to speed quickly on various topics around Fiori, UI5, WebIDE, infrastructure, application design and business engagement:




Read “Get Started” in the UI5 Developer Toolkit

Throughout my UI5 journey, there’s been a number of times where the UI5 Developer Toolkit has answered my questions before doing a google search.  If you’re new I would go through the “Get Started” section and build an app from scratch.  You’ll find you will start referring to different sections as you go along and whilst it’s alien first time around, it will all eventually make sense if you persist.



Learn about wireframe mockups with Axure

 

 

References I can’t live without

Once you’re building your confidence with UI5, I would bookmark the following pages and keep them handy for reference!


  • Fiori Design Guidelines - My bible for best practise on how to design UI5 applications.  I’m not a trained designer and the experts who built this page have years of research behind these guidelines.  Great resources for building great UI5 applications.
  • Experience SAPSAP's user experience community website, a great place to educate yourself about good design.
  • Fiori Application Library - Great website to reference technical setup and see what Fiori apps are available to your customer.
  • Fiori Demo - Great website to quickly understand demonstrate sample Fiori applications.
  • W3schools - When you get proficient at HTML, CSS, Javascript and jQuery – sometimes you need a reference to see what’s available or how to implement something.
  • UI5 Developer Toolkit - The bible for UI5 development.  Gets better every time I visit it!


Have fun learning and if you have some great resources to share please feel free to add to the comments below.

 

Regards,

Ben


Get user name from server login page

$
0
0

Hi,

 

Scenario:

 

1. I am using Server login page to access my SAP GW service

2. I need username to display it in my next screen

 

Solution:

 

var oUserData = "";

var usernameService = "/sap/bc/ui2/start_up"; //Standard service

    var HttpRequest = "";

   HttpRequest = new XMLHttpRequest();

   HttpRequest.onreadystatechange = function() {

    if (HttpRequest.readyState == 4 && HttpRequest.status == 200) {

       oUserData = JSON.parse(xmlHttp.responseText);

       }

    };

    HttpRequest.open( "GET", usernameService, false );

var usernameFinal = oUserData.id


Thanks,


Karthik A

How to export UI5 development program from SAP WEB EDI to Eclipse

$
0
0

SAP WEB IDE has became a useful tool to develop Fiori UI5 APP program. But currently WEB IDE development environment requires SAP HANA cloud connector to be installed on either customer premise or SAP Hana cloud platform, which makes many customers and companies hard to build a WEB IDE development enviroment. As WEB IDE incorporates a lot of user-friendly and userful UI5 development features, many developers tend to use WEB IDE as a tool to generate a Fiori UI5 program then export the program to eclipse, then modify the program in eclipse, finally deploy the program in SAP ABAP server.

In this blog I will use north wind odata to generate a UI5 program in WEB IDE, export it to eclipse and then modify the program and run the UI5 program on Apache tomcat test server.

Prerequisities:  set up northwind odata destination on SAP Hana trial cloud platform link

 

1. create a new project in WEB IDE and choose SAP Fiori full screen Application

 

1.jpg

2. specify project name 'zproductdemo'

3. in data connection screen, choose 'service URL' and 'Northwind Odata service', specify /V3/northwind/northwind.svc in the input field

2.jpg

4 choose properties of products odata collection to be displayed in Main page and second page.

3.jpg

5. After the project is generated, export the project to a zip file

4.jpg

6. Open Eclipse and create empty UI5 application project with the name "zproductdemo"

5.jpg

7. import the UI5 program from the zip file and make sure into folder is 'zproductdemo/WebContent' and overwriting the existing file

7.jpg

8. After I import the project, open Component.js. Change serviceUrl as below and remove V2 at odatamodule method

serviceConfig: {

  name: "NorthwindModel",

  serviceUrl: "proxy/http/services.odata.org/V3/Northwind/Northwind.svc/"

  }

 

_initODataModel: function(sServiceUrl) {

  jQuery.sap.require("zproductdemo.util.messages");

  var oConfig = {

  metadataUrlParams: {},

  json: true,

  // loadMetadataAsync : true,

  defaultBindingMode: "TwoWay",

  defaultCountMode: "Inline",

  useBatch: true

  };

  var oModel = new sap.ui.model.odata.ODataModel(sServiceUrl, oConfig);

  oModel.attachRequestFailed(null, zproductdemo.util.messages.showErrorMessage);

  this.setModel(oModel);

  }

});

 

9. add the UI5 program to apache tomcat server and run it on server. On firefox you can get below products list UI5 APP

9.jpg

10.jpg

Then based on the WEB IDE UI5 program, you can develop further functions in eclipse.

 

I hope this blog is useful for you and Good Luck

How to use Hybrid Application Toolkit (HAT) and test the apps - Run

$
0
0

Introduction

 

This is the continuation of the blog started here.

 

This blog has been split in 3 parts:

LinkContent
Part1Introduction and some preliminary steps
Part2Preview apps on the emulator and on the device (iOS and Android)
Part3 (this page)Run apps on the emulator and on the device (iOS and Android)

 

In this part we are going to see how to run the mobile app we created in the first part of the blog on a mobile emulator/device. The first thing to do is to use HAT to deploy the app on the local machine and then push the app as stand-alone on the mobile emulator/device. We will see as well how to update the app and push it again to all the devices which have installed it. This will be done through HCPms.

 

 

 

Deploy the app on local HAT

At this moment the application is still inside SAP Web IDE. What we have seen in the previous part is that a link to the preview page is sent to the Companion App and this app takes care to show this preview as it was a stand-alone application. So far, only the Companion app is installed on the mobile device.

Now we'll see how to deploy the app from SAP Web IDE to your local machine (PC or Mac) so that you can push the generated .apk (Android) or .ipa (iOS) files to your device.

 

1) Open SAP Web IDE

 

2) Right click on the name of your project and choose Deploy --> Deploy to local Hybrid App Toolkit

12.jpg

 

3) The deployment starts: you can follow its status by the console window

 

4) At the end of the process click on OK

14.jpg

 

5) If you look in your user folder you will find a subfolder called SAPHybrid. Inside of it there will be another subfolder with the name of your project containing all the needed files for deployment of the app on the mobile device

15.jpg

 

6) Congratulations! You have deployed your app on your local HAT!

 

 

 

Run the app on the emulator

We'll firstly run the app on the Android emulator/iOS Simulator

 

1) Open SAP Web IDE

 

2) Right click on the index.html in your project and choose Run --> Run on --> (Android Emulator | iOS Simulator)

16.jpg

 

3) If you are running your app on the Android emulator you may get this further screen. Since we are just doing a test you can select Test Key and click on OK

17.jpg

 

4) The application which has been built by the deployment operation in the previous chapter is being pushed now to the emulator. You can check the status of the process in SAP Web IDE by enabling the console from the menu View --> Console. Once the application has been pushed onto your emulator, enter your SCN credentials and hit <ENTER>

18.jpg

 

5) We don't need a passcode for this exercise, so click on Disable Passcode

19.jpg

 

6) Click on Submit

20.jpg

 

7) Your application starts successfully

21.jpg

 

8) You can also click on one of the products to see its details

22.jpg

 

9) At this point we can't go any further with the emulator because it's not able to use the camera of our underlying hardware (well, Android emulator can but it needs to be properly configured!), so we prefer to use real devices for preview: let's go to the next chapter, then!

 

 

 

Run the app on the device

In order to run the app on a real device the steps are pretty the same as for the emulator so I won't report here all the screenshots again, but just the description of the steps.

 

1) Open SAP Web IDE

 

2) Right click on the index.html in your project and choose Run --> Run on --> (Android device | iOS device)

 

3) If you are running your app on the Android emulator you might get a further screen where you have to choose between using a Test Key or a Custom Key. Since we are just doing a test you can select Test Key and click on OK

 

4) The application which has been built by the deployment operation in the previous chapter is being pushed to the emulator. You can check the status of the process in SAP Web IDE by enabling the console from the menu View --> Console. Once the application has been pushed onto your emulator, enter your SCN credentials and hit <ENTER>

 

5) Click on Disable Passcode

 

6) Click on Submit

 

7) Your application starts successfully

 

8) You can also click on one of the products to see its details

 

9) Click on the Barcode Scanner button

 

10) The camera is invoked: you might be requested to allow the use of the camera on your device for this app. Please allow it and put the barcode you printed/downloaded in the first part of this blog in front of the camera: the barcode is automatically recognised

droid@screen-7.png

 

11) The product related to this code is found in the product list

droid@screen-8.png

 

12) Congratulations! You have successfully installed and executed the app on your device!

 

 

 

Update the app and re-deploy it on HCPms

Let's assume now that you want to change your app and push the changes to all the devices which have installed your application. How can you easily do it? The best thing to do is to change the app, re-deploy it on HCPms so that, after the deployment, all the devices/emulators running this app, will be informed that there is a new version of the app ready to be installed.

 

1) Open SAP Web IDE

 

2) In the Products project, open the file Master.view.xml by double clicking on it

 

3) Add the following line just after the one related to the Barcode Scanner button

 

<Button id="testbutton" icon="sap-icon://overflow"></Button>

 

24.jpg

 

4) Save the file

 

5) Test this new change in the layout by running the application in preview mode

25.jpg

 

6) Right click on the name of the project and choose Deploy --> Deploy to HCP Mobile Services

26.jpg

 

7) If required, enter again your SCN credentials

 

8) The Application ID field comes already populated, you just need to press Next

27.jpg

 

9) The package creation process might take time. When finished click on Browse to locate the zip file you need to upload to the server. The path to this file is also reported on this window

28.jpg

 

10) Locate the file and click on Open

29.jpg

 

11) Click on Deploy

30.jpg

 

12) The deployment phase takes some time too, depending on your upload speed. When finished click on Close

31.jpg

 

13) Now open the HCMms cockpit and click on the Applications tile

32.jpg

 

14) Click on the com.test.products application and then on Configure

33.jpg

 

15) Open the App Specific Settings tab and select the platforms which you want to deploy the new version for (in my case I'm doing it for both). Then click on Deploy

34.jpg

 

16) The new version is deployed. Now you need to open again the application on your device and after a certain time you should be prompted that a new version is available for this application. You can choose if you want to use this new version now or later. Choose Relaunch Now

35.jpg

 

17) The new application is launched

36.jpg

 

18) Congratulations! You have successfully updated your mobile app though HCPms!

How to use Hybrid Application Toolkit (HAT) and test the apps

$
0
0

Introduction

In this blog we are going to see how to use the Hybrid Application Toolkit for SAP Web IDE and how to mobilise and test the app generated with the development environment.

 

This blog has been split in 3 parts:

LinkContent
Part1 (this page)Introduction and some preliminary steps
Part2Preview apps on the emulator and on the device (iOS and Android)
Part3Run apps on the emulator and on the device (iOS and Android)

 

 

 

What is Hybrid Application Toolkit (HAT)

SAP Web IDE Hybrid App Toolkit Add-on enables developers to create and deploy Apache Cordova hybrid apps.

The Hybrid App Toolkit includes 3 components:

 

1) SAP Web IDE plugin which adds hybrid app development features to SAP Web IDE. These features include:


  • auto code completion and documentation for Cordova and Kapsel plugin APIs
  • hybrid project templates and code snippets
  • device configuration
  • previews on Companion app, and browsers
  • deploy to local, HANA Cloud, and SAP Mobile Platform environments
  • deploy and run app on target device

 

This plugin is currently available as an optional plugin for SAP Web IDE. This means that it's shipped with SAP Web IDE, you just need to enable it from the Optional Plugins section

 

2) Hybrid App Toolkit Connector which is a local server process that enables SAP Web IDE to connect to the local system's Cordova development environment and allows developers to create and manage a local Cordova project.

It can be downloaded from here

 

3) Companion application which is a native mobile application that runs on a mobile device or device emulator and enables a live preview of a Web application created with SAP Web IDE. It's included in the Hybrid App Toolkit package

 

 

 

How to get HAT

Hybrid Application Toolkit can be downloaded here directly from the SAP Store

 

 

 

How to install HAT

The installation guide for Hybrid Application Toolkit can be found here.

Beside this you can find a complete walkthrough for the installation on the Windows platform in this blog.

 

 

 

How to use HAT

There are many different ways to use HAT and in this blog we are going to see some of them. The steps listed here are pretty the same for Android and iOS platforms so I'm going to put side-by-side the screenshots for both platforms just for sake of comparison.

 

 

 

What is the main goal of this blog

The main goal of this blog is to show you how to

  • develop a simple SAPUI5 Master-Detail application from one of the standard templates, in SAP Web IDE. This app takes data from a SAP HANA Cloud destination, which we are going to define, pointing to the service http://sapes1.sapdevcenter.com:8080/sap/opu/odata/IWBEP/GWDEMO for getting the Sales Order Products information
  • add some custom code to this app to extend the search bar functionality:
    • add a new button next to the search field of Master View to scan the product barcode
    • search for its information in the backend. For this the Kapsel Barcode Scanner Plugin will be used
  • when the app is ready, mobilise it using the Hybrid Application Toolkit and the trial HCPms system
  • test it using various methods like,
    • Test as a Web app
    • Run with Cordova Façade in the browser
    • Preview with Companion App on
      • Emulator
      • Android Device
    • Run on
      • Emulator
      • Device
    • Deploy to HCPms and then on Device

 

 

 

Preliminary steps

  • Check the prerequisites
  • Setup the required destination
  • Enable HAT plugin in SAP Web IDE and check its connectivity
  • Create a new app in the HCPms administration console
  • Create a QR-Code of a product
  • Create an hybrid application with SAP Web IDE

 

 

Check the prerequisites

Ensure all the prerequisites are met.

  • SAP Web IDE (Register at SAP HANA Cloud Platform to get the development environment)
  • Hybrid Application Toolkit downloadable from here
  • An HCPms account configurable as described here
  • Valid user for ES1. Procedure to get access information is described here
  • An Android/iOS device to test the application. To connect an Android device to the PC to test your applications you need to install the appropriate USB driver. Follow this link for the detailed steps.

 

Note: A mobile device simulator can be used only to add contacts, but for Barcode Scanning a real Mobile device is needed. For using the Device Emulators and for other installation prerequisites regarding SAP Web IDE Hybrid App Toolkit Add-on please refer to the SAP Web IDE Hybrid App Toolkit Add-on | SCN.

 

 

Setup the required destination

1) Login to your HANA Trial account

 

2) Navigate to Destinations --> New Destination

 

3) Set up a destination named "es1" in the following way:

 

ParameterValue
Namees1
Descriptiones1
TypeHTTP
URLhttp://sapes1.sapdevcenter.com:8080
ProxyTypeInternet
CloudConnectorVersion2
AuthenticationNoAuthentication

 

and add these additional properties

 

PropertyValue
WebIDEUsageodata_abap
WebIDEEnabledtrue
WebIDESystemes1

as shown in this screen shot

01.jpg

4) Save the configuration

 

 

Start the HAT Connector

To allow SAP Web IDE to interact with HAT add-on components on your local machine over HTTPS protocol, start the HAT Connector


Windows platforms

1) With Windows Explorer on your machine, go to the folder where the HAT tool is installed


2) Double click on the run.cmd program


3) At the prompt enter your keystore password (which you defined already during the HAT setup procedure)

 

4) The HAT Connector starts listening for requests from SAP Web IDE

 

2015-08-04_18-10-12.jpg


Mac platforms

1) Open a terminal window on your Mac

 

2) Go inside the folder where the HAT tool is installed

 

3) Type the command: ./run.sh

 

4) At the prompt enter your keystore password (which you defined already during the HAT setup procedure)

 

5) The HAT Connector starts listening for requests from SAP Web IDE

02.jpg

 

 

Enable HAT plugin in SAP Web IDE and check its connectivity

Login to SAP Web IDE and ensure that HAT plugin is enabled. Verify that the connection is up and running.

 

1) Open SAP Web IDE

 

2) Go to Tools --> Preferences

 

3) Select Plugins --> Optional Plugins

 

4) Enable the Hybrid App Toolkit plugin

03.jpg

 

5) Save the configuration

 

6) Choose the Hybrid Application Toolkit item on the left side

 

7) Click on Test Connection

 

8) Ensure that the connection is up and running

04.jpg

 

 

Create a new app in the HCPms administration console

Login to HCPms and create a new application.

 

1) Login to https://hcpmsadmin-<your_account>.dispatcher.hanatrial.ondemand.com where <your_account> is the account you received when registering to the HANA Trial Landscape

 

2) Click on the Applications tile

05.jpg

 

3) Click on the "+" sign

06.jpg

 

4) Enter the following values and save the settings

ParameterValue
Application IDcom.test.products
Version1.0 (default)
NameProducts
TypeHybrid
DescriptionSales Order Products
VendorSAP

07.jpg

 

5) Keeping the application selected on the left side click on Configure

08.jpg

 

6) Select the Backend tab and enter the following values. Leave all the other values as proposed and click on Save

ParameterValue
Backend URLhttp://sapes1.sapdevcenter.com:8080/sap/opu/odata/IWBEP/GWDEMO
Authentication TypeNo Authentication
Proxy TypeInternet

09.jpg

 

7) Test the connection by pinging it, you should get a successful result

10.jpg

 

 

Create a QR-Code of a product

Let's generate a QR-Code for at least one product so that we can test our app.

 

1) Go to http://www.barcode-generator.org/

 

2) Select the Text tab, provide for example the code "HT-1002" as plain text and click on Create QR Code

11.jpg

 

3) The code is generated: you can either download or print this code in order to be used later in this blog.

 

 

Create an hybrid application with SAP Web IDE

We are going to create now the hybrid application that we'll use during this exercise.

 

1) Open SAP Web IDE

 

2) Choose File --> New --> Project from template

 

3) Choose SAPUI5 Master Detail Kapsel Application and click on Next

 

4) Enter a project name (i.e. "Products") and click on Next

 

5) Select Service Catalog on the left side, choose the destination "es1" you have created previously, in the search bar enter "gwd", select the GWDEMO service and click on Next

15.jpg

6) Eventually, enter the credentials for the "es1" service

 

7) Enter the following information and click on Next

ParameterValue
Project Namespacecom.test.products
TitleProducts
OData CollectionProductCollection
Search FieldProductID
TitleProduct
Item TitleProductName
Numeric AttributeUnitPrice
Unit AttributeCurrencyCode
Additional Attribute 1ProductCategory
Additional Attribute 2ProductDepth

16.jpg

8) Click on Finish

 

9) After the project has been created, open the view folder and double click on the Master.view.xml file. The file is opened in the editor. Right click in the editor pane and choose Beautify

18.jpg

 

10) Paste the following code just after the closing of the "contentMiddle" tag and save the file

 

<contentRight>  <Button id="barcodebutton" icon="sap-icon://bar-code" press="onBarcodeScan"></Button></contentRight>

 

19.jpg

 

11) Open the Master.controller.js file, paste the following code just after the "onInit" function and save the file

 

  onBarcodeScan: function() {  var that = this;  var code = "";  if (!cordova.plugins.barcodeScanner) {  alert("Barcode scanning not supported");  return;  }  cordova.plugins.barcodeScanner.scan(  function(result) {  code = result.text;  that.getView().byId("searchField").setValue(code);  that.onSearch();  },  function(error) {  alert("Scan failed: " + error);  }  );  },

 

20.jpg

 

12) Right click on the name of the project and choose Project Settings

 

13) Click on Device Configuration and set the parameters in the following way

ParameterValue
App NameProducts
App IDcom.test.products
DescriptionSales Order Products
Version1.0.0
Local Build OptionsRelease Mode
PlatformAndroid or iOS or both
Kapsel PluginsLogon Manager, App Update, Barcode Scanner
HCPms/SMPHCPms
HCPms Hosthcpms-<your_account>.hanatrial.ondemand.com (where <your_account> is the one you got on the Trial Landscape

 

NOTE: regarding the Platform parameter, you have to choose the platform you are going to test your app for. If you have a Windows machine you can only use Android as deployment platform. If you have a Mac, instead, you can use both platform for testing and running mobile applications. In my case, since I'm using a Mac and I want to show you the differences between the two platforms I'm going to select both!

 

22.jpg

 

14) Congratulations! You have created your hybrid application. This is the app we are going to use for our tests in this exercise.

 

This blog now will continue with a second part where you will learn about all the different ways to test and run an hybrid application with HAT.

How to use Hybrid Application Toolkit (HAT) and test the apps - Preview

$
0
0

Introduction

 

This is the continuation of the blog started here.

 

This blog has been split in 3 parts:

LinkContent
Part1Introduction and some preliminary steps
Part2 (this page)Preview apps on the emulator and on the device (iOS and Android)
Part3Run apps on the emulator and on the device (iOS and Android)

 

In this part we are going to see how to preview the mobile app we created in the first part of the blog on a mobile emulator/device.

The preview operation will be executed in SAP Web IDE by installing on the emulator/device a special app called Companion App. This is a special app, as I said, because it just takes the preview link passed from the SAP Web IDE and displays it in its container. This special app, of course, in order to be as much generic as possible to be able to display all the possible Kapsel applications created with SAP Web IDE, contains all the available Cordova and Kapsel plugins. For this reason its generation might take some time. However only the first time it needs to be installed on the device. You can understand how quickly you can preview your app when you are developing it.

We will see also how to preview the app directly in the SAP Web IDE preview using the Façade technology.


So, three will be the preview modes we are going to illustrate here:

 

  • Preview using Cordova Façade in Browser
  • Preview using Companion App on the emulator
  • Preview using Companion App on the device

 

 

Preview using Cordova Façade in Browser

The first preview you can get of the new app is by executing it directly in the Web Browser using a sort of web emulation for the Cordova / Kapsel plugins named Façade. This technology allows you to use all the native devices of your local machine as they were part of the mobile device. You can use for example the webcam of your PC as it was the camera of your mobile device.

By right clicking on the project name in SAP Web IDE and accessing to Project Settings, you can open the Façade configuration where you can change some of the parameters related to this kind of emulation. You can assign some values to the Accelerometer for example or to the Compass, you can also configure the emulation for the geo-location feature.

In this exercise we are just going to use the camera so non need to change any of these parameters.

 

1) Open SAP Web IDE

 

2) Go to Tools --> Preferences

 

3) Select Hybrid Application Toolkit and ensure that the checkbox Cordova Façade Preview is enabled

2015-08-18_13-01-36.jpg

 

4) Click on Save if you made any change

 

5) Select the index.html file in your project and click on the Run button on the toolbar

2015-08-18_14-48-55.jpg

 

6) Click on the Barcode Scan button (you may be requested to allow the use of the webcam on your laptop if you have one, please allow it)

2015-08-18_14-49-13.jpg

 

7) Put the barcode you generated in the first part of this blog in front of the camera

2015-08-18_14-52-36.jpg

 

8) As soon the Barcode Scanner plugin identifies the code, this is searched in the search box and the found product is displayed

2015-08-18_14-54-17.jpg

 

9) Congratulations! You have previewed your app with Cordova Façade

 

 

 

Preview using Companion App on the emulator

We'll see here how to preview the app directly on the Android emulator/iOS Simulator.

 

1) Open SAP Web IDE

 

2) Right click on the index.html in your project and choose Run --> Preview on --> (Android Emulator | iOS Simulator)

01.jpg

 

3) After some time the Companion App included in the HAT folder, built at the time of the HAT setup, is automatically pushed to the emulator. You can check the status of the process in SAP Web IDE by enabling the console from the menu View --> Console. Once the application has been pushed onto your emulator, enter your SCN credentials and hit <ENTER>

02.jpg

 

4) We don't need a passcode for this exercise, so click on Disable Passcode

03.jpg

5) Click on Submit

04.jpg

 

6) Enter your credentials for the ES1 system

05.jpg

 

7) Your application starts successfully

06.jpg

 

8) At this point we can't go any further with the emulator because it's not able to use the camera of our underlying hardware (well, Android emulator can, but it needs to be properly configured!), so we prefer to use real devices for preview: let's go to the next chapter, then!

 

 

 

Preview using Companion App on the device

In order to preview the app on a real device the steps are pretty the same as for the emulator so I won't report here the screenshots, but just the description of the steps.

 

1) Open SAP Web IDE

 

2) Right click on the index.html in your project and choose Run --> Preview on --> (Android Device | iOS Device)

11.jpg

 

3) After some time the Companion App included in the HAT folder, built at the time of the HAT setup, is automatically pushed to the device. You can check the status of the process in SAP Web IDE by enabling the console from the menu View --> Console. Once the application has been pushed onto your device, enter your SCN credentials and hit <ENTER>

 

4) Click on Disable Passcode

 

5) Click on Submit

 

6) Enter your credentials for the ES1 system

 

7) Your application starts successfully. Since you are now on a real device you can click on the Barcode Scan button

droid@screen-6.png

 

8) The camera is invoked: you might be requested to allow the use of the camera on your device for this app. Please allow it and put the code you printed/downloaded in the first part of this blog in front of the camera: the code is automatically recognised

droid@screen-7.png

 

9) The product related to the code is found in the product list

droid@screen-8.png

 

10) Congratulations! You have successfully previewed the app on your device!

 

Let's continue with the final part of this blog!

SAP Fiori & SAP Business Workflow - Generic Decision App

$
0
0

Hy everybody,

 

i'm working alot with SAP Fiori Applications (SAP UI5) and created a simple application that integrates with SAP Business Workflow.

 

I wanted to create a application, which allows a simple user decision kind of a question with yes/no answers. I ended up in creating a customizable application wich dinamicly creates the selection options and the to be answered question(s).

 

Now i would like to share quickly what i've been doing for this application & share the experience i've made.

 

  1. Created a simple 1 step workflow - without any start events or something -> I wrote a simple 20line of code report to start a workflow instance from sap gui transaction.
  2. Created a customizing table with scenario information to determine asked question and answer possibilities.
  3. Created a  NW Gateway Service to read the customizing tables & to prcoess workflow items.
  4. Checked everything with SWIA to look at workitem container and other elements.

 

  • I wanted to keep everything as simple as possible and with SAP Fiori and SAP Business Workflow it was really simple to achieve a simple solution.
  • The SAP UI5 framework is quite stable and after getting into it it's nice to work with it.
  • SAP Business Workflow will be my choice if i have to create business processes wich are supported by a workflow engine.
  • Programming of SAP UI5 & ABAP in Eclipse works quite nice.

 

How could this app be extended (What i did not implement)

  • User Assignement - I did not provide a way to select the next user/org. unit. I've implemented many rules FM's and other logic to determine a user or org. unit therefore it was not a key learning i wanted to have and therefore i skipped it.
  • Attachments - I did not implement a Attachment List or any other link to a document management system. I've implemented several ICF services & multiple SAP UI5 Applications already including a document/attachment handling because of this, i skipped it in this application.
  • Business Data - I did not implemenet a kind of generic Business Data Visualization Area to display business data in a generic way. Altough with SAP UI5 and NW GW this can be easily achieved.

 

The end result is a simple, customizable application for generic decisions that does not require huge development efforts and that will be used in a future SAP project at our enterprise.


I wish you all a nice day.


Regards,

Michael

Create reusable Custom Tile

$
0
0

Abstract


SAPUI5 library provides many controls but sometimes we may need to have our own custom controls which can be reusable. Here, I am trying to explain how we can create a custom Tile which can be reused in our application in different pages like standard control.


What we want at the end?

                 I have included table in custom tile. We can put any standard control instead of table like Pie chart, Button etc.

CustomTile.JPG


How can we achieve?


create custom tile extending generic tile : TableTile.js

hierarchy.JPG

 

jQuery.sap.declare("sap.ui.test.custTile.control.TableTile");
jQuery.sap.require("sap.suite.ui.commons.GenericTile");
sap.suite.ui.commons.GenericTile.extend("sap.ui.test.custTile.control.TableTile", {
metadata :{},
init : function() {  sap.suite.ui.commons.GenericTile.prototype.init.apply(this);
this.isCreate = false;  },
create : function() {this.oTileContent = new sap.suite.ui.commons.TileContent({size : "L"});  this.otxt = new sap.m.Text({text : "Business SLA"}).addStyleClass("tileTitle");  this.oTable = new sap.m.Table("tab",{  visibleRowCount: 5,  firstVisibleRow: 5,  }).addStyleClass("tbcell");  var oColumn1 = new sap.m.Column({  width: "70%",  textAlign: "Center",  header : new sap.m.Text({text:"KPI"}).addStyleClass("tbcell")  }).setStyleClass("tbcell");  var oColumn2 = new sap.m.Column({  width: "30%",  header : new sap.m.Text({text:"Value"}).addStyleClass("tbcell")  }).setStyleClass("tbcell");  this.oTable.addColumn(oColumn1);  this.oTable.addColumn(oColumn2);  this.oTable.addStyleClass("tbTile2");  var oTableItemTemp = new sap.m.ColumnListItem({cells:[new sap.m.Label({text: "{KPI}"}) ,                                                       new sap.m.Label({text: "{Value}"})                                  ]}).addStyleClass("tbcell");  this.oTable.bindItems("/OV",oTableItemTemp);  this.oTable.setModel(new sap.ui.model.json.JSONModel());
this.oTileContent.setContent(this.oTable);     this.addTileContent(this.oTileContent);      this.isCreate = true;  }  },  onAfterRendering : function() {  this.isCreate = true;
}  }

Here,I have not created property for custom tile but we can add properties to custom control in metadata section.I have created Table in custom Tile instead of that we can add any control like chart,button etc. to Create method.


style.css

.tileTitle{  font-size : large!important;
}
.tbcell>.sapMListTblCell{       padding : 0rem !important;       padding-left:15px!important;     
}
.tbTile2{    margin-top: 20px!important;        border-style: ridge;        background-color: rgb(220, 235, 239);
}


How you consume in XML view?

custTile.view.xml

 

<core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:tiles="sap.ui.test.custTile.control"  controllerName="custTile.view.ctile" xmlns:suite="sap.suite.ui.commons" xmlns:html="http://www.w3.org/1999/xhtml">  <Page title="Title">  <content>     <Panel>  <tiles:TableTile id="TBTile2"  size="L" class="SPPanel">  </tiles:TableTile>  </Panel>  </content>  </Page></core:View>

so like above we can use <tiles:TableTile> by including own namespace sap.ui.test.custTile.control in any other page of our application.

 

Regards,

Zalak

l



How to make a swipe-to-navigate UI5 application

$
0
0

Intro

 

After digging around in the UI5 examples and code, I was unable to find a mobile application that supported swipe-to-navigate pages, and I needed some for a project.

 

Swipe to navigate means, you use your finger to navigate between pages by swiping left or right: left will take you back, right will take you forward. Turns out, it wasn’t very hard to build. Here’s a description what I did. Please be nice, this is my first blog and I hardly consider myself a writer. Also if this stuff comes with the framework, feel free to laugh at me in the comments. I find it difficult to navigate the UI5 documentation

 

Have a peek at the GitHub repository, it contains all the code here so you can try it for yourself. It’s not a bad base to start with either if you want to build an app. I'm packaging this up with PhoneGap when I'm done.

 

To give you on idea, here's a visual of what we’re making:

 

 

What’s needed

 

We need four things:

 

  • Swipe events, so the app can detect when someone is putting their fingers on the screen and moving them in a particular direction
  • Slide animations. The slide animation that comes with UI5 out-of-the-box is only right-to-left, so we need one going in the other direction.
  • A way to identify the next or previous page
  • Combining everything by attaching the swipe event and animation to an app.to call.

 

And of course we need an application to build this into. I’m using grunt, bower and a Component to bootstrap an application. My abbreviated project’s code structure looks like this:

 

root
|-- package.json
|-- bower.json
|+- src
|   |-- Component.js
|   |-- index.html
|   |+- controller
|   |   |-- App.controller.js
|   |+- model
|   |+- views
|   |   |-- App.view.xml
|   |   |-- Page1.view.xml
|   |   |-- Page2.view.xml
|   |   |-- Page3.view.xml

The code that matters for this is all in Component.js, App.controller.js and App.view.xml.

 

For full code, please refer to the Git repository (above).

 

Swipe events

 

Conveniently, UI5 provides those for us, so: score. The events swipe-left and swipe-right are perfect for this. On non-mobile devices they’re also triggered by holding down the mouse button and dragging so that’s a bonus.

 

Swipe Animations

 

The page animations in UI5 are declared in sap.m.NavContainer (API document). We could create a fully custom one, but we can also realize that swiping from left-to-right is identical to right-to-left —- only in reverse!

This means, lucky us, that we can use the default slide animation and flip it. Here’s the code. You’ll notice it has a to and a back component.

 

Component.js (github)

 

init: function() {    //attach animations    this._setUpSwipeAnimations();    //other things    //call parent method    UIComponent.prototype.init.call(this, arguments);
},
_setUpSwipeAnimations: function() {    var slide = NavContainer.transitions.slide;    //technically, swiping from left to right just means    //reversing the "to/back functions" of the existing slide animation    NavContainer.transitions["slide-left"] = slide;    NavContainer.transitions["slide-right"] = {        to: slide.back,        back: slide.to    };
}

 

This lives in Component.js. The code takes the default slide animation, and re-attaches it to the NavContainer, renamed as slide-left. It is then added again as slide-right, only the to and back parts are switched. That is all!

 

By adding this code in the init portion of the Component, and before the call the parent init method, it’s ready for action by the time the app itself is boostrapped.

 

Identifying pages

 

I like to keep things dynamic. Thankfully, by keeping the pages` class name and ID similar, this can be achieved with relatively little code:

 

Page1.view.xml (github)

 

<Page backgroundDesign="Solid" class="swipe-page">

By adding the same classname to all pages, the events can be attached to just the HTML bits that we like. In this case, all my pages have the class swipe-page attached to them.

 

The last thing is adding the pages to the app in the right order in App view:

 

App.view.xml (github)

 

<mvc:View     xmlns:mvc="sap.ui.core.mvc"    xmlns:core="sap.ui.core"    xmlns="sap.m"    controllerName="holcim.swipedemo.controller.App"    displayBlock="true"    resourceBundleName="holcim.swipedemo.i18n.i18n"    resourceBundleAlias="i18n"    id="swipedemo-view">    <Shell>        <App id="swipedemo-app">          <mvc:XMLView id="swipe-page1" viewName="holcim.swipedemo.view.Page1" />          <mvc:XMLView id="swipe-page2" viewName="holcim.swipedemo.view.Page2" />          <mvc:XMLView id="swipe-page3" viewName="holcim.swipedemo.view.Page3" />        </App>    </Shell></mvc:View>

 

Observe the multitude of ID’s here: the main view is called swipedemo-view, the app is called swipedemo-app and all the pages have numbered ID’s: swipe-page1 to .. however many pages you have. This is to make retrieving all parts of the application easier.

 

This way we can determine the next page and the previous page.

 

Putting it together

 

The best place to link everything together is in the initialization phase of the App controller. This way the animations are ready to be used, and the code belonging to swiping the app is actually inside the correct controller.

 

App.controller.js (github)

 

return Controller.extend("holcim.swipedemo.controller.App", {    onInit: function() {        this._setupTransitions();    },    _setupTransitions: function() {        $('body').on('swipeleft', '.swipe-page', function(e) {            this._navigate(e.currentTarget.parentNode.id, 'left');        }.bind(this));        $('body').on('swiperight', '.swipe-page', function(e) {            this._navigate(e.currentTarget.parentNode.id, 'right');        }.bind(this));    },    _navigate: function(id, direction) {        var newId, match, add;        match = id.match(/.*swipe-page([0-9]{1,}$)/);        add = (direction === 'left') ? 1 : -1        if (match && match.length > 1) {            newId = this.createId('swipe-page' + (Number(match[1]) + add));            this.byId('swipedemo-app').to(newId, 'slide-' + direction);        }    }
});

 

Let’s break that down. The first interesting block of code is this one:

 

$('body').on('swipeleft', '.swipe-page', function(e) {    this._navigate(e.currentTarget.parentNode.id, 'left');
}.bind(this));

 

This attached a handler to the body of the page for the swipeleft event, limited to class swipe-page. Without the class addition, this triggers on elements overlaying the page itself as well like header elements, lists, tables, forms and anything else you might have on there. By filtering on this class, the event’s currentTarget always contains a page. Observe that the ID was actually located in the view that the page is in, hence the currenTarget.parentNode.

 

The same code is attached to the swiperight event.

 

Second code block is the function that does the navigating:

 

_navigate: function(id, direction) {    var newId, match, add;    match = id.match(/.*swipe-page([0-9]{1,}$)/);    add = (direction === 'left') ? 1 : -1    if (match && match.length > 1) {        newId = this.createId('swipe-page' + (Number(match[1]) + add));        this.byId('swipedemo-app').to(newId, 'slide-' + direction);    }
}

 

This takes the current target’s ID, which is something like __xmlview0--swipe-page1. To get the right page number, all we need is to get the number at the end of the string, here collected in regex array match, and either add 1 or subtract 1, depending on the direction of the swipe, and create an ID using the appropriately named method.

 

Thankfully, it doesn’t matter if the page you’re trying to navigate to doesn’t exist. UI5 will not throw an error, although you might see a warning in the console.

 

That's it, really. Once again, see the gif at the top for a quick visual, or check the git repo for the details.

 

Cheers

Autocomplete formatted address via Google Places API

$
0
0

Formatted addresses which are validated by Google or Veda database provide more accurate customer address information to users. If addresses of millions users or customers in an IT databases are unformatted or not uniformed, the address mess will make IT business users difficult to make statistics and retrieve valuable information and increase their administration effort. Furthermore google formatted address contains Geocode –latitude and longitude which can identify exact location and show the location in the google maps. Therefore when users are typing address information on an UI5 web page, it is better that we populate suggested address list from Google Places API to the input field and let the user choose right formatted address.


How to achieve this in SAPUI5?

Technically there are two ways in SAP UI5 to achieve this function:

    1. Via SAP NetWeaver gateway. When a user is typing address at the input field, a OData call is generated and this trigger Http client service class to call Google Places API in the NetWeaver gateway, then retrieve the formatted address list, then send the OData from SAP Net Weaver gateway to UI5 page and display them in the address input field

    2. Call Google Place API directly via Javascripts Ajax, After the Json file containing formatted address is received from Google API, these addresses will be displayed in the address input field.

In this blog I will explain how to use the second way to fulfill auto complete address function.


How to call Google Place API directly via Javascripts Ajax

I referred to below UI5 blog to know how to call open API via Javacripts Ajam

http://scn.sap.com/community/developer-center/front-end/blog/2013/08/02/creating-sapui5-applications-based-on-public-json-apis-or-web-services

In the case, the URL which will be used to call Google Places API is as below:

var url = "proxy/http/maps.googleapis.com/maps/api/geocode/json?address=" + sTerm + "&sensor=false"


Walk Through

I created a UI5 project at Eclipse and followed below steps

   1. At an XML view, eg businesspartner.view.xml, create a address input field with suggest items and add a event listener function ”onAddressTyped’” to this field

 

code1.png

 

   2. At the function ”onAddressTyped’” of Controller Javascript, eg businesspartner.controller.js,

    1. call google place API via UI5 javascripts and return a Json file with formatted addresses
    2. Set the Json file into OData Model
    3. Bind formatted addresses in OData Model with suggest items of the address input field

code2.jpg

If I run the UI5 program on the test server and type more than 8 charactor at address input field, I can get suggested address list from Google Places API.

auto.jpg

Then users can choose a formatted address which he/she want to type in. I hope this can help you to call google place API and build a function with formatted address information.

Extending a SAPUI5 control

$
0
0

Sometimes SAPUI5 controls does not support a specific use case you run into. For that, an extensibility functionality is provided for all of SAPUI5’s controls.

 

Extending a control or even creating a new one is a simple task, which will be explained in this step-by-step post. This post will extend the sap.m.Select control, creating an option to add new items to it at runtime. It is divided in the following tasks:

  1. Create a javascript file to extend the control
  2. Add new properties and events to control
  3. Check standard control source code in OpenUI5
  4. Extend standard control’s function onBeforeRendering + init
  5. Create function to handle new option
  6. Extend standard control’s function onSelectionChange
  7. Add control to the view and test it

 

If you are on a hurry, you can look at the code from this sample at https://github.com/tiagoquaini/sapui5-select-extension and check the behavior of the control at http://output.jsbin.com/horadi/1.

 

Feel free to use and enhance this control if it fits your needs .

 

The only requirement to follow this post is having a running SAPUI5 project. If you have not already set up your project, please find helpful content here: http://help.sap.com/saphelp_hanaplatform/helpdata/en/da/0c8ca95ba447f2970cdba2aef7639b/content.htm

Create a javascript file to extend the control

Start creating a new js file which will be the extension control:

1.png

 

The name of our control will be Select.js.

2.png

 

Add the following code to the control:

jQuery.sap.declare("<your_project_path>.<your_folder>.Select");
jQuery.sap.require(
"sap.m.Select");
jQuery.sap.require("sap.m.SelectRenderer");

 

sap.m.Select.extend("<your_project_path>.<your_folder>.Select", {

     renderer: "sap.m.SelectRenderer"

});


The code above is declaring the control’s name (line 1), requiring the standard controls which will be extended (lines 2 and 3), executing extend function from parent control, and defining the file that will be the renderer.


On this example the renderer will not be extended and the standard will be used.

 

Until now no changes were made to the control. It would behave exactly like the standard control if instantiated.

Add new properties and events to control

Now create the new properties and events this control needs. This can be done by simply creating a metadata object:


metadata: {

      properties: {

                 "addValueEnabled": {

              type: "boolean",

              defaultValue: true

         }

      },

      events: {

         "newValueCreated": {}

      }

}


The addValueEnabled property will be responsible for enabling the new “add” feature. By default it is set to true, and if the user sets it as false the control will behave exactly like the standard sap.m.Select.

 

In addition, the newValueCreated event will be fired when the user creates a new option.

 

Also, as a good practice, we are going to create two new constants bellow the metadata object. They will be responsible for the add option’s text and key.


ADD_OPTION_KEY: "__addNewValue",

ADD_OPTION_TEXT: "Add..."


Check standard control’s source code on OpenUI5 git

Most of the times, extending a control requires extending also some of its functions. For that, it is helpful knowing the standard control’s source code.

 

The best way to have access to an UI5 control is taking a look at the OpenUI5 git repository.

3.png

 

Extend sap.m.Select standard functions

Looking through the standard control’s source code, it is possible to figure out that some functions need to be extended to support our new feature.

 

The onBeforeRendering function will place the main code of this extension, where the new option named “Add” will be created and inserted to the select. Besides, the init function will hold a control's verification property.

 

init: function() {

           // define variable for control initial loading handling

           this._bInitialLoading = true;

    

     // execute standard control method

     sap.m.Select.prototype.init.apply(this, arguments);

},

    

onBeforeRendering: function() {

      if (this.getAddValueEnabled()) {

 

                // check if "add..." option does not exist yet. if so, create it

                if (!this.getItemByKey(this.ADD_OPTION_KEY)) {

              

           // create add value item and add it to select

           var oItem = new sap.ui.core.Item({

                          key: this.ADD_OPTION_KEY,

             text: this.ADD_OPTION_TEXT

           });

   

                      this.insertItem(oItem, 0);

        }

 

        // set item index if more than one option and initial loading

                if (this._bInitialLoading && this.getItems().length > 1) {

                     this.setSelectedItem(this.getItems()[1]);

 

         

           // the “onBeforeRendering” method will only be executed again on new option creation

           // further verifications are not necessary

                     this._bInitialLoading = false;

        }

      }

          

            // execute standard control method

      sap.m.Select.prototype.onBeforeRendering.apply(this, arguments);

}

 

First it is verified whether the add value feature is enabled in the control. After that, it is verified whether the “Add” option is already created. If not, the “Add” item is created and inserted to the select options. This verification will avoid the creation of multiple “Add” options, because the “onBeforeRendering” function is called always when a new option is created. Note that its key and text are the constants created in step 2.

 

The next validation checks if the control is in its initial load and if it has any options. In case both sentences are true, the second item (first item after the custom “Add” option) is selected.

 

Note that on both functions, the standard control’s apply function is being called. This function executes the standard behavior of the control, meaning that both custom and standard content will be executed.

 

Handling new option

Now it is necessary to create a function to handle the “Add” option. It is a simple item on the select, but will have an special treatment when selected. Instead of just displaying it, a dialog with an input will be shown for the user to add the new value.

 

It will be necessary to extend the onSelectionChange function from parent control. This function is called when the select value changes and will be enhanced to check whether the selected item is the “Add” option. If the add option is selected a dialog is created with an input to allow the user to enter the new value.


onSelectionChange: function(oControlEvent) {

     // get selected item

          var oItem = oControlEvent.getParameter("selectedItem");

          

          // check if the add value option is enabled and if the key is the 'add option' key

          if (this.getAddValueEnabled() && oItem.getKey() === this.ADD_OPTION_KEY) {

                this._createNewOptionDialog();

     }

         

     // execute standard control method

     sap.m.Select.prototype.onSelectionChange.apply(this, arguments);

},

    

_createNewOptionDialog: function() {

          // create dialog with input field

          var that = this;

     var oDialog = new sap.m.Dialog({

          title: 'Add value',

          content: new sap.m.Input({

               id: 'idNewValueInput'

          }),

          beginButton: new sap.m.Button({

               text: 'Add',

               press: function() {

                    that._handleNewOption();

                    oDialog.close();

               }

          }),

          afterClose: function() {

               oDialog.destroy();

          }

     });

     oDialog.open();

},

    

_handleNewOption: function() {

     // get new option value

          var oInput = sap.ui.getCore().byId("idNewValueInput");

          var sNewValue = oInput.getValue();

    

     // create new item to be added in select

     var oItem = new sap.ui.core.Item({

              key: sNewValue,

       text: sNewValue

     });

    

     // add item to select and set it as selected

     this.addItem(oItem);

     this.setSelectedItem(oItem);

                

     // fire an event in case the parent object needs to handle this

     this.fireNewValueCreated({

          value: sNewValue

     });

}


When the dialog create button is pressed, the function executed creates a new item, adds it to the select and fires the custom event newValueCreated sending the value as a parameter.

 

Add control to the view

Using an extension control is as simple as using any other SAPUI5 control.


<mvc:View

      xmlns:mvc="sap.ui.core.mvc"

      xmlns="sap.m"

      xmlns:l="sap.ui.layout"

      xmlns:core="sap.ui.core"

      xmlns:custom="sapui5-control-extension-demo.controls"

      controllerName="sapui5-control-extension-demo.main"

      xmlns:html="http://www.w3.org/1999/xhtml">

      <Pagetitle="Control extension">

            <content>

                  <l:VerticalLayoutwidth="100%">

                        <l:content>

                             <Labeltext="Extension Control"/>

                             <custom:Select

                    width="50%"

                    newValueCreated="handleNewValue"

                    items="{/}">

                                   <core:Item

                       key="{CountryId}"

                       text="{Name}"/>

                             </custom:Select>

                        </l:content>

                  </l:VerticalLayout>

            </content>

      </Page>

</mvc:View>


It is only necessary to create a new xmlns with the path to the control (or require the control, in case of a JS view) and add it to the view.

 

The final result is the following: Live demo

4.PNG

5.PNG

6.PNG

Upcoming SAPUI5 CodeJam in Vienna 2015

$
0
0

CodeJam_Date_4.jpg

On Thursday, November 5th, 2015 from 10:00 Am to 04:00 PM (CEST) there will be a SAP CodeJam in Vienna.

The topic will be SAPUI5 development. Both beginners and advanced developers are welcomed!


The SAP Expert, Denise Nepraunig will be available for all your questions. She will be valuable help for all first

SAPUI5 programming attempts as well as for all further issues.


In a relaxed and comfortable atmosphere you can dive into new technology, meet new people and have fun with coding.

 

Be part of the first SAPUI5 CodeJam in Vienna and experience it live with us!

Registration page: SAP CodeJam Vienna Registration, 1090 Wien | Eventbrite

 

Here you can follow all recent news about the event:

Cadaxo | Facebook

 

Best regards,

Ana

SAPUI5 – Cloud Connector

$
0
0

Login on https://account.hanatrial.ondemand.com


Go to HTML5 Applications and click on application

 

1.png

 

 

 

Then run Cloud connector Installed in your machine

Check if Cloud Connector is running or not using services.msc command and search for SAP  HANA.

After that open Connector URL : https://localhost:8443/

 

 

2.png

 

 

 

This should be Green and working

 

3.png

 

This should be in connected status.

 

Download SAP Cloud Connector to use Service we created.


Prerequisite: Services which you want to use should already be there.

https://help.hana.ondemand.com/help/frameset.htm?e6c7616abb5710148cfcf3e75d96d596.html

 

 

Steps of Installing HANA Cloud

http://hcp.sap.com/developers/TutorialCatalog/con100_1_setting_up_cloud_connector.html

Hana Cloud Administrator UID/Pass : Administrator/*******

 

 

Login to your HANA Cloud Connector:

 

 

4.png

 

 

Select the system which you want here we are using SAP Gateway because our Service is on Gateway SEGW.

 

5.png

 

Set Protocol HTTP/HTTPS.

 

6.png

 

Click on Add button and add Virtual Port and Internal Host names.

To minimize the confusion put Virtual and Internal Host as same

 

7.png

 

Provide the URL Path for Service you created.

 

8.png

 

No other things needs to be configure.

 

Now open your Cloud Cockpit to configure Destination.

After this we need to configure Destinations in Cloud Cockpit.

Additional Properties are required, there are 4 exists add all of them.

 

9.png

 

10.png

 

 

 

This is done for Cloud Cockpit. Restart your Cloud Cockpit once, than proceed for below steps.

 

Now we need to setup service for Project. Open your SAPUI5 project and set OData Service.

 

11.png

 

 

This will only come once you define Destination properly and after that restart it once.

You will see all the services which are already created in Gateway Server which we have selected earlier.

 

12.png

 

Select the one of your Interest.

 

13.png

 

 

Many of Configuration changes will be done automatically to your SAPUI5 application’s Component.JS file.

This blue box details will be added automatically.

 

 

14.png

 

15.png

 

Thanks-

Abhishek

Viewing all 789 articles
Browse latest View live




Latest Images