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

CRUD Operation on ODATA Model

$
0
0

When we play with data, then the most talked about operations are CRUD Operations. CRUD features are nothing but Create/Read/Update/Delete operations.

As we know we can bind a UI element in an SAPUI5 application to the data specified in an OData service. For example, you can populate the contents of table columns displayed in an SAPUI5 application with the data stored in a database table defined in an OData service. In this document, you learn how to build an SAPUI5 Mobile App that provides the options, which you can use to create a new record or update an existing record in a database table, for example, using the OData create, update, and delete (CRUD) features. Now lets take a look into it:

 

Create Request:

 

The create function triggers a POST request to an OData service which was specified during creation of the OData model. The application has to specify the collection where to create the entry and the entry data payload. To get the result of the request, the application can hand over callback handler functions. To recreate and update the bindings, a refresh is triggered automatically after the successful creation.

The following code triggers a new entry in the Products collection:

 

oModel.create()

var oEntry = {};

 

oEntry.ID = 9;

oEntry.Rating = 5;

oModel.create('/Products', oEntry, null,
function(){
          alert("Create successful");

               },function(){

        alert("Create failed");});

 

 

 

Delete Request:

 

The remove function triggers a DELETE request to an OData service which was specified during creation of the OData model. The application has to specify the path to the entry which should be
deleted. To update the bindings in the model, a refresh is triggered automatically after successful deletion. A single parameter oParameters can be passed into the function and can carry all optional attributes, such as attributes for success and error handling functions as well as ETag attributes.

 

The following code deletes the product entry with ID=1 from the Products collection of the data service:

oModel.delete()

oModel.remove('/Products(1)', null,
function(){
           alert("Delete successful"); },

function(){                alert("Deletefailed");});

 

 

Update Request:

 

The update function triggers a PUT request to an OData service which was specified during creation of the OData model. See the ODataModel API for information about attribute use. The application has to specify the path to the entry which should be updated with the specified updated entry. After a successful request to update the bindings in the model,a refresh is triggered automatically.

 

The following code updates the rating:

 

oModel.update()

var oEntry = {};

 

oEntry.Rating = 5;

oModel.update('/Products(1)', oEntry, null,
function(){
alert("Update successful");  },

function(){ alert("Updatefailed");});

 

 

Read Request:

 

The read function triggers a GET request to a specified path which should be retrieved from the OData service which was specified during creation of the OData model. The retrieved data is returned in the success callback handler function.

 

The following code reads the specific data:

oModel.read()

oModel.read('/Products(1)', null, null,
true, function(oData, oResponse){

alert("Read successful: " + JSON.stringify(oData));  },

function(){  alert("Readfailed");});

 

 

 

Now, Lets Create a small Demo app to demonstrate all these features.

 

Demo

Go to eclipse---New Project---SAPUI5 Mobile App—Create a js View View.

Now we would use the following oData service for our app:

http/services.odata.org/V2/(S(hgfvvt31yj5dms3ogd01si4d))/OData/OData.svc/

 

Now , Paste the following code in onInit function() of controller .js:

 

onInit() function of controller.js

var oModel = new sap.ui.model.odata.ODataModel "proxy/http/services.odata.org/V2/(S(hgfvvt31yj5dms3ogd01si4d))/OData/OData.svc/", false);

sap.ui.getCore().setModel(oModel);

 

Now Paste the following code in the createContent function() of  view.js file:

 

 

createContent() of view.js

var oPage = new sap.m.Page({

 

                                title: "Product Details",

                                });

var oButton1 = new sap.m.Button("Submit", {

 

                                   text: "New Entry",

                                   tap: [ oController.NewEntry, oController ]

                              });

var oButton2 = new sap.m.Button("Save", {

 

                                   text: "Save",

                                 tap: [ oController.Save, oController ]

                              });

var oButton3 = new sap.m.Button("Cancel", {

       text: "Cancel",

    tap: [ oController.Cancel, oController ]

                              });

var oButton4 = new sap.m.Button("Update", {

    text: "Update",

  tap: [ oController.Update, oController ]

   });

  var oButton5 = new sap.m.Button("Delete", {

      text: "Delete",

  tap: [ oController.Delete, oController ]

    });

var oDialog = new sap.m.Dialog("Dialog1",{

  title:"Details of New Entry",

modal: true,

contentWidth:"1em",

buttons : [oButton2, oButton4, oButton5, oButton3 ],

  content:[

new sap.m.Label({text:"Enter Id(must be a number)"}),

new sap.m.Input({                                       

   maxLength: 20,

  id: "Id"   

  }), new sap.m.Label({text:"Enter Rating"}),

new sap.m.Input({                                       

   maxLength: 20,  id: "Rating"           

  }),

new sap.m.Label({text:"EnterPrice"}),

new sap.m.Input({                                       

  maxLength: 20,

   id: "Price"           }),

]

   });

var oTable = new sap.m.Table({

  id: "Products",

  itemPress : [ oController.ItemPress,oController ],

columns: [

  new sap.m.Column({

   width: "1em",

   header: new sap.m.Label({

      text: "ID"  })   }),
new sap.m.Column({

    width: "1em",    header: new sap.m.Label({

    text: "Release Date"    })

  }),
new sap.m.Column({

   width: "1em",  header: new sap.m.Label({

    text: "Discontinued Date"

     })

      }),
new sap.m.Column({
   width: "1em",

  header: new sap.m.Label({

      text: "Rating"

})

  }),
new sap.m.Column({

  width: "1em",

  header: new sap.m.Label({

    text: "Price"

  })   })

     ]  });

   var template = new sap.m.ColumnListItem({

 

                                             id: "first_template",

                                             type: "Navigation",

                                            visible: true,

                                             cells: [

 

                                             new sap.m.Label("ID", {

  text: "{ID}"

  }),
new sap.m.Label({

    text: "{ReleaseDate}"

  }),
new sap.m.Label({

                        text: "{DiscontinuedDate}"

     }),
new sap.m.Label({

                        text: "{Rating}"

     }),
new sap.m.Label({

                 text: "{Price}"

        })

                ]

       });

  var  oFilters = null;

  oTable.bindItems("/Products",template, null, oFilters);

  oPage.addContent(oButton1);

oPage.addContent(oTable);

  return oPage;

 

 

Now finally Paste the following code at the end of controller.js file:

controller,js

 

ItemPress: function(evt) {

   sap.ui.getCore().byId("Dialog1").open();

sap.ui.getCore().byId("Save").setVisible(false);

   sap.ui.getCore().byId("Update").setVisible(true);

sap.ui.getCore().byId("Delete").setVisible(true);

var oSelectedItem = evt.getParameter("listItem");

     varsID = oSelectedItem.getBindingContext().getProperty("ID");

  varsRating = oSelectedItem.getBindingContext().getProperty("Rating");

   var sPrice = oSelectedItem.getBindingContext().getProperty("Price");

sap.ui.getCore().byId("Id").setValue(sID);

   sap.ui.getCore().byId("Rating").setValue(sRating);

   sap.ui.getCore().byId("Price").setValue(sPrice);

sap.ui.getCore().byId("Id").setEnabled(false);

},

NewEntry: function() {

sap.ui.getCore().byId("Dialog1").open();

   sap.ui.getCore().byId("Save").setVisible(true);

sap.ui.getCore().byId("Update").setVisible(false);

   sap.ui.getCore().byId("Delete").setVisible(false);

   sap.ui.getCore().byId("Id").setValue("");

    sap.ui.getCore().byId("Rating").setValue("");

   sap.ui.getCore().byId("Price").setValue("");

sap.ui.getCore().byId("Id").setEnabled(true);

 

               },

   Save: function() {

     var oEntry = {};

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

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

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

  sap.ui.getCore().getModel().create('/Products',
oEntry, null, function(){

    alert("Create successful");

   location.reload(true);

    },function(){

       alert("Create failed");});

               },

Update: function() {

var oEntry = {};

var ID = sap.ui.getCore().byId("Id").getValue();

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

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

sap.ui.getCore().getModel().update('/Products('+ID+')',
oEntry, null, function(){

    alert("Update successful");

  location.reload(true);

},function(){  alert("Update failed");});

 

               },

Delete: function() {

var oEntry = {};

var ID = sap.ui.getCore().byId("Id").getValue();

 

sap.ui.getCore().getModel().remove('/Products('+ID+')',
null, function(){
  alert("Delete successful");

  location.reload(true);

   },function(){   alert("Delete failed");});

 

               },

  Cancel:function() {

    sap.ui.getCore().byId("Dialog1").close();

               }

 

 

Complete, now save run your application:-

Select the Item you update and then a popup appears

 

 

chrome.jpg

Done!!!

 


Explore the com.sap.ui5.resource.ResourceServlet

$
0
0

There is one questionasking how and where the js file "resources/sap-ui-core.js" is loaded when you run your ui5 application locally ( for example using tomcat )?

 

In my sample project mymap, there is no folder named resources and thus no sap-ui-core.js either.

 

clipboard1.png

However, in the runtime, you could indeed observe the folder resources and the sap-ui-core.js inside it via Chrome development tool, tab "Sources":


clipboard2.png

In order to figure out what happens in the runtime, let's have a look at the web.xml under folder WEB-INF in the project.

There is a ResourceServlet defined. Actually it is the responsibility of this servlet delivered by SAP, which returns the content of resouces like js, css and other type in the runtime. So now if I would like to investigate on this servlet, how could I get its source code?

clipboard3.png

How to get source code of ResourceServlet

 

Suppose you have already an working Tomcat instance.  Right click your UI5 project, choose Export->War file, and manually copy that exported war file to the webapps folder of your tomcat instance folder. In my case the folder is : C:\myProgram\tomcat-7.0.54\webapps.

 

Now start your tomcat via bat file, in my case: "C:\myProgram\tomcat-7.0.54\bin\startup.bat":

 

You should see one information message that the war file is deployed:

clipboard4.png

Now go back to your webapps folder, you should have a folder mymap which is automatically unzipped from war file by Tomcat.


clipboard5.png

Now just search by keyword "Resource", and unzip the first hit jar file.

clipboard6.png

After that you could find three .class file in the unzipped folder, in my case they are:

 

"C:\myProgram\tomcat-7.0.54\webapps\mymap\WEB-INF\lib\com.sap.ui5.resource_1.24.1\com\sap\ui5\resource\ResourceServlet.class"

 

"C:\myProgram\tomcat-7.0.54\webapps\mymap\WEB-INF\lib\com.sap.ui5.resource_1.24.1\com\sap\ui5\resource\impl\ServletResource.class"

 

"C:\myProgram\tomcat-7.0.54\webapps\mymap\WEB-INF\lib\com.sap.ui5.resource_1.24.1\com\sap\ui5\resource\impl\ServletResourceLocator.class"

 

The last step, google "jd-gui" and download it. It allows you to directly review source code of a .class file.

clipboard7.png

clipboard8.png

Since now we have source code at hand, we could do further investigation on this servlet.

 

More investigation on ResourceServlet

 

The main job of resource handling is wrapped in method serveResource of class ResourceServlet. We could find at least 2 useful hint from this method.

 

1. use dev mode to figure out where the resource is loaded

clipboard9.png

From line 616 and 617, we get to know if the current application runs under Dev mode, it is supported to print out the url of the found resource in http response header.

 

Just switch on Dev mode by making following settings in web.xml:

clipboard10.png

after that you could observe the x-sap-ResourcUrl attribute for sap-ui-core.js in Chrome Metwork tab, which shows where Tomcat loads this js file in the runtime.


clipboard10.png

You could directly browse your application resource by appending "/resources/" to your application url, in my case it is: http://localhost:8080/mymap/resources/

clipboard11.png

You might already notice the "CLASSPATH", what does it mean?

 

The constructor of ServletResource which extends base class Resource has one parameter source, which indicates whether this resource is loaded locally or remotely ( configured through parameter com.sap.ui5.resource.REMOTE_LOCATION ):

clipboard12.png

in class ServletResourceLocator which implements interface ResourceLocator, the instance for found ServletResource is initialized with corresponding source category, "CLASSPATH" or "REMOTE", according to different approaches how they are actually loaded:

clipboard13.png

And ResourceServlet will print out this property for each found resource between a pair of "[ ]":

clipboard14.png

this is the reason why you could see lots of CLASSPATH in tomcat output:

clipboard15.png

2. understand HTTP 304 status

 

For example, why I get a HTTP 304 Not Modified for this file?

clipboard16.png

The answer is in line 625 of ResourceServlet class:

clipboard17.png

In this example, the second condition after && is always true, since I never make any modifications on this standard library js file:



clipboard18.png

So we only need to evaluate the result of CacheControlFilter.hasNoCacheHeader(request). The source code of this method is listed below:


clipboard19.png

In my example since there is no such Cache-Control in request header, this method will return false and finally leads to a 304 status code.

clipboard20.png


So now if we click the checkbox "Disable cache" in Chrome, we then get a HTTP 200 status code instead, since this checkbox adds a Cache-Control header with value "no-cache":

clipboard21.png

With the approach introduced in this blog, you could also explore another servlet by yourself, which you could also find and configure it in web.xml: com.sap.ui5.proxy.SimpleProxyServlet.


Enjoy learning

Changing the shape of sap.m.Button in SAPUI5

$
0
0

Now in this blog we will see how to create a round button. The thought behind this blog is to play with the shape of the button.We would use the a bit css to change the boundary of the button.

For that create a SAPUI5 mobile project.

 

In the index.html add the following code to within the <head> tag:

 

index.html --<style> tag

<style>

.circleButtondiv.sapMBtnInner {

       height: 300%;

       width: 230%;

       border-radius: 50%;

}

</style>

 

Now in the createContent of the view.js paste the following code:

 

createContent of view.js

var oPage = new sap.m.Page({

title: "Round Button Demo"

});

  var oButton=new sap.m.Button({

text:"Click",

press:funtion(){

sap.m.MessageToast.show("shaped button clicked",{duration:1000});

}

});

oButton.addStyleClass('circleButton');

oPage.addContent(oButton);

  return oPage;

 

 

Save and run the application;

 

Round Shape

chrome.jpg

 

Now in the <style> tag change the height and width and border-radius to find different shapes:

 

Round Edged Button

 

height: 300%;

width: 230%;

border-radius: 20%;

 

chrome1.jpg

 

Oval Shaped Button

   
height
: 200%;

width: 230%;

border-radius: 50%;

 

chrome3.jpg

So, keep changing the parameters to find the shape which fits your requirement.

My experience while learning new languages - Deutsch and JavaScript ( UI5 )

$
0
0

               Status quo is the easiest state, for one to stay. Change brings about disruption into the present state of affairs. However, in life it is change which is the status quo.

 

               Now and then, we are faced with a disruption in world of technology which results in replacing the existing best-practices with new ones. Till a while ago, I felt there is no better way to maintain data than by normalizing tables and introduction of HANA and NoSQL just turned it upside down. A normal behaviour in particular period of time could turn into abnormal in future. I was faced with this dilemma when I had to learn Deutsch. My experience of learning Deutsch gave some insights into learning the other language i.e. JavaScript. I wish to share them with my fellow members of SCN esp. the ones who belong to non-Java community. My intention is to find a pattern which could be useful in learning the new language.


 

Deutsch LernenJavaScript
Initial Feeling Decision to learn Deutsch was enforced as part of the company policy. I took it up with a positive intent but internally, I was not fully committal. I used to question the need or importance of it in my life. However, with the lack of alternative I started my lessons. Introduction of UI5, Mobile Development and Web made JavaScript the recommended programming language. As a Web Dynpro developer, I had no option but to take up learning JavaScript and UI5. My feelings were same as it was with Deutsch: I was faking it on outside but non-committal in the inside.
Refer to status quoEnglish was my language of reference. So, I started to look for words and grammar in deutsch which had parallels in english. Wort was word, fliegen was to fly, mussen was must; subject verb and object - Ich bin gut i.e. I am good. The new world of deutsch seemed easy . Java(tossed with a bit of ABAP) was my language of reference. I started to look for keywords which had parallels with my reference programming language. Var was to declare a variable, "break, catch, continue, for, return, switch" were the same as ones in Java. It felt like a walk in the park
Selective amnesiaIn the process of finding parallel elements of deutsch with english language, I started to ignore aspects which did not confirm. The famous being, the various forms of pronoun: ich, du, er/es/sie, wir, ihr, Sie/sie. Everytime, I had to find the forms of the verb, I just skipped it. Functions as an object is something which is difficult to fathom. Its not always sequential execution of statements, it could be haphazard. I was slowly ignoring it as abnormal.
Dead EndI could no more ignore the rules of deutsch pronouns. No more could I avoid various forms of verb. Then the dead-end: A word can be masculine, feminine, neutrum and plural. Tee is masculine and Flasche(bottle) is feminine, how?Everything is a variable, variables can be reassigned, it is interpretor based language, functions can be passed as objects, and many other unique aspects of JavaScript meant, I was stuck. I did not know where to go next.
Accept the new language in the independent formI started to treat Deutsch independent of references to English. I stopped translating everything in Deutsch to English. Accepting the new paradigm and treating in its original form helped me to move forward. JavaScript is not Java. JS brings in scripting into the static HTML and runs on the browser client. It does not follow the strict syntax rules of Java or ABAP. It is unique and had its unique characteristics.
Get deeper into the new languagePractice the lessons without the fear of embarrassment. It started to expose my mistakes and in return helped me improve my language.Started to write JS programs. With the abundant browser based editors, it was easier to practice JS on the runtime. It improved my skills and in-forced confidence.


               I am still taking baby steps with my Deutsch. I would look to improve on my language skills. However, my focus is more on JavaScript. I am like the novice swimmer, now looking into the ocean and feeling ready to dive in. We will never be completely ready at the start. We should be adequately prepared. More importantly, we should be ready to fail and learn to keep moving forward.


               Thank you for your time and ich freue mich(I look forward) to your feedback.


Upload file from SD Card / Camera to phone/Tablet Screen using SAP UI5

$
0
0

Hi,

 

Here we discuss about DMS initial steps concepts.

 

Intro:

A document management system (DMS) is a system (based on computer programs in the case of the management of digital documents) used to track and store documents. It is usually also capable of keeping track of the different versions modified by different users (history tracking).


From SAPUI5:


1. How to get my image/Doc from Camera or SD Card?


Code for getting image from Camera:


function capturePhoto(idImage) {

      // Take picture using device camera and retrieve image as base64-encoded string

      var id = idImage;

      navigator.camera.getPicture(function (imageData) {

          // Uncomment to view the base64 encoded image data

          var smallImage = document.getElementById(id);

          smallImage.style.display = 'block';

          smallImage.src = imageData;

    

             jQuery.sap.require("sap.m.MessageToast");

  var msg = 'Image added Successfully!!!';

      sap.m.MessageToast.show(msg);

         // localStorage.setItem('img',smallImage.src);

        var path = movePicturetoSDCard(imageData);

         

        }, onFail, { quality: 50 });

    }

 

 

 

Code for getting image from SD Card:


function getPhoto(source,idImage) {

      // Retrieve image file location from specified source

      navigator.camera.getPicture( function (imageData) {

          // Uncomment to view the base64 encoded image data

          var smallImage = document.getElementById(idImage);

          smallImage.style.display = 'block';

          smallImage.src = imageData;

         

         

          jQuery.sap.require("sap.m.MessageToast");

  var msg = 'Image added Successfully!!!';

      sap.m.MessageToast.show(msg);

         // localStorage.setItem('img',smallImage.src);

          var srcAlert = smallImage.src;

          //movePicturetoSDCard(imageData);

        }, onFail, { quality: 50,

           destinationType: destinationType.FILE_URI,

           sourceType: source });

    }

 

 

if you have any doubt while upload your image to your mobile/tablet screen. don't hesitate to ask your questions

 

From SAP Gateway Side:

 

refer: DMS Application Server file Upload

 

 

Cheers

Karthik A



 

Sap UI5 with Local JSON Model

$
0
0

Hi All,

 

This blog shows the step by step procedure to use the local json model with Sap UI5.

 

Tools used:

  • Eclipse Luna Service Release 1
  • Tomcat Apache (Server)
  • SAP UI5 Plug-in installed in Eclipse.
  • Google Chrome

 

 

Step 1: Create the Sap UI5 Application project


In Eclipse, File-->New-->Other and select "SAP UI5 Application Development"-->Application Project and click on next button.

Image1.jpg

 

Provide the project name and click on next button.

Image1.jpg

 

Step 2: Create the Folder Json and file

Then provide the name of the view and click on Finish.

 

Image1.jpg

 

 

 

Then select the Project JsonDemo and create a new folder using the context wizard

 

Image1.jpg

 

 

Create a new folder named “JSON” in the Web Content directory of the project JsonDemo


Image1.jpg


Creating a File named Item.json under the folder json

Image1.jpg



Image1.jpg

STEP 3: Add the below mentioned content to the JSON File.


{

"Item": [

        {

"Manufacturer": "Microsoft",

"Type": "Optical Mouse",

"Price": 300

        },

        {

"Manufacturer": "Intex",

"Type": "Laptop Mouse",

"Price": 200

        },

        {

"Manufacturer": "Iball",

"Type": "Traditional Mouse",

            "Price": 150

        },

        {

"Manufacturer": "Dell",

"Type": "Gaming Mouse",

"Price": 400

        },

        {

"Manufacturer": "Logitech",

"Type": "Wireless mouse",

"Price": 500

        },

        {

"Manufacturer": "HP",

"Type": "Optical Mouse",

"Price": 300

        }

      

    ]

}

 

 

 

Implement the following code in JsonDemo.view under the createcontent method.

// Create instance of JSON model

             var oModel = new sap.ui.model.json.JSONModel();

           // Load JSON in model

              oModel.loadData("json/Item.json");

 

              // Create instance of table control

              var oTable = new sap.ui.table.Table({

                     title : "Computer Accessories",

                     visibleRowCount : 6,

                     firstVisibleRow : 0

              });

              // First column "Manufacturer"

              oTable.addColumn(new sap.ui.table.Column({

                     label : new sap.ui.commons.Label({

                           text : "Make"

                     }),

                     template : new sap.ui.commons.TextView().bindProperty("text",

                                  "Manufacturer"),

                     width : "100px"

              }));

              // Second column "Type"

              oTable.addColumn(new sap.ui.table.Column({

                     label : new sap.ui.commons.Label({

                           text : "Model"

                     }),

                     template : new sap.ui.commons.TextView().bindProperty("text",

                                  "Type"),

                     width : "100px"

              }));

 

              // Third column "Price"

              oTable.addColumn(new sap.ui.table.Column({

                     label : new sap.ui.commons.Label({

                           text : "Amount"

                     }),

                     template : new sap.ui.commons.TextView().bindProperty("text",

                                  "Price"),

                     width : "100px"

              }));

 

              // Bind model to table control

              oTable.setModel(oModel);

              oTable.bindRows("/Item");

              oTable.placeAt("content");

 

 

 

Remember to include the library “sap.ui.table” in the index.html

 

       <scriptsrc="resources/sap-ui-core.js"

         id="sap-ui-bootstrap"

         data-sap-ui-libs="sap.ui.commons,sap.ui.table"

         data-sap-ui-theme="sap_bluecrystal">

        </script>

 

 

Right click on the index.html and select the option run on server

Result:

 

Image1.jpg

My small experience about how to find the exact line position which causes "undefined is not a function" error

$
0
0

Recently I meet with an annoying Javascript error "undefined is not a function" during my Fiori development. After debugging the framework code for several hours , I finally find a more efficient way to find the exact source code which causes the trouble. I would like to share this small tip with you and hope it could help.

 

Issue: When I am doing test on my application on a local tomcat, I could only see an empty screen.

For sure there must be some Javascript error occurred.

 

clipboard1.png

Open Chrome console and I see one Uncaught TypeError: undefiend is not a function as expected.

clipboard2.png

Unfortunately this error is raised in UI5 framework js "UIComponent.js", after I click the hyperlink in the screenshot above, I am automatically navigated to this file, however I do completely not understand what has happened here, in function ( q, C, U, V ).

clipboard3.png

Then I press Ctrl+Alt+Shift+P to switch on debug by marking checkbox "Use Debug Sources".

clipboard4.png


Refresh UI and now the debug resource, UIComponent-dbg.js is loaded instead. Since what I bad need is the context of this error, or callstack, so I set a breakpoint on catch statement, line 47. Relaunch application UI and breakpoint is triggered.

 

I add variable e in Watch Expression:

clipboard5.png

Expand variable e in Watch Expressions and put the mouse to stack. The complete callstack is instantly displayed.

 

The topmost callstack shows the error occurs in line 154, column 36 of file ConnectionManager-dbg.js:

clipboard6.png

Then I find the root cause here:

clipboard7.png

the variable service.serviceUrl is not a String but an object of URI which does not have a method named "indexOf":

clipboard8.png

Conclusion

 

Although this error is raised in UI framework js file, it is however an absolute application issue: the url of OData is defined in Configuration.js file by application as metadata, and UI framework in the runtime will ask for it by calling some callback functions defined by application and then consume it. Framework will assume always a String for OData service url returned by application.

 

After the following fix is done on application, the issue is fixed.

clipboard9.png

Any other alternative solution?

 

Later on I find another approach to find the position ( line 154, column 36 ) even without debugging.

 

I test my app with Firefox. To my surprise, it could directly display more detail about this error compared with Chrome: "j.serviceUrl.indexOf is not a function".

clipboard10.png

 

The Firefox console shows this error occurs in sap-ui-core.js line 80

clipboard11.png


However I could not find any hit by searching "indexOf" within this file.

clipboard12.png

So I just again switch to Chrome and search serviceUrl.indexOf in Chrome instead, this time I get directly what I am looking for.

clipboard13.png

From this cause it seems that these two complementary poweful tool, Chrome and Firefox, could make our life as UI5 developer more easier

Asking for coding help - SAPUI5 - (please read before posting coding questions)

$
0
0

Hello community,

 

with this blog I hope solving coding problems will be faster in future.

A lot of questions / problems in Space UI Development Toolkit for HTML5 Developer Center are about coding issues.

 

So how can somebody who has a problem make it easier for people who can solve the problem?

Often there is the problem, you need to see the result of your coding, so people who want to help must establish a working area for your code snippet.

 

With JS Bin you can share your code online, but the special here is you can run the code online / live. You don't need to download anything. Also people who can help you don't need to download your example code.

 

JS Bin offers also versioning of the code.

 

But you can't upload your whole SAPUI5 Project to JS Bin, only code snippets. This isn't that bad, because nobody want to upload his whole project :-P

 

So here are some examles, how to implement your code at JS Bin:

 

Here you can read a lot more about the basics of JS Bin: http://code.tutsplus.com/tutorials/javascript-tools-of-the-trade-jsbin--net-36843

 

Important for asking users: Please paste your code at JS Bin and don't paste the code between your question (only for explanation, but better use comments in xml / js at JS Bin) and don't attach the code as archived files.


I hope this blog will help the whole SAPUI5 community.

You can refer people to this blog if they aren't familiar with JS Bin.


Suggestions are welcome.


SAPUI5 Discussions - RTFRoE

$
0
0

Hello SCN Citizens,


Personally, I'm not a great fan of writing blogs. However, few instances in this UI space made me to write this blog.

I'm not going to write something new instead going to echo fellow SCN members mind voice here.


In most thread, I have come across like below reply


  1. Its working, Thanks for helping.
  2. Some AAA has solved my problem. Closing this thread.              

   3.  Share your mail id, I will send the code

   4.  Mail me your code to bbb@bbb.com


              

By mentioning "thanks or solved" in the word doesn't mean the thread is closed. Either click "Helpful" or "correct answer" as appropriate.

It not only help the readers, it motivates contributors as well.


Don't we have rules of engagement in this forum? (Personally, I feel Rules are meant to be broken , but not here)

Yes, we do have, but I don't know what's stopping you to follow this


How to ask questions in the forum?


1.  Search Forum First, Why you need to search the forum first?


You are not the first one who is having or facing the problem.The same questions might have asked and answered before.

Search will give result faster than waiting for SCN members reply.

 

2.  Show Some Effort


          SCN members are always ready to answer your questions. It doesn't mean we are here to do your homework.


          A few instance as follows - I've a requirement and I want this this.

         

          Instead, tell us, I have tried this this and I'm stuck here. Please help me to solve the problem.

          In this way it will attract fellow members to answer your query and you will get reply quickly.

          Otherwise, there is a possibility; SCN members might skip your questions.


3. Share your code in jsbin


     What is jsbin and Why you need to share your code in jsbin, refer Kai Helferich blog here

 

4. Mention Cross posting


          Stackoverflow also have separate space for SAP UI5. Some users post the same question in SCN and stack overflow.

          We understand you want to solve your problem quickly and finish your development work before your deadline.

          So you are posting it in other forums. Experts might have answered the same questions in other forums.

          If you mention cross posting, it will help fellow readers to choose the best answers.


5. Avoid ASAP questions


          SCN members are not paid to solve your problems. Like you "we too have project work, we too have deadlines."

          We are spending our personal time to answer your questions. Please do value our personal time.


Thanks for understanding and comments are most welcome.


P.S: Title credit goes to Michael Appleby (updated)

Exporting to Excel from sap.m.Table via csv

$
0
0

Guys some good news, hopefully for many others as well. In this process of learning and playing with SAPUI5 mobile, I have silently got a way out to export the data to excel. To be frank, we can’t directly export the data to excel. It needs to be formed into a csv format and then to excel.

 

So, lets begin.

 

Go to eclipse---New SAPUI5 project<Mobile>--Give the view name as “View1” (js view).

 

Firstly, the Design

Paste the following code in the createContent() of  View1.view.js (Design):

 

createContent() of  View1.view.js

 

 

var oPage = new sap.m.Page({

 

                    title: "Company Details"

             });

 

var oButton = new sap.m.Button({

 

                    text: "Export",

                    press:[ oController.Export, oController ]

             });

 

 

             var oTable = new sap.m.Table({

 

                    id: "Countries",

 

                    mode: sap.m.ListMode.None,

 

                    columns: [ new sap.m.Column({

 

                       width: "1em",

                         header: new sap.m.Label({

                           text: "Name"

 

                           })

                    }),new sap.m.Column({

 

                           width: "1em",

                            header: new sap.m.Label({

                            text: "short"

                            })

                      })

                    ]

              });

 

 

             var template = new sap.m.ColumnListItem({

 

                   id: "first_template",

                      type: "Navigation",

                      visible: true,

                      selected: true,

                      cells: [ new sap.m.Label({

 

                           text: "{name}"

 

                    }),new sap.m.Label({

 

                           text: "{short}"

                      })

 

                   ]

              });

               oTable.bindItems("/countries", template, null, null);

               oPage.addContent(oButton);

               oPage.addContent(oTable);

              return oPage;

 

 

 

 

Now, Lets create the model which will hold the data.

For that paste the following code in the onInit() method of the controller.js file:

 

 

onInit() method of the controller.js

 

 

var data1 = {

 

                    "countries" : [ {

 

                           "name" : "India",

                           "short" : "In"

 

                    },
{

 

                           "name" : "England",

                           "short" : "En"

 

                    },
{

 

 

                           "name" : "Australia",

                           "short" : "Oz"

 

                    },
{

 

                           "name" : "New Zealand",

                           "short" : "Nz"

 

 

                    },
{

 

                           "name" : "France",

                           "short" : "Fr"

 

                    },
{

 

                           "name" : "SouthAfrica",

                           "short" : "SA"

                    },
{

 

                           "name" : "Germany",

                           "short" : "Gr"

 

                    }
]

 

      };

 

var oModel = new sap.ui.model.json.JSONModel(data1);

sap.ui.getCore().setModel(oModel);

 

 

Now the functionality which would export the data to excel.

 

 

For that paste the following method in the controller.js file

 

JSONToCSVConvertor

 

JSONToCSVConvertor : function(JSONData, ReportTitle, ShowLabel) {

 

         

// If JSONData is not an object then JSON.parse will parse the JSON

// string in an Object

 

   var arrData = typeof JSONData.countries!= 'object' ?JSON.parse(JSONData.countries) : JSONData.countries;

   var CSV = '';

   // Set Report title in first row or line

CSV+= ReportTitle + '\r\n\n';

 

             if (ShowLabel) {

 

                    var row = "";             

                    row= row.slice(0, -1);

                  CSV+= row + '\r\n';

 

             }

 

             //loop is to extract each row

 

             for (var i = 0; i <arrData.length; i++) {

 

                    var row = "";

                  row+= '"' + arrData[i].name + '","' + arrData[i].short +'",';

                  row.slice(0,row.length - 1);

                    CSV+= row + '\r\n';

 

             }

 

             if (CSV == '') {

 

          alert("Invalid data");

                    return;

             }

 

             // Generate a file name

 

             var fileName = "MyReport_";

           fileName+= ReportTitle.replace(/ /g, "_");

 

             // Initialize file format you want csv or xls

             var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

 

             // Now the little tricky part.

             // you can use either>> window.open(uri);

             // but this will not work in some browsers

             // or you will not get the correct file extension

             // this trick will generate a temp<a /> tag

             var link =document.createElement("a");

       link.href= uri;

 

             // set the visibility hidden so it will not effect on your web layout

 

       link.style= "visibility:hidden";

       link.download= fileName + ".csv";

 

// this part will append the anchor tag and remove it after automatic

  // click

             document.body.appendChild(link);

             link.click();

             document.body.removeChild(link);

 

       }

 

 

And the last part. In the design we added a button, now we need to invoke the above function on the click of the button.

For that past the following code in controller.js as well.

 

Export function in controller.js

 

Export : function() {

 

  var data= sap.ui.getCore().getModel().getData();

  this.JSONToCSVConvertor(data,"Report", true);

 

       }

 

Now our application ready for testing.  Here, we go:

 

chrome.jpg

 

 

Hmmmm, Not Bad!!!!!!!!!

How to use OData service exposed via Integration Gateway (on-premise) with SAP Web IDE Cloud

$
0
0

Hello Developers,

 

Well, I heard a lot about SAP Web IDE and thought of getting my hands dirty. Here, I am trying to use OData service exposed via Integration Gateway (on my local machine in SAP Mobile Platform 3.0) with SAP Web IDE cloud version.

Never heard about Integration Gateway?

 

        

 

Tools required: SAP Mobile Platform 3.0 SP04, Eclipse Kepler with SAP Mobile Platform Tools plugins added, SAP HANA Cloud Connector

 

I have already exposed one of the publicly available Article SOAP web Service into OData services via Integration gateway in SMP3. (Ref link)

 

This is how it looks like:

 

          

          articleservice.png   

 


Setting up SAP HANA Cloud Connector

 

Prerequisite: Download SAP JVM for Windows sapjvm-7.1.024-windows-x64.zip or JDK 1.7

Set Env variables  JAVA_HOME : C:\Program Files\Java\jdk1.7.0_67

                          PATH: C:\ProgramFiles\Java\jdk1.7.0_67\bin;C:\WINDOWS\system32;C:\WINDOWS;

 

Steps:

 

1. Download HANA Cloud Connector from SAP Development Tools for Eclipse (sapcc-2.4.3-windows-x64.zip)

2. Extract the downloaded zipped file. Run go.bat command


        gobat.png


3. Once done, run https://localhost:8443/run it in a browser

 

Don't close command prompt window as per step #2

As i was trying to install SAP HANA Cloud Connector on Windows 8.1 OS and as per official information it doesn't support. As a workaround have tried copying sapscc20jni.dll file from auditor folder at sapcc-2.4.0-windows-x64 into Windows\System32 (Reference)


                    (User Name: Administrator, Password: manage (default))              


               hcclogin.png       


4. Choose Installation type: Master (Primary Installation)>Apply

5. Change the login password

6. Set up Initial Configuration (for more info: check http://account.hanatrial.ondemand.com/)

     Enter proxy details if any.


        iniCong.png

      

     This is how it looks like: Status :CONNECTED


          statusconnectd.png



7. Since OData service has been deployed on my local machine and to access on-premise resources from cloud platform, I need to open secure connection between on-premise network and cloud. I need to make sure what kind of resources I want to expose from on-premise to SAP HANA cloud system, for that go to Access Control

Add system mapping:

 

          addsystemmapping.png

 

 

ParameterValue
Virtual HostAny name of your choice
Virtual PortAny number of your choice
Internal HostSMP server host name ('jk' in my case)
Internal Port

Port on which OData URL (Exposed via Integration Gateway) is listening

(https://jk:8083/gateway/odata/SAP/ARTICLESERVICE;v=2/)

ProtocolHTTPS
Back-end TypeThere is no option to related to SMP and Integration gateway so selected 'SAP Gateway'

 

8.Now, I want to decide which resource path I have to select 


            addresource.png


As you can the green icon (state of each entry)


             status.png

Setting up SAP HANA Cloud Platform

 

It's time to set up SAP HANA Cloud account and have to create destination to exposed resources in SAP Mobile Platform server.


9. Login to SAP HANA Cloud Platform> Cockpit (Requires SCN username and password to login)

  • Create a new destination >Save

 

     destinationDetails.PNG


URL:https://virtualhost:virtualport (as per step #7)

Proxy Type: As OData service resides on on-premise system

Authentication: Basic Authentication (Credentials to access Odata URL: smpAdmin, s3pAdmin)


Additional Properties:


 

WebIDEEnabledtrue
WebIDESystemIGWDestination
WebIDEUsageodata_gen


Value for the parameter WebIDEUsage is important otherwise you won't be able to pick your destination from the Service URL combo box when creating a new project with the template wizard. (Step #14)


In general, the value for the parameter WebIDESystem is SID of the gateway system but in case of SMP (Integration Gateway) it's value doesn't need to be anything special. Normally, in order to see the destination working, i have assigned to the webIDESystem the same string used for the destination name. i.e. IGWDestination


10. Go to Subscriptions >launch SAP Web IDE


          subscription.PNG


 

Create a project in SAP Web IDE (Cloud)


11. File>New>Project from Template


          projectfromtemplate.PNG         


12. Select "SAP Fiori Starter Application" as the template > Next


         sapfioritemplate.PNG

13.Basic Information> Give any project name of your choice


          projName.PNG              

    

14. Data Connection> Service URL > select "IntegrationGateway" from the drop-down (as per step #9)

  • Paste the URL : /gateway/odata/SAP/ARTICLESERVICE;v=2

 

          beforetest.PNG

   

  •   Test connection . This is how it should like:

              

               aftertest.PNG


15.Template Customization

 

    We will having one master section and one detail section,provide information and Finish.



    masterdetailsection.PNG


16.  You can see auto-generated artifacts for this project. Select "index.html" > Run

 

 

                 

 

 

               outpur.PNG

 

        

Big thanks to Virinchy P , Markus TolksdorfSIMMACO FERRIERO for great support.


References:


Video links: SAP Web IDE - YouTube, Krishna 's self explanatory videos

Forums to follow: SAP Mobile Platform Developer Center , UI Development Toolkit for HTML5 Developer Center

Useful link: SAP Web IDE - Enablement

 

Regards,

JK (@jkkansal1987)

Create a Simple Chart in Fiori SAPUI5 using Makit

$
0
0

This is a simple guide on how to add a chart in a Fiori app using the Makit library, and the example will be continued from the Fiori App given in Building SAP Fiori-like UIs with SAPUI5 in 10 Exercises. I have used Eclipse to make the app as noted in the step by step guide. The first step here is to include the makit library in your index file:

 

makit library include.JPG

 

Next go into your detail view and add the makit xml namespace to your View tag.

detail view.JPG

Following this, I have added a new IconTab into the detail view, which is in XML format. To do this insert a new <IconTabFilter> tag into the <IconTabBar> section under the closing table tag. 

icontab.JPG

This adds a new Icon tab into the view, for this example you can see I have chosen the bar-chart icon, and used the "Negative" color to have it show in red. To insert your chart use the <content> tag and place  <ma:Chart> into your content area. Here in the opening tag you include your chart dimensions, chart type, binding (via 'rows') and chart 'show' options such as total view, range selector and so on. Then the chart needs the following <ma:> tags to build it: category, value, rows, columns which should be self explanatory. the binding is set from the names included in the mock.json file, where value is displayed in curly brackets, ie. "{SoId}" and "{GrossAmount}". Place the binding in the row cells and columns to get the data from the mock.json, as shown below

chart.JPG

 

Now the chart will appear in the detail view in the added icon tab filter. You can change the chart type to Bubble, Pie, etc. to get a different output.

output.JPG

To use this chart in an example with a live data source, just change your oModel to your data source in the component.js, and adjust the binding accordingly in the views.

OpenUI5 & JSBin play well together .. but, is there even more?

$
0
0

Spoiler alert: There is!

 

After posting my blog about how easy it is to get started with web development using OpenUI5 & JSBin, I thought I'd check out existing alternatives!

 

My result: There are quite a few really good ones. Developers call them Playgrounds. Playgrounds are the newest hit for front end developers and designers. They allow us to play around with code and see the live results while also being able to interact with it. It removes all the hurdles to actually getting started with coding! I wanted to see if I could make use of those playgrounds to run OpenUI5!


So, if you like front end playgrounds and do have a preference already, check out my greenfield OpenUI5 examples to get you started very quick:

 

PlaygroundOpenUI5 Greenfield (Mobile)Is OpenUI5 officially supported?

JSBin

www.jsbin.com

jsbin.png

JSBin GreenField

YES.Thanks to DJ Adams it is.

 

Just hit "Add Library" on the left side of the menu bar and choose "OpenUI5 latest (Mobile BlueCrystal)"

JSFiddle

www.jsfiddle.net

jsfiddle.png

JSFiddle GreenField

 

JSFiddle Master Detail Sample

Not yet. There is a way to make it run, which is not intuitive.

 

Status: I proposed to add OpenUI5 to JSFiddle on Github. Please support me and up-vote it!

 

Solution: Just use the greenfield code sample.

Plunker

www.plnkr.co

plunker.png

Plunker GreenField

 

Plunker MVC GreenField

Kind of, I added the current version (1.24.5) to the packages. You can find it in the packages browser by clicking on "Find and add external libraries" on the right menu bar. Nevertheless, you'd need to add the data attributes to the script tag - which is unfortunate.

 

Solution: Just use the greenfield code sample.

 

Update:Denise Nepraunig (@denisenepraunig) published a nice greenfield MVC code example using separate files. Thanks very much Denise!

CodePen

www.codepen.io

codepen.png

CodePen Greenfield

No. Only way is to modify the HTML settings (the gear-wheel icon on the left of the HTML pane). You need to set the script tag yourself to being able to set the data attributes that are required.

 

Status: Created a support ticket to get OpenUI officially supported.

 

Solution: Just use the greenfield code sample.

 

 

What is your preferred playground and why? Try them out and let me know!

Start with the SAP Web IDE On-Premise

$
0
0

Hi all,

 

SAP has recently released the new ide, called SAPWebIDE. Actually it was fitst called River RDE (Rapid Development environmt) but this was to confusing with HANA river. My first opinion was: "How can a browser based development environment ever replace eclipse?". I could not believe this change of SAP. After I was over it, I decided to try it out. I started investigating the SAPWebIDE in my cloud trial account. I already started seeing some of the benefits, but I was still not fully convinced . The next step was to start developing a real UI5 application. Therefore I wanted to use my existing gateway service. The gateway and backend system are both On-Premise. So I didn't want to use the SAPWebIDE in the cloud for my On-Premise application. Therefore I installed the SAPWebIDE On-Premise.

 

Installation steps:

1) download the SAPWebIDE plug-in from the SAPStore

https://store.sap.com/

 

2) create a folder SAPWebIDE under your C drive. Together with the SAPWebIDE plugin you will find the SAP Dev Guide.

C:\SAPWebIDE

 

3) extract the SAPWebIDE plug-in to the new folder

 

4) download eclipse Orion

Orion

 

5) extract to the SAPWebIDE folder

 

6) Download Eclipse Director

http://www.eclipse.org/downloads/download.php?file=/tools/buckminster/products/director_latest.zip&mirror_id=324

 

7) extract to the SAPWebIDE folder

 

8) open command line

 

9) navigate to the Director folder

 

10) run the following installation command

director -repository jar:file:..//updatesite.zip!/ -installIU com.sap.webide.orionplugin.feature.feature.group -destination c:\SAPWebIDE\eclipse

 

11) execute Orion.exe

start orion.png

 

Watch the tutorial for a more detailed guide:

 

 

 

Enjoy the tutorial and in the next blog we'll connect the SAPWebIDE to our On-Premise gateway. So stay tuned!

 

Connect the SAPWebIDE On-Premise to your SAP Gateway system On-Premise

 

Kind regards,

Wouter

Connect the SAPWebIDE On-Premise to your SAP Gateway system On-Premise

$
0
0

Hi,

 

Hopefully you all have successfully installed the SAPWebIDE On-Premise. If not, follow the previous blog:

Start with the SAP Web IDE On-Premise

 

The SAPWebIDE has some really nice wizards. But if you want to use these wizards you'll need a connection to your gateway system. You'll also need this connection to deploy your application to your SAP Gateway system.

 

 

Configuration steps:

 

1) Navigate to C:\SAPWebIDE\eclipse\config_master\service.destinations\destinations

     - If the path does not exists, just create the folders manually

 

2) Create a new file without extension and call it the same as your SAP Gateway system ID

 

3) Open the created file with a texteditor

 

4) Add the following configruation

 

#ServiceDestination

Description=Gateway Description                                      <-- Description

Type=HTTP                                                                     <-- Connectiontype

TrustAll=true                                                                   

Authentication=NoAuthentication                                       <-- Authenticationtype

WebIDEUsage=odata_abap,ui5_execute_abap,dev_abap    <-- described in the SAP Documentation

Name=SYSID                                                                  <-- name of destination

URL=http\://0.0.0.0\:8000                                                  <-- host and port of SAP Gateway OnPremise

ProxyType=OnPremise                                                  

WebIDESystem=SYSID                                                   <-- system ID

WebIDEEnabled=true                                                       <-- enable destination for SAPWebIDE

sap-client=100                                                                  <-- SAP Gateway client

 

Follow this well explained tutorial for creating a destination in the SAPWebIDE:

 

 

 

Enjoy the tutorial and in the next blog we'll use this destination in the SAPWebIDE to create our custom Fiori application. So stay tuned!

Generate your custom Fiori application with SAPWebIDE On-Premise using Gateway On-Premise

 

Kind regards,

Wouter


Generate your custom Fiori application with SAPWebIDE On-Premise using Gateway On-Premise

$
0
0

Hi,

 

If everything went fine, you should have installed the SAPWebIDE On-Premise and created a connection to your SAP Gateway system On-Premise. If not, you can follow Start with the SAP Web IDE On-Premise and for the gateway connection you can follow Connect the SAPWebIDE On-Premise to your SAP Gateway system On-Premise .

 

Now we'll see one of the huge benefits of this SAPWebIDE. We'll use the wizards of the SAPWebIDE to create our Custom Fiori Application on our SAP Gateway service On-Premise. Follow the steps in our video tutorial:

 

 

Enjoy the tutorial and in the next blog we'll extend our Custom Fiori Application with a home view of tiles. So stay tuned!

Navigate between single full view and split view

 

Kind regards,

Wouter

Build a Custom Fiori Application with SAPWebIDE On-Premise

$
0
0

Hi,

 

This blog is a starting point to build your Custom Fiori Apllication with the SAPWebIDE On-Premise based on your On-Premise Gateway system.

 

First of all, why SAPWebIDE:

The SAPWebIDE has a lot of great features which are not available in eclipse and it's easy to use in the cloud. You don't need to configure any connection. One of the features of SAPWebIDE is the wizard to generate a fiori application based on your OData services. Besides the wizard it has also a wysiwyg editor. But from my opinion this has still some bugs and limitations. There are lot more features which you can find in the sap help: SAP Web IDE Developer Guide

 

Second, why On-Premise:

For my Custom Fiori Application I'm going to use my On-Premise backend system and my On-Premise gateway system. So if I only want to use my custom fiori application internally, why should I use cloud. For the cloud, I would also need the cloud connector and a cloud account. I don't want/need this overhead so therefore I want to install the SAPWebIDE On-Premise!

 

Follow the steps to build your Custom Fiori Application:

 

 

1) Install and configure the SAPWebIDE On-Premise:

 

Start with the SAP Web IDE On-Premise

 

Connect the SAPWebIDE On-Premise to your SAP Gateway system On-Premise

 

 

 

2) Generate your Custom Fiori Application:

 

Generate your custom Fiori application with SAPWebIDE On-Premise using Gateway On-Premise

 

 

 

3) Extend your generated Custom Fiori Application:

 

Navigate between single full view and split view

 

Organize your UI5 project

 

How to add the Fiori / Unified Shell

 

 

Enjoy all tutorials!

 

Our last tutorials for 2014! Happy Holidays! 

 

 

Stay tuned because 2015 will be a year filled with UI5 tutorials!

 

Kind regards,

Wouter

How To Use JSON DataBinding Without Gateway and OData

$
0
0

Hello community,

 

I describe here how to extend your copy of the function module (FM) RFC_READ_TABLE to get the result also in JSON format. On this way you have the tiny possibility to get a little bit the feeling of OData via SAP Gateway interface, e.g. if you are using an older version of an SAP AS.

 

Here I describe how to call a VBScript from JavaScript with IE 11 in edge mode.

 

With this descriptions and the COM Connector (CCo) is it now possible to realize a solution in the UI5 context. We will start with the html file:

 

<!doctype html>

 

<html>

 

  <head>

 

    <title>Table SFLIGHT</title>

 

    <meta http-equiv="Content-Type" content="text/html" />

    <meta charset="ISO-8859-1" />

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

 

    <script src="resources/sap-ui-core.js"

      id="sap-ui-bootstrap"

      data-sap-ui-libs="sap.ui.commons, sap.ui.table"

      data-sap-ui-theme="sap_bluecrystal">

    </script>

 

    <script language="JavaScript">

 

      function getData(TableName) {

 

        //-Variables----------------------------------------------------

          var wsh, pathName;

 

 

        if ("ActiveXObject" in window) {

          wsh = new ActiveXObject("WScript.Shell");

          if (typeof(wsh) == 'object') {

            pathName = location.pathname.substr(0,

              location.pathname.lastIndexOf("/"))+"/";

            pathName = pathName.slice(1);

            wsh.run("wscript.exe \"" + pathName +

              "ReadTableJSON.vbs\" " + TableName + " \"" + pathName +

              "\"", 1, true);

            wsh = null;

          }

        }

        else {

          alert("Your Browser doesn't support ActiveXObject");

        }

 

      }

 

      function Column(Text, Width) {

 

        //-Variables----------------------------------------------------

          var oLabel, oTemplate, oColumn;

 

        oLabel = new sap.ui.commons.Label();

        oLabel.setText(Text);

 

        oTemplate = new sap.ui.commons.TextView();

        oTemplate.bindProperty("text", Text);

 

        oColumn = new sap.ui.table.Column();

        oColumn.setLabel(oLabel);

        oColumn.setTemplate(oTemplate);

        oColumn.setWidth(Width);

 

        return oColumn;

 

      }

 

      function main() {

 

        //-Variables----------------------------------------------------

          var oModel, oTable;

 

        getData("SFLIGHT");

 

        oModel = new sap.ui.model.json.JSONModel();

        oModel.loadData("SFLIGHT.json");

 

        oTable = new sap.ui.table.Table();

        oTable.setTitle("Table SFLIGHT");

        oTable.setVisibleRowCount(15);

        oTable.setFirstVisibleRow(0);

 

        //-Add the columns----------------------------------------------

          oTable.addColumn(Column("CARRID", "35px"));

          oTable.addColumn(Column("CONNID", "35px"));

          oTable.addColumn(Column("FLDATE", "50px"));

          oTable.addColumn(Column("PRICE", "50px"));

          oTable.addColumn(Column("CURRENCY", "50px"));

          oTable.addColumn(Column("PLANETYPE", "50px"));

 

        oTable.setModel(oModel);

        oTable.bindRows("/SFLIGHT");

 

        oTable.placeAt("content")

 

      }

 

    </script>

 

  </head>

 

  <body class="sapUiBody" role="application" onLoad="main()">

    <div id="content" />

  </body>

 

</html>

 

As you can see it is not really the known standard. The main function gets at first the data as local JSON file via our copy of RFC_READ_TABLE from the table SFLIGHT. It loads the data, creates the table and adds the columns via an own function. I use only the set and get methods, it is better readable I think. Here now the VBScript file to get the data in JSON format:

 

'-Begin-----------------------------------------------------------------

 

  '-Directives----------------------------------------------------------

    Option Explicit

 

  '-Constants-----------------------------------------------------------

    Const RFC_OK = 0

    Const ForWriting = 2

 

  '-Sub getData---------------------------------------------------------

    Sub getData(tableName, pathName)

 

      '-Variables-------------------------------------------------------

        Dim SAP, hRFC, rc, hFuncDesc, hFunc, hTable, RowCount, i, hRow

        Dim charBuffer, charFile, FSO, F

 

      Set SAP = CreateObject("COMNWRFC")

      If IsObject(SAP) Then

        hRFC = SAP.RfcOpenConnection("ASHOST=ABAP, SYSNR=00, " & _

          "CLIENT=000, USER=BCUSER")

        If hRFC Then

          hFuncDesc = SAP.RfcGetFunctionDesc(hRFC, "Z_RFC_READ_TABLE_JSON")

          If hFuncDesc Then

            hFunc = SAP.RfcCreateFunction(hFuncDesc)

            If hFunc Then

 

              rc = SAP.RfcSetChars(hFunc, "QUERY_TABLE", tableName)

              rc = SAP.RfcSetChars(hFunc, "DELIMITER", "~")

 

              If SAP.RfcInvoke(hRFC, hFunc) = RFC_OK Then

 

                If SAP.RfcGetTable(hFunc, "DATA_JSON", hTable) = RFC_OK Then

                  rc = SAP.RfcGetRowCount(hTable, RowCount)

                  rc = SAP.RfcMoveToFirstRow(hTable)

                  For i = 1 To RowCount

                    hRow = SAP.RfcGetCurrentRow(hTable)

                    rc = SAP.RfcGetChars(hRow, "LINE", charBuffer, 1024)

                    charFile = charFile & RTrim(charBuffer) & vbCrLf

                    If i < RowCount Then

                      rc = SAP.RfcMoveToNextRow(hTable)

                    End If

                  Next

 

                  '-Write JSON file-------------------------------------

                    Set FSO = CreateObject("Scripting.FileSystemObject")

                    If IsObject(FSO) Then

                      Set F = FSO.OpenTextFile(pathName & tableName & _

                        ".json", ForWriting, True)

                      F.Write charFile

                      F.Close

                      Set FSO = Nothing

                    End If

 

                End If

              End If

 

            rc = SAP.RfcDestroyFunction(hFunc)

            End If

          End If

 

          rc = SAP.RfcCloseConnection(hRFC)

        End If

        Set SAP = Nothing

      End If

 

    End Sub

 

  '-Main----------------------------------------------------------------

    getData WScript.Arguments.Item(0), WScript.Arguments.Item(1)

 

'-End-------------------------------------------------------------------

 

With this mixture of RFC libary via CCo, VBScript and JavaScript in IE 11 you can easily simulate an UI5 environment on the presentation server, without any other server. Also it is not necessary, with the modifiaction of your copy of RFC_READ_TABLE, to have the newest AS environment.

 

001.JPG

On this way you can realize a relatively lightweight solution, to simulate OData via SAP Gateway and to use it in your UI5 environment on your presentation server.

 

Enjoy it.

 

Cheers

Stefan

Navigate between single full view and split view

$
0
0

Hi,

 

After you've generated your custom fiori application by using the SAPWebIDE you'll have a split view which contains a master and detail view. If you haven't generated your application, follow previous tutorial:

Generate your custom Fiori application with SAPWebIDE On-Premise using Gateway On-Premise

 

The SAPWebIDE will have generated something like this. A container "App.js" which will contain your master en detail views and master view and detail view:

 

sapui splitapp.png

 

Great that you can generate a splitview! But what if you want another view before the split view? What if you want a login view? Or a tile container?

 

In this tutorial I'll explain you how to achieve this. First start by creating a new view which we'll use as a tile container. So you'll have something like this:

sapui splitapp en full.png

We have a single full view and a split view with the master and detail view. Now we'll need something to connect the single fulle view and the splitview. Therefore we add a new view which will act as a container for single views. We'll place it on top of the single full view and the splitview. It will contain the "sap.m.App" component. This will enable us to connect the single full view with the splitview.

 

sapui splitapp final.png

 

We'll use the "masterApp" to embed the single full view and the splitview. The splitview will embed the master and detail view. For the real connection we'll need to configure the router component in the "component.js".

 

To see how, just follow this tutorial:

 

 

In the next tutorial we'll see how to organize your project before it is getting too big!

Organize your UI5 project

 

Kind regards,

Wouter

Organize your UI5 project

$
0
0

Hi,

 

From my own experience I found out that it's important to organize your project! It can grow fast and unstructered, even for a small application

 

This tutorial is based on previous tutorials:

 

Start with the SAP Web IDE On-Premise

Connect the SAPWebIDE On-Premise to your SAP Gateway system On-Premise

Generate your custom Fiori application with SAPWebIDE On-Premise using Gateway On-Premise

Navigate between single full view and split view

 

In this tutorial we are going to create some sub folders in the root folder of the views. We'll place the views in there related folder. It's important that you not just replace the views, but also rename them!

 

After renaming and replacing the views, you'll have to update your "component.js".

 

 

We just created a few subfolders. But you could also create subfolder in subfolder and so on... Just don't forget to change the name of your view and update the "component.js"!

 

Extend your UI5 app clean !

 

Next tutorial will be about the unified shell!

How to add the Fiori / Unified Shell

 

Kind regards,

Wouter

Viewing all 789 articles
Browse latest View live




Latest Images