34
12/02/2015 SAPUI5 | … And All That JS http://allthatjs.com/category/sapui5/ 1/34 CATEGORY ARCHIVES: SAPUI5 Node.js on Azure calling SAP Gateway Posted on March 21, 2012 It’s hard to miss the growing excitement around Node.js, a serverside JavaScript environment, especially ever since Microsoft supports the Node.js project and even offers Node app hosting as a service on Windows Azure. I was eager to get a first handson with Node on Azure, so in this post we are going to build a Node.js app running on Windows Azure, accessing SAP business data through SAP Gateway. I decided to go for ‘the Cloud’ alltheway, so we will develop both a server and client (i.e. browser) application in JavaScript using Cloud9, a web based IDE. The browser app is based on SAPUI5. It displays a list of Sales Orders and the user can also request an overview in Excel, generated onthefly on the server. To easily work with the source code of the project, we will use a repository on GitHub. Here are screenshots of the end result: … And All That JS JavaScript, Web Apps and SharePoint

SAPUI5 Download Excel Sheet From Table

  • Upload
    age0110

  • View
    323

  • Download
    9

Embed Size (px)

DESCRIPTION

SAPUI5 download Excel sheet from TableSAPuia 5 download excel

Citation preview

Page 1: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 1/34

CATEGORY ARCHIVES:  SAPUI5

Node.js on Azure callingSAP GatewayPosted on March 21, 2012

It’s hard to miss the growing excitement around Node.js, a server­side JavaScriptenvironment, especially ever since Microsoft supports the Node.js project and even offersNode app hosting as a service on Windows Azure.

I was eager to get a first hands­on with Node on Azure, so in this post we are going tobuild a Node.js app running on Windows Azure, accessing SAP business data throughSAP Gateway. I decided to go for ‘the Cloud’ all­the­way, so we will develop both a serverand client (i.e. browser) application in JavaScript using Cloud9, a web based IDE. Thebrowser app is based on SAPUI5. It displays a list of Sales Orders and the user can alsorequest an overview in Excel, generated on­the­fly on the server. To easily work with thesource code of the project, we will use a repository on GitHub.

Here are screenshots of the end result:

… And All That JSJavaScript, Web Apps and SharePoint

Page 2: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 2/34

Page 3: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 3/34

So if you are in for some exposure to cutting edge technologies, read on! 

The players

SAP Gateway is a SAP server add­on that allows you to access  business data in SAPsystems through OData, an open web protocol for querying and updating data, built oncommon web technologies like HTTP, XML and REST.

SAPUI5 (officially known as “UI development toolkit for HTML5”) is a JavaScript library,currently in Beta, to build HTML5 apps.

Node.js is a server platform that is quickly gaining popularity. It is built on Chrome’s V8JavaScript runtime and allows you to create server applications in JavaScript. Node.jsuses an event­driven, non­blocking I/O model that makes it lightweight and efficient.

Cloud9 is a web­based IDE + node.js runtime environment offered as a service (partiallyopen sourced). In Cloud9 you can develop, debug and test node.js applications, all fromwithin your browser. Cloud9 can use a GitHub repository to manage and share the sourcecode. Once you have completed your application, you can deploy the application toWindows Azure.

Page 4: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 4/34

Windows Azure is Microsoft’s cloud platform. One of the services is hosting a Node.jsapplication in a scalable environment.

GitHub hosts source code repositories,using the Git version control system. GitHuboffers public and private repositories. To work with GitHub, you need to use Git clientsoftware.

The Big Picture

Before we go into the details, let’s sketch how it all fits together:

For development, we’ll create a code repository on GitHub. This way we can add/updatesource code and resource files both from our local machine (via Git) and on Cloud9. Wewill use the repository to add all SAPUI5 js and css files that are required to our projectfiles. In Cloud9 we use a clone of the GitHub repository. This way we can push and pullCloud9 project files in and out of the GitHub repository.

Cloud9 is a fully web­based development environment: developers use a browser toaccess the Cloud9 code editor, system command prompt, debugger, Node.js consoleoutput etc. We can run a Node.js application directly on the Cloud9 environment and usea special url to access the running server app as a (test) user.

Actually we need 2 applications: a server application which runs on the Node.js serverand acts as middleman to SAP Gateway (and possibly other data sources) and a clientapplication (HTML5, SAPUI5)  which runs in the browser, but uses html/css/js fileswhich are hosted on the server. It is important to keep these two apart, even if we developboth in JavaScript.

The client and server app interact in the following way:

DISPLAY SALES ORDERS  IN DATA TABLE

the user starts the app by requesting the server url

Page 5: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 5/34

the server sends the client application html file (index.html) which instructs thebrowser to load additional SAPUI5 resource files and the client js code.the client app starts up and creates a SAPUI5 OData Model and Data Table to fetchand display Sales Order data. The data isn’t fetched from the SAP Gateway directly(not allowed due to the Same Origin Policy). Instead, the request is sent to theserver, which forwards it to SAP Gateway. The server acts as a reverse proxy.The server passes the OData response from SAP Gateway to the browser. Here,the OData feed is parsed using SAPUI5’s built in OData support and the extracteddata is shown in the Data Table.

DOWNLOAD AS EXCEL

When the user clicks on ‘Download as Excel’ button, the client app requests aspecial url from the server.This will trigger the server to fetch the Sales Order data from SAP Gateway, parse it(but now on the server side!), convert it into an Excel format and return this to theuser. The user experience is identical to requesting a downloadable file.

Once we have the application working in the Cloud9 environment, we can requestdeployment to Windows Azure. Cloud9 will generate configuration files, package the apps,upload and deploy to Azure.

Caveats:

This demo project involves quite some platforms and services. Within the scope ofthis blog post it is not feasible to provide a very detailed, click­by­click walk­through.Instead I will refer to tutorials for the respective services which contain detailedinstructions and I will point out the main route and highlights along the way.I recommend that you use Safari, Chrome or Firefox on GitHub and Cloud9. IEsupport is lagging (GitHub) or non­existent (Cloud9).

Step 1: Create a GitHub repository

First we need to create a repository on GitHub to manage and share our source codeacross environments.

1.  Sign­up with a (free) account for GitHub. A free account let’s you create publicrepositories.

2.  Follow the instructions on Set up Git to install Git local software and set up SSHkeys

3.  Create a repository on GitHub. We’ll assume it is named: NODEJS_SAPGW4.  Clone the repository to local machine5.  Try out pushing and pulling content from your local machine into the repository until

you become familiar with the process

Here are the important Git commands you will need:

Page 6: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 6/34

I think GitHub is a great tool for developers, so I encourage you to check out the GitHubhelp center to learn more.about the other features of Git and GitHub. For our demo projectthe above commands are all we need.

Step 2: Develop on Cloud9

Now we have a repository on GitHub, we can start a project on the Cloud9 IDE.

1.  Signup on http://c9.io. It is very convenient to signup with your GitHub account.Look for the small GitHub icon.

2.  After signup, you will see your GitHub repository (I blurred out my otherrepositories):

// Clone repository$ git clone [email protected]:[yourname]/NODEJS_SAPGW.git // push contentgit add .git commit ‐m "Commit message"git push // pull contentgit pull

Page 7: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 7/34

3.  Select the repository and click ‘Clone to edit’ and select Shared Developmentserver.

4.  The Cloud9 environment will make a Clone of the GitHub repository available in yourCloud9 environment.

5.  Once the Clone is completed, you see the following screen. Click on ‘Start Editing’.

6.  This will bring you into the project environment. Create a folder called ‘Public’. Thisfolder will contain all the files required for the client application. Add the index.htmland app.js (described below) and push the changes to GitHub and pull to your localmachine. Add the SAPUI5 resources on your local working directory and push toGitHub and pull from Cloud9. All this pushing and pulling sounds like a workout, buttrust me, you’ll get the hang of it!

Client application

The client application consists of an index.html file and app.js file and uses SAPUI5 tofetch and parse OData and render a data table widget.

The index.html includes the SAPUI5 core library (which dynamically will load alldependencies), the application js file and a placeholder for the data table.

01 <!DOCTYPE html>

Page 8: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 8/34

The app.js contains the client code:

02030405060708091011121314151617181920

<html>    <head>        <meta http‐equiv='X‐UA‐Compatible' content='IE=edge' />        <title>Node.js calling SAP Gateway</title>         <script id="sap‐ui‐bootstrap"           src="resources/sap‐ui‐core.js"           data‐sap‐ui‐theme="sap_goldreflection"           data‐sap‐ui‐libs="sap.ui.commons, sap.ui.table"></script         <script src="app.js"></script>     </head>    <body class="sapUiBody">         <img src="images/sap_logo.png" />         <div id="salesorders"></div>             </body></html>

123456789

101112131415161718192021222324252627282930313233343536373839404142434445

// Let's define some shortcuts to increase// readability of the codevar ODataModel = sap.ui.model.odata.ODataModel,    TextView = sap.ui.commons.TextView,    Label = sap.ui.commons.Label,    DataTable = sap.ui.table.DataTable,    Toolbar = sap.ui.commons.Toolbar,    Button = sap.ui.commons.Button,    Column = sap.ui.table.Column,    Right = sap.ui.commons.layout.HAlign.Right,    Begin = sap.ui.commons.layout.HAlign.Begin,    SelectionMode = sap.ui.table.SelectionMode; // Specify the SAP Gateway SalesOrder service as an OData model.// Please note: we do not connect directly to SAP Gateway (no host specified)// Instead, the calls are made to the Node.js server,// which will proxy the calls to SAP GW// This way, we comply with Same Origin Policy of the browser. var salesOrderService =        "/sap/opu/sdata/IWFND/SALESORDER",     // SAP Gateway only supports XML, so don't use JSON    asJson = false,    salesOrderModel = new ODataModel(salesOrderService, asJson),    salesOrderCollection = "SalesOrderCollection"; // Create a button to request an Excel workbook from server var button = new Button({    text: "Download as Excel",    icon: 'images/excel.png',    iconFirst: false,    height: '24px',    press: function () {        window.location = "/workbook"    }}); var toolbar = new Toolbar({     items: [button]}); // Create a master table with sales orders var salesOrders = new DataTable({    title: "Sales Orders",    width: "600px",

Page 9: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 9/34

With that, our client application is in place.

Server application

Node.js includes core library functions to create an HTTP server and client. You haveprobably seen the famous 6 lines of code to create a ‘Hello world’ http server in Node.js.The core library is intentionally kept light­weight and (relatively) low­level. But is very easyto extend the base capabilities of Node by including modules in your code. The Node.jscommunity has built a wide range of modules that handle common tasks like XMLparsing, static file serving, request routing etc.

To keep our server application compact, we will use 2 of these modules:

express.js: a web application framework on top of Node, to provide request routing(connecting incoming requests to JS functions) and serving the static files (the html,js and css files for the client application).xml2js: to parse the SAP Gateway OData response into a JavaScript object

4647484950515253545556575859606162636465666768697071727374757677787980818283848586

    visibleRowCount: 20,    toolbar: toolbar,    selectionMode: SelectionMode.None,    editable: false}); // define the relevant column optionsvar salesOrderColumns = [    { header: "Sales Order ID", value: "{SalesOrderID}", width: '100px'    { header: "Customer Name", value: "{CustomerName}", width: '100%'    { header: "Net", value: "{NetSum}", width: '100px', hAlign: Right },    { header: "Tax", value: "{Tax}", width: '100px', hAlign: Right },    { header: "Total", value: "{TotalSum}", width: '100px', hAlign: Right }]; // create the columnssalesOrderColumns.forEach(function (options) {    var label = new Label({ text: options.header }),        template = new TextView({ text: options.value }),        column = new Column({            label: label,            template: template,            width: options.width,            hAlign: options.hAlign || Begin        });     salesOrders.addColumn(column);}); // connect the data table to the SalesOrder servicesalesOrders.setModel(salesOrderModel); // An OData request for the SalesOrderCollection // will return the sales orders. // Each sales order should result in a table row.salesOrders.bindRows(salesOrderCollection); // Put table in the DOM.// placeAt will automatically defer if // DOM is not ready yet (like in this demo).salesOrders.placeAt("salesorders");

Page 10: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 10/34

To install the modules in your Cloud9 project, you can use NPM (Node PackageManager). Just issue the following commands in the command field:

This will install the modules (and their dependencies) in the node_modules folder of yourCloud9 project. Click the refresh button next to Project Files and you can see the results.

Now we have the required modules installed, we can coding our server.js file whichcontains the server application code. Based on the code of our client application, theserver application needs to respond to the following requests:

/ : redirect requests without pathname (i.e. server name only) to index.html in the‘public folder/sap/*: forward (proxy) all requests for SAP Gateway content and includeauthentication/workbook: generate an Excel workbook on the fly and deliver as downloadotherwise: serve static files for the client app if contained in the ‘public’ folder

So here is server.js, the code to implement the server application

npm install expressnpm install xml2js

123456789

1011

var http = require('http'),    express = require('express'),    xml2js = require('xml2js'),    app = express.createServer(),    port = process.env.PORT; // The SalesOrder service requires authentication// get the username/password from the SCN page. var username = 'USERNAME',    password = 'PASSWORD'; 

Page 11: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 11/34

121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980

var sapgw = {  host: 'gw.esworkplace.sap.com',   // set up Basic authentication  headers: {    'Authorization': 'Basic ' + new Buffer(username + ':' + password).toString(  }} // Action: Proxy an incoming (ie. from the user's browser) request to the SAP Gatewayfunction proxy(user_request, user_response) {   // We're proxying calls,  // so copy the path from the user request  sapgw.path = user_request.url;   // Use a client request to call SAP Gateway  http.get(sapgw, function (sapgw_response) {     // Include a content type in the response header    user_response.header('Content‐Type', 'application/atom+xml;type=feed'     // In Node, http responses are streams. You can just    // pipe the response data from the Gateway to the user.    sapgw_response.pipe(user_response);  });} // Action: Generate an Excel workbook containing SalesOrders on the fly  function workbook(req, res) {   // We will fetch the SalesOrderCollection from SAP Gateway  sapgw.path = '/sap/opu/sdata/IWFND/SALESORDER/SalesOrderCollection'   // Kick‐off by fetching the SalesOrderCollection..         http.get(sapgw, function (sapgw_response) {    var xml = '';     // Every time Node receives a chunk of data    // from SAP Gateway, the 'data' event fires.    // We just collect all chunks into a string    sapgw_response.on("data", function (chunk) {      xml += chunk    });     // The 'end' event fires when the SAP Gateway response is done     // We can start processing the xml string...    sapgw_response.on("end", function () {       // Node.js doesn't automatically parse the XML (like XmlHttpRequest),      // so we need to do that explicitly.      // We will use the xml2js module to parse the XML string      // into a JavaScript object      // Create a parser to convert the XML to JavaScript object      var parser = new xml2js.Parser();       // The 'end' event fires when the parser is done.      // The resulting JS object is passed as parameter.      parser.on('end', function (result) {        // The result parameter is a complete representation         // of the parsed XML string.        // We need to extract the values we need to render the workbook        var rows = [],         // columns is the subset of properties we want to include        // in the Excel list        columns = ['SalesOrderID', 'CustomerName', 'NetSum', 'Tax         // the value of result['atom:entry'] is an array of objects, 

Page 12: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 12/34

81828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148

        // representing 's in the XML string.        // Each entry represents a SalesOrder        result['atom:entry'].forEach(function (entry) {          var row = {},            // properties points to the parsed properties             properties = entry['atom:content']['m:properties'];           columns.forEach(function (property) {            // get the value for the property            row[property] = properties['d:' + property]['#'] ||                             properties['d:' + property];          });           // add it to the rows           rows.push(row)         })         // We're done processing the response and have extracted all data required to         // create the workbook.        // First, include the proper HTTP headers        res.header('content‐disposition', 'attachment;filename=SalesOrders.xml        res.header('Content‐Type', 'application/vnd.ms‐excel');         // Next, render the contents of Excel workbook as        // Excel 2003 XML format, using the Workbook.ejs template        res.render('Workbook.ejs', {          layout: false,          rows: rows        });       });       // Set the parser in motion with the xml data received      // from SAP Gateway. The parser will turn the XML string into      // a JS object. When done, the 'end' event will fire      // and the 'end' event handler defined above will extract the values      // and render the Workbook.      parser.parseString(xml);    });   });}; // Action: perform a redirect to the home page (index.html)   function home(req, res) {  res.redirect('/index.html')} // Now we will set up the routing for the server...// Look if the request is for a static file in the public directory// this is where the client side html, css, js and SAPUI5 resources are locatedapp.use(express.static(__dirname + '/public')); // If you just call the server (root), redirect to homepageapp.get('/', home); // Requests starting '/sap/' are proxied to the SAP Gatewayapp.get('/sap/*', proxy); // Route for workbook actionapp.get('/workbook', workbook); // Routes are set up,// Now start the app server...app.listen(port); console.log('Server started on port ' + port);

Page 13: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 13/34

You can find the username/password for the SAP Gateway demo environment on thisSCN page.

The server application uses an ejs view template to generate the Excel workbook content.Express expects these views by default in the ‘views’ directory. An ejs template is a textfile interspersed with JavaScript (very similar to classic asp or jsp pages). The viewrenderer uses the template and provided parameter to output a text string, in our case theExcel content. Here’s the relevant part of the view template (rows are passed as aparameter):

Now, let’s run the application in debugging mode on Cloud9. The Output tab will show theoutput from the application initialization and any console.log statements you include in thecode. It also provides the url where you can access the running application.

123456789

101112131415161718192021222324252627

<Worksheet ss:Name="Sheet1">  <Table ss:ExpandedColumnCount="5"         ss:ExpandedRowCount="<%= rows.length+1 %>"           x:FullColumns="1"          x:FullRows="1"          ss:DefaultRowHeight="15">   <Column ss:AutoFitWidth="0" ss:Width="77.25"/>   <Column ss:AutoFitWidth="0" ss:Width="138.75"/>   <Column ss:StyleID="s67" ss:AutoFitWidth="0" ss:Width="56.25"     <Row ss:StyleID="s62">              <Cell><Data ss:Type="String">SalesOrderID</Data></Cell            <Cell><Data ss:Type="String">CustomerName</Data></Cell            <Cell><Data ss:Type="String">Net</Data></Cell>            <Cell><Data ss:Type="String">Tax</Data></Cell>            <Cell><Data ss:Type="String">Total</Data></Cell>    </Row>    <% rows.forEach(function(row){ %>        <Row>               <Cell><Data ss:Type="String"><%= row.SalesOrderID %></            <Cell><Data ss:Type="String"><%= row.CustomerName %></            <Cell><Data ss:Type="Number"><%= row.NetSum %></Data></            <Cell><Data ss:Type="Number"><%= row.Tax %></Data></Cell            <Cell><Data ss:Type="Number"><%= row.TotalSum %></Data        </Row>    <% }) %></Table></Worksheet">

Page 14: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 14/34

Click on the server url and our application opens up:

Page 15: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 15/34

Click on the ‘Download as Excel’ button and Excel workbook with the Sales Orders willopen:

OK, we now have a working application in Cloud9! There’s a lot more to explore in theIDE. For example, try the debugging options: you can set breakpoints, just like in desktopIDEs. Code execution on remote server will halt and you can explore variable andparameter values, etc. You can also push your changes to the central repository onGitHub.

Here, we will continue our Quick Tour by deploying the application we just completed toWindows Azure.

Step 3: Deploy to Windows Azure

Cloud9 makes deployment to Windows Azure very easy. This tutorial shows all the stepsin detail. You can skip the first steps because we already have a working app on Cloud9.Please start at “Create a Windows Azure account’.

After the initial set up, you can request deployment to Azure:

Page 16: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 16/34

Cloud9 will offer to create default configuration files for you. Please accept.

Deploying can take a few minutes, while the application is packaged, uploaded anddeployed on Azure:

Once deployment is active, you can click on it and see the details 

Page 17: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 17/34

The Windows Azure management tool provides full details on the deployment:

Our application is now available on Windows Azure:

Page 18: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 18/34

http://nodesapgw.cloudapp.net

You can try it! It’s live.

You’ll notice that it takes quite some time to load the page. This is mainly caused bydynamic loading of SAPUI5 resource files. Optimizations are certainly possible, butoutside the scope of this article.

This concludes our demo project to show how you can front­end SAP Gateway usingNode.js on Azure.

‘Just because you can, doesn’t mean you should’

That’s a profound adage, so let’s wrap­up with a number of suggestions  why you mayconsider front­ending SAP Gateway in the Cloud:

Provide access to multiple backend systems through a single domain (origin). Thisway, you comply with the Same Origin Policy.Integrate SAP data in an Azure based cloud solution (E.g. a hosted .Net, MS­SQLsolution)Offload non­business data http traffic of SAP Gateway to a more cost­effectiveplatform.Avoid exposing the SAP Gateway end­point to the public internetLow­latency traffic by using caching to prevent repeatedly asking the same data viaSAP Gateway. E.g. for type­ahead and suggestion/select drop­boxes in HTML5apps, low­latency response are required. This is becoming more important withmobile apps where quick selections/suggestion lists are preferred of manual input oftextsScale­out on demandProtocol conversion: you may want to build client applications using other protocols(e.g. WebSockets) to expose business data. E.g. consider real­time auctions.Content conversion: for example turning business data into Excel sheet asdemonstrated in our applicationIdentity conversion: a consumer facing web application may allow consumers tologin with their Facebook or Twitter account using OAuth2. The web application

Page 19: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 19/34

server can connect to SAP Gateway with a functional account.

Let me know if you have other suggestions/use cases.

Thanks for reading!

Helpful resources

Set up GitDeploying a Windows Azure App from Cloud9Getting started with Node.js Web Application: describes a local developmentapproach for Node.js apps on Azure using the Windows Azure SDK for Node.js.Cloud9 help pagesOverview of Node modules

Posted in Azure, GitHub, JavaScript, Node.js, OData, SAP Gateway, SAPUI5 |Tagged Azure, Cloud9, Node.js, SAP Gateway, SAPUI5 | 17 Replies

Installing the SAPUI5SDK SamplesPosted on February 27, 2012

My previous post “Getting started with SAPUI5” provides the steps required to get theSAPUI5 SDK documentation installed and ready for use on your local machine usingVisual Studio.

The SAPUI5 SDK documentation also includes lots of live code samples. To get them upand running requires some additional steps.

Installing the SAPUI5 SDK Samples

unzip HTML5Beta_complete/demokit/WEB­INF/lib/demokit­uilib­1.2.0inside the unzipped demokit­uilib­1.2.0, copy the META­INF/resources/sap/ui/demokit folder into the previously created /resources/sap/uifolder

Your SDK folder should now look like this:

Page 20: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 20/34

If you open the SAPUI5 documentation and navigate to the Controls > Button page, youshould see:

Page 21: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 21/34

Via the ‘Show Source’ link you can see and even change/re­run the source code, whichallows you to easily experiment with the configuration settings:

The SDK samples provide a good impression of the look & feel of the SAPUI5 controls.The screenshots below show some of the available SAPUI5 Controls (using the “goldreflection” theme).

CheckBox

Page 22: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 22/34

ComboBox

DatePicker

RadioButtonGroup

RatingIndicator

Page 23: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 23/34

Slider

SearchField

TabStrip

Menu and MenuButton

Page 25: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 25/34

 

More information

For more information, visit the SAPUI5 SDK developer center on SDN.

Thanks for reading!

Posted in JavaScript, SAPUI5 | 1 Reply

Getting started with SAPUI5Posted on February 23, 2012

There are some great HTML5 UI frameworks available in the marketplace: Sencha Touch,KendoUI and Twitter Bootstrap to name just a few. And now SAP has unveiled the Betaversion of SAPUI5, officially known as “UI development toolkit for HTML5”.

As a follow up on my post on Building a SAP mobile app with Sencha Touch 2, I waskeen on having a hands­on with SAPUI5. These helpful posts helped me to get started.

In this post we’ll set up the Beta version of SAPUI5 for use in Visual Studio and create ademo SAPUI5 app that fetches SAP ERP Sales Orders from SAP Gateway andcombines them with issues tracked in a SharePoint list.

Installing the SAPUI5 SDK on Visual Studio 2010

1.  Visit the homepage for SAPUI5 on SDN and download the trial version (SAPUI5beta)

2.  Unzip the downloaded file HTML5Beta_complete.zip3.  Open the folder with extracted content. Unzip ‘sapui5­static.zip’. You will need the

‘resources’ folder for development4.  Rename demokit.war to demokit.zip and unzip. This archive contains the

documentation which you can install locally.

Page 26: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 26/34

5.  In Visual Studio, create a solution and within the solution ‘Add a new web site’6.  Copy the contents of the demokit into the web site7.  Copy the resource folder of sapui5­static.zip to the web site8.  Rename index.html to default.html (the VS dev server opens default.html instead of

index.html when browsing a directory).9.  Your file/folder structure should now look like this:

10.  Now select the web site and ‘View in Browser’

You now have access to the documentation of SAPUI5:

A first test

Page 27: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 27/34

Now we have the documentation up and running, we create our first test to see if we haveall the required files.

To run this test, setup a new project or website in VS. Copy the ‘resources’ folder fromsapui5­static into the site and create the following test.html file:

The test.html file instructs the browser to load the sap­ui­core.js file which contains jQueryand also a dynamic loader which will load further required js and css files. To show thateverything loads correctly, we simply create an alert box (one of the SAPUI5 controls)when the DOM is ready.

View the test.html file in the browser and you see:

123456789

10111213141516171819

<!DOCTYPE html><html>    <head>        <meta http‐equiv='X‐UA‐Compatible' content='IE=edge'>        <title>SAPUI5 test</title>        <script id="sap‐ui‐bootstrap"           src="resources/sap‐ui‐core.js"           data‐sap‐ui‐theme="sap_platinum"           data‐sap‐ui‐libs="sap.ui.commons"&gt;&lt;/script&gt;        <script>            $(function () {                // show an SAPUI5 alert box                sap.ui.commons.MessageBox.alert("SAPUI5 ready for action.");            })        </script>    </head>    <body>    </body></html>

Page 28: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 28/34

OK, we’re all set to do something a little more exciting!

Building a demo app

Consider the following business scenario: a company is managing Sales Orders in SAPERP. To improve order fulfillment, they use a issue tracking workflow system inSharePoint. Their requirement is to see the info from SAP and SharePoint in a singlescreen. Let’s build that with SAPUI5!

We will connect to the online SAP Gateway demo system to fetch Sales Orders fromSAP ERP. Using the demo SAP Gateway system, you can try out SAPUI5 withouthaving to install/configure any server side components.

Our issue tracking list is part of a SharePoint Online site (SharePoint Online is part ofMicrosoft’s Office365 offering). Each Issue contains a field Sales Order ID which we willuse to filter. Here’s how the Issues look inside the SharePoint site:

Page 29: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 29/34

Both SAP Gateway and SharePoint are OData providers, so we will use SAPUI5’s ODatamodel to connect to the backend systems and parse the responses. Our application pagewill present three tables:

Sales Orders: the master table showing the available Sales OrdersLine items: a details table showing the line items belonging to the selected SalesOrderIssues: a details table showing the issues tracked in SharePoint related to theselected Sales Order.

This structure is already pre­defined in the body of the index.html file:

123456789

101112131415161718

<!DOCTYPE html><html>    <head>        <meta http‐equiv='X‐UA‐Compatible' content='IE=edge'>        <title>SAPUI5 demo</title>        <script id="sap‐ui‐bootstrap"           src="/resources/sap‐ui‐core.js"           data‐sap‐ui‐theme="sap_platinum"           data‐sap‐ui‐libs="sap.ui.commons, sap.ui.table"></script        <script src="app/app.js"></script>    </head>    <body class="sapUiBody">         <img src="images/sap_logo.png" >         <div id="salesorders"></div>         <div id="lineitems"></div>         <img src="images/o365_logo.jpg" style="margin:30px 0 10px 0"         <div id="issues"></div>    </body>

Page 30: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 30/34

The JavaScript of our application is contained in app/app.js.

19 </html>

001002003004005006007008009010011012013014015016017018019020021022023024025026027028029030031032033034035036037038039040041042043044045046047048049050051052053054055056057058059060061062063

// Let's define some shortcuts to increase// readability of the codevar ODataModel = sap.ui.model.odata.ODataModel,    TextField = sap.ui.commons.TextField,    TextView = sap.ui.commons.TextView,    Label = sap.ui.commons.Label,    DataTable = sap.ui.table.DataTable,    Column = sap.ui.table.Column,    SelectionMode = sap.ui.table.SelectionMode;// Specify the SAP Gateway SalesOrder service as an OData modelvar salesOrderService =        "https://gw.esworkplace.sap.com/sap/opu/sdata/IWFND/SALESORDER    // The SalesOrder service requires authentication    // get the username/password from the SDN page.    username = "[username]",    password = "[password]",    // SAP Gateway only supports XML, so don't use JSON    asJson = false,    salesOrderModel = new ODataModel(salesOrderService, asJson, username, password)    salesOrderCollection = "SalesOrderCollection";// specify the SharePoint site containing the Sales Order Issues as an OData model// we will assume there a SharePoint site called 'demo'// which has an issues list called 'SalesOrderIssues'var issueService =        "http://[SharePoint_server]/demo/_vti_bin/ListData.svc",    issueCollection = "SalesOrderIssues"  // name of SP List    issueModel = new ODataModel(issueService);// Create a master table with sales ordersvar salesOrders = new DataTable({    title: "Sales Orders",    width: "100%",    visibleRowCount: 5,    selectionMode: SelectionMode.Single,    editable: false});// define the relevant column propertiesvar salesOrderColumns = [    { header: "Sales Order ID", value: "{SalesOrderID}", width:     { header: "Customer Name", value: "{CustomerName}", width: '50%'    { header: "Amount", value: "{TotalSum}", width: '50%' }];// create the columnssalesOrderColumns.forEach(function (column) {    var label = new Label({ text: column.header }),        template = new TextView({ text: column.value }),        column = new Column({            label: label,            template: template,            width: column.width        });    salesOrders.addColumn(column);});// connect the data table to the SalesOrder servicesalesOrders.setModel(salesOrderModel);// An OData request for the SalesOrderCollection// will return the sales orders.// Each sales order should result in a table row.salesOrders.bindRows(salesOrderCollection);// Put table in the DOM.// placeAt will automatically defer if// DOM is not ready yet (like in this demo).salesOrders.placeAt("salesorders");// At this point the Sales Order master table is done

Page 31: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 31/34

064065066067068069070071072073074075076077078079080081082083084085086087088089090091092093094095096097098099100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131

// Creating the lineItems and issues table is very similar// Creating the line items datatablevar lineItems = new DataTable({    title: "Line items",    width: "100%",    visibleRowCount: 10,    selectionMode: SelectionMode.Single,    editable: false});lineItemColumns = [    { header: "Line item #", value: "{SalesOrderItem}", width: '100px'    { header: "Product Name", value: "{ProductName}", width: '50%'    { header: "Amount", value: "{NetSum}", width: '50%' }]lineItemColumns.forEach(function (column) {    var label = new Label({ text: column.header }),    template = new TextView({ text: column.value }),    column = new Column({        label: label,        template: template,        width: column.width    });    lineItems.addColumn(column);})lineItems.setModel(salesOrderModel);lineItems.placeAt("lineitems");// Create the issues datatablevar issues = new DataTable({    title: "Issues",    width: "100%",    visibleRowCount: 5,    selectionMode: SelectionMode.Single,    editable: false});issuesColumns = [    { header: "Id", value: "{Id}", width: '30px' },    { header: "Title", value: "{Title}", width: '40%' },    { header: "Status", value: "{IssueStatusValue}", width: '10%'    { header: "Comments", value: "{Comments}", width: '50%' }]issuesColumns.forEach(function (column) {    var label = new Label({ text: column.header }),        template = new TextView({ text: column.value }),        column = new Column({            label: label,            template: template,            width: column.width        });    issues.addColumn(column);});issues.setModel(issueModel);issues.placeAt("issues");// The three data tables are ready!// Now we need to define what should happen when// the user selects a row in the sales order (master) tablesalesOrders.attachRowSelect(function (event) {    var Filter = sap.ui.model.Filter,        FilterOperator = sap.ui.model.FilterOperator,        selectedRowContext = event.getParameter("rowContext"),        selectedSalesOrderID = salesOrderModel.getProperty("SalesOrderID"        selectedSalesOrderLineItems = selectedRowContext + "/salesorderlineitems"    // load the line items for the selected sales order    lineItems.bindRows(selectedSalesOrderLineItems);    // create a filter based on sales order ID    var filter = new Filter("SalesOrderID", FilterOperator.EQ, 'SO:'    // load the issues table using the filter    issues.bindRows(issueCollection, null, [filter]);});

Page 32: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 32/34

Now, fire up your Chrome browser with the “disable­web­security” command line. This willsuppress the Same Origin Policy which normally doesn’t allow you to do XHR requestacross domains:

Now you can view index.html in Chrome:

We have just build our first mash­up of SAP ERP and SharePoint data using SAPUI5!

Page 33: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 33/34

Themes

SAPUI5 provides a number of themes. The theme used in this example is called‘sap_platinum’. You can find other themes in the /resource/sap/ui/*/themes folders. Hereare screenshots of the same page using the other themes (click the images to enlarge):

Theme:sap_goldreflection Theme: sap_ux

Theme:sap_hcb Theme: base

My first impressions on SAPUI5:

Offers a comprehensive set of UI widgets and layouts

Huge code base. Definitely not a micro­framework  .Amazingly little code is required to get a demo app with OData sources describedabove up and running.Includes jQuery (version 1.4.4. included in sap­core­ui.js)Includes datajs.js(OData library by Microsoft)Style and idiom is a bit verbose and seems to be influenced by Java. This may be apro or a con, depending on where you are coming from.

Overall SAPUI5 is a very interesting entrant in the marketplace and sure to further boost

Page 34: SAPUI5 Download Excel Sheet From Table

12/02/2015 SAPUI5 | … And All That JS

http://allthatjs.com/category/sapui5/ 34/34

the position as HTML5 as UI platform.

I hope this post is helpful in starting to explore the SAPUI5 Beta yourself.

Thanks for reading!

UPDATE (Oct 2012): SAPUI5 now includes mobile controls. See comment below fromRuben.

Posted in JavaScript, SAP Gateway, SAPUI5 | 33 Replies