Local storage using OpenUI5 and Apache Cordova - javascript

I'm building a mobile app using OpenUI5 and Cordova. This app consume OData services but must support full offline capabilities. There are many optiones to store data using Cordova such as LocalStorage, Web SQL or even FileWriter. Also I find that OpenUI5 framework offer jQuery.sap.storage to store data through LocalStorage but I can't take this option into account due to the limited storage capacity (5MB).
Is it possible to request the entire data model from the OData service and convert it into JSON model? Because if there is any way to accomplish this, I could write files for every entity in the model (and the metadata file) using the FileWriter and consume this model when the app goes offline.
Does anyone tried to do something like this?
Edited
Thanks for answering...
I'm using jumpifzero tips to set data from the OData services into the Json model, like this:
var sServiceUrl = "http://address:port/DataService.svc/";
var odataModel = new sap.ui.model.odata.ODataModel(sServiceUrl, true);
var jsonModel = new sap.ui.model.json.JSONModel();
odataModel.read("/Dates", {
async: false,
success: function (odata, response) {
jsonModel.setData({ Dates: odata.results });
}
});
this.setModel(jsonModel);

You can also read the odata for each entityset, with the .read method, without any filter. In the success function given to the read, you can put the JS objects in a JSON model.
You can make a layer that fills the JSON model from the odata when online and from localstorage when offline.

You have an option to create offline apps (CRUD) using offline Kapsel plugin (Cordova plugin developed by SAP) that comes with SAP Mobile Platform. You should buy license for SAP Mobile Platform.
You can find more information here: http://scn.sap.com/docs/DOC-58063

I don't suggest offline Kapsel plugin. It is not mature enough to use it and it is actually under development. Furthermore you would need an SMP server for offline feature.
I would rather say you should use a half-baked solution that you form according your needs e.g.: http://coenraets.org/blog/2012/05/simple-offline-data-synchronization-for-mobile-web-and-phonegap-applications/

Related

AngularJS and WebSockets beyond

I just read this post, and I do understand what the difference is. But still in my head I have the question. Can/Should I use it in the same App/Website? Say I want the AngularJs to fetch content and update my page, connecting to a REST api and all of that top stuff. But on top of that I also want a realtime chat, or to trigger events on other clients when there is an update or a message received.
Does Angular support that? Or I need to use something like Socket.io to trigger those events? Does it make sense to use both?
If someone could help me or point me to some good reading about that if there is a purpose for using both of them together.
Hope I'm clear enough. thank you for any help.
Javascript supports WebSocket, so you don't need an additional client side framework to use it. Please take a look at this $connection service declared in this WebSocket based AngularJS application.
Basically you can listen for messages:
$connection.listen(function (msg) { return msg.type == "CreatedTerminalEvent"; },
function (msg) {
addTerminal(msg);
$scope.$$phase || $scope.$apply();
});
Listen once (great for request/response):
$connection.listenOnce(function (data) {
return data.correlationId && data.correlationId == crrId;
}).then(function (data) {
$rootScope.addAlert({ msg: "Console " + data.terminalType + " created", type: "success" });
});
And send messages:
$connection.send({
type: "TerminalInputRequest",
input: cmd,
terminalId: $scope.terminalId,
correlationId: $connection.nextCorrelationId()
});
Usually, since a WebSocket connection is bidirectional and has a good support, you can also use it for getting data from the server in request/response model. You can have the two models:
Publisher/Subscriber: Where the client declares its interest in some topics and set handlers for messages with that topic, and then the server publish (or push) messages whenever it sees fit.
Request/response: Where the client sends a message with a requestID (or correlationId), and listen for a single response for that requestId.
Still, you can have both if you want, and use REST for getting data, and WebSocket for getting updates.
In server side, you may need to use Socket.io or whatever server side framework in order to have a backend with WebSocket support.
As noted in the answer in your linked post, Angular does not currently have built-in support for Websockets. So, you would need to directly use the Websockets API, or use an additional library like Socket.io.
However, to answer your question of if you should use both a REST api and Websockets in a single Angular application, there is no reason you can't have both standard XmlHttpRequest requests for interacting with a REST api, using $http or another data layer library such as BreezeJS, for certain functionality included in various parts of the application and also use Wesockets for another part (e.g. real time chat).
Angular is designed to assist with handling this type of scenario. A typical solution to would be to create one or more controllers to handle the application functionality and update your page and then creating separate Services or Factories that encapsulate the data management of each of your data end points (i.e. the REST api and the realtime chat server), which are then injected into the Controllers.
There is a great deal of information available on using angular services/factories for managing data connections. If you're looking for a resource to help guide you on how to build an Angular application and where data services would fit in, I would recommend checking out John Papa's AngularJS Styleguide, which includes a section on Data Services.
For more information about factories and services, you can check out AngularJS : When to use service instead of factory

Implementing Database in HTML5 Mobile App

I am having trouble deciding hot to implement a database for my mobile app. I am using javascript with jquery mobile and phonegap to hopefully deploy to IOS and Android. The database is basically a list of about 60-70 location names, description, latitude and longitude. I need the data to be available even if the user does not have internet access and need to perform queries such as sorting the locations by closest distance.
Is there a way to create the database file beforehand and open as needed or do I need to create the database each time when my app opens? Does the database file reside on the device even after the app is closed or does it create it again when app is restarted?
Any suggestions or examples?
Thanks,
Robert
There are several types of browser storage such as localStorage they are all built in and can be used directly.
Storage objects are a recent addition to the standard. As such they may not be present in all browsers.........The maximum size of data that can be saved is severely restricted by the use of cookies.
Code sample:
function storeMyContact(id) {
var fullname = document.getElementById('fullname').innerHTML;
var phone = document.getElementById('phone').innerHTML;
var email = document.getElementById('email').innerHTML;
localStorage.setItem('mcFull',fullname);
localStorage.setItem('mcPhone',phone);
localStorage.setItem('mcEmail',email);
}
On the other hand, localStorage might not be enough, therefore, external libraries come to hand which actually utilize the browsers built in storage and make the db works cross browsers.
1- SQL like DB sequelsphere (looks like suitable for heavy lifting!)
Code sample for query that will run directly from the browser:
SELECT empl_id, name, age
FROM empl
WHERE age < 30
2- JSON like DB taffydb (looks like suitable for every day activity!)
// Create DB and fill it with records
var friends = TAFFY([
{"id":1,"gender":"M","first":"John","last":"Smith","city":"Seattle, WA","status":"Active"},
{"id":2,"gender":"F","first":"Kelly","last":"Ruth","city":"Dallas, TX","status":"Active"},
{"id":3,"gender":"M","first":"Jeff","last":"Stevenson","city":"Washington, D.C.","status":"Active"},
{"id":4,"gender":"F","first":"Jennifer","last":"Gill","city":"Seattle, WA","status":"Active"}
]);
// Find all the friends in Seattle
friends({city:"Seattle, WA"});
3- Since you mentioned mobile, then jstorage is a cross-browser key-value store database to store data locally in the browser - jStorage supports all major browsers, both in desktop (yes - even Internet Explorer 6) and in mobile.
If you would like to have more options ->(client-side-browser-database)
The easiest would be to use localStorage.
window.localStorage.setItem("key", "value");
var value = window.localStorage.getItem("key");
If you need to store more data and have complex queries use a real Database.
Both can be found in the Cordova Docs on Storage
There is also pouch db. I use it with my Ionic App. Works great and very simple to learn and use. I use local storage only for minor temporarily used data (within a session). To persist data even when app is closed and re-opened, Pouchdb works great. By default, it's calls are async. Works well with Promises.

web services with phoneGap

I am working on project and I will implement by HTML5, javascript and I will use phonegap to give me applications in multi platforms and I have database in my server.
I know two ways to connect to my database and phoneGap accept that way :
1:Jquery Ajax requests.
like in the tutorial
http://www.indiageeks.in/phonegap-jquery-ajax-example-jsonjavascript-object-notation-response/
2:java script like in the tutorial
http://simonmacdonald.blogspot.com/2011/12/on-third-day-of-phonegapping-getting.html
but I am wondering ,,, Can I use web services on this thing ?
for example : all services will be in my server and also the database and I will connect to the web services through (html or java script or Jquery ) page and the data return in XML file and display it in the page.
Does phoneGap accept that way ?
if yes i want any good tutorials that will help me
It is a little difficult to be specific without knowing your server technology...
You can GET/POST to URLs from javascript, so yes you can access a webservice.
I have typically used MVC WebAPI projects to allow my phonegap applications to interact with the server.
WCF webservices work as well. This is a good example: http://www.codeproject.com/Articles/132809/Calling-WCF-Services-using-jQuery
You would access them in exactly the same way as you would from a normal web application, with a couple of gotchas:
You need to allow the origin within the res/xml/config.xml file, to test you can allow all origins:
<access origin="*" />
Add this tag under the widget tag.
You must enable CORS on the web server.
I would expose/consume JSON from the webservice, this is a natural serialization format for javascript based applications, with built in serialize/deserialize functions.
You can also download the output of the webservice to a file on the device using:
Download files and store them locally with Phonegap/jQuery Mobile Android and iOS Apps
You can use below method for making JSON request
var apiurl = "your url";
$.ajax({
url : apiurl,
dataType : 'jsonp',
data : {
token : Token,
key : keyuser,
method : 'method_name'
},
success : function(data) {
// here all output come and do action
console.log("data is " + data);
},
failure : function() {
console.log("error");
}
});

Consuming Web Services by AJAX directly

I'm currently developing a web-site for the public transportation system based on the Trafikanten API (http://reis.trafikanten.no/topp2009/topp2009ws.asmx)
The site has several functionalities though it's Web-Services. It is implemented done in .NET framework with SOAP format. But we need to consume it's functionalities in client side language like JavaScript to be able to display the information in web-page. Can anybody suggest some easy way to cope this scenario?
Provided you're using a LAMP stack:
I would write a PHP script using the nusoap (http://sourceforge.net/projects/nusoap/) libarary to consume the SOAP web service and return JSON to your JavaScript via an AJAX call.
Edit
It's even easier in .NET. Just right click on your project and choose Add a web service. Then you can access methods of the web service just as you would any other object. As far as using it in JS, you could implement create an ASP page that outputs the results in JSON format and then consume that using jQuery as you would with a LAMP stack. Although, with the post back abilities of ASP, you might be better off letting it do the heavy lifting in JS and consume the web services directly in your code file behind your view.
Hope that helps.
If the service doesn't support JSONP, which it probably doesn't as an ASMX service, you'll need to create a service proxy to run on your local web server. Then, use that local service to act as an intermediary that circumvents the browser's cross-domain limitation.
If you added a service reference to Top2009WS in your ASP.NET project, something like this could act as a server-side proxy for GetLines() for example:
[WebMethod]
public Line[] GetLines(int ID) {
var client = new Topp2009WS.Topp2009WSSoapClient();
client.open();
return client.GetLines(ID);
}
Then, you could call through the proxy like this on the client-side:
$.ajax({
url: 'Service.asmx/GetLines',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: '{"ID":' + 12345 + '}',
success: function(response) {
// Alerts the first result's "LineName"
alert(response.d[0].LineName);
}
});
See this post for more information on using jQuery to call the web service.
I've done it in the past as Jesse says but with .NET. I build an "composed service" or adapter service which then calls the other services. The composed service would communicate SOAP with the .NET services while your application would communicate JSON with your composed service.

Access MongoDB directly via JavaScript

is there any possibility to access and retrieve data from MongoDB directly over JavaScript form browser without backend processing?
MongoDB natively does not have a fully usable REST interface. You will need either Python based Sleepy Mongoose or Node.js based MongoDB Rest
Please see http://www.mongodb.org/display/DOCS/Http+Interface for more information.
Mongo's inbuilt REST interface is very basic & read only.
If you happen to host your database on MongoLabs, they also expose a REST API. Watch out, it's not secure, as an API key is passed with each request, but your could use it to retrieve public data through Javascript:
https://support.mongolab.com/entries/20433053-Is-there-a-REST-API-for-MongoDB-
Once you have your mongolab db setup, you can access it thru REST request such as
$.getJSON("https://api.mongolab.com/api/1/databases/your-db/collections/your-collection/?apiKey=your-key", function(json) {
//console.log( "JSON Data: " + json );
});
Not in the standard security context.
If you have a situation where you have elevated security rights (such as inside a custom browser extension) then it may become possible.

Categories