HTML5 database storage (SQL lite) - few questions - database

Hy there,
I can't find enough beginner resources on the web about HTML5 database storage usage examples (CRUD)
I'm opening(creating) my DB like this:
var db;
$(document).ready(function()
{
try
{
if (!window.openDatabase) {
alert('Not Supported -> Please try with a WebKit Browser');
} else {
var shortName = 'mydatab';
var version = '1.0';
var displayName = 'User Settings Database';
var maxSize = 3072*1024; // = 3MB in bytes 65536
db = openDatabase(shortName, version, displayName, maxSize);
}
}
catch(e)
{
if (e == 2) {
alert("Invalid database version.");
} else {
alert("Unknown error "+e+".");
}return;
}
});
QUESTION 1: How many databases can i create and use on one domain?
QUESTION 2. How to delete (drop) a database. -> i have not figured this out yet.
To create sql queries you use transaction:
function nullDataHandler(transaction, results) { }
function createTables(db)
{
db.transaction(function (transaction)
{
//first query causes the transaction to (intentionally) fail if the table exists.
transaction.executeSql('CREATE TABLE people(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL DEFAULT "John Doe", shirt TEXT NOT NULL DEFAULT "Purple");', [], nullDataHandler, errorHandler);
});
}
QUESTION 3: How so is the above transaciton failed if a table exists? Is the nullDataHandler involved to do this? Where on the web is there documentation explaining the executeSql API? Arguments?
thx

The spec you're looking for is Web SQL Database. A quick reading suggests:
There is no limit, although once your databases increase beyond a certain size (5MB seems to be the default), the browser will prompt the user to allow for more space.
There is no way, in the current spec, to delete databases.
The executeSql() function takes an optional error callback argument.
HTML5 Doctor also has a good introduction.
Going forward, though, I'd recommend looking at Indexed DB. Web SQL has essentially been abandoned since there is no standard for SQL / SQLite. Even Microsoft has endorsed Indexed DB. See Consensus emerges for key Web app standard.

CREATE TABLE IF NOT EXISTS table_name
will create a table table_name only if if does not exist.

I found the following WebSQL tutorials helpful for basic CRUD operations, as they contained examples, and explained what the code was doing:
A Simple TODO list using HTML5 WebDatabases
HTML5 Web SQL Database
And the following links for SequelSphere (an HTML5 JavaScript SQL Relational Database Alternative to WebSQL that works in all browsers, storing data in LocalStorage and IndexedDB):
SequelSphere basic Usage instructions
API Documentation
Full Index of Guides and Helper Documentation

Using PersistenceJS there is a persistence.reset API which will wipe the database clean.
PersistenceJS Site
For developing / testing purposes, you can view content and delete webSQL, IndexedDB, cookies, etc by searching for your domain name at this URL in Chrome:
chrome://settings/cookies
There, you can delete all the storage for a domain or just certain local storage entities. Yes, the URL implies just 'cookies', but the interface at this URL includes all types of offline storage.
It would be great I think if the Chrome developer tools interface had the ability to right-click and delete a data storage entity in the Resources tab along with inspecting the content. But for now, all I know of is the settings/cookies URL.

It is supported on iOS safari,chrome and some latest version of opera....it's not yet adopted by IE and Firefox that's it......what more one can ask than local db on browser which has relational db system...so u can query it easily and handle complex data....which is very tougher in key vale based systems..
I remember reading it even supports upto one gb.i am not sure....
Note:
1)I'd like to mention one point there is a IDE called Dashcode which let's u build web apps that looks like iOS native.even there also web SQL is used.
2)actually web SQL is a implementation of SQLite on browsers.
3)SQLite is most prefered in both iOS and android as db for native code..
The drawbacks of SQLite:
The Lack of concurrency support but which is not a problem in browser as it's gonna be used by single user at a time..this is a case also in mobile.
Conclusions:
Web Sql is abandoned by w3 that's a sad thing so we've to explore other options.

Related

What are the differences between mobiledata and cloudant services?

hello I am analyzing these two services to use In my app, and I could not find some doc about the difference between these two services. I know that mobiledata extends the cloudant, but what are the pro and cons? In my case I need to have more control above the data, for example create views (I could not create In mobiledata service) etc
So, do you know what the main divergences between these two services? When to use mobile data or cloudant?
Thanks
There are three ways to use Cloudant on Bluemix from an iOS application:
Use Cloudant directly by adding it as a service to your application.
Use MobileFirst for iOS, the Data part specifically (currently beta).
Use the Mobile Data cross-platform SDK.
(1) and (2) allow you to use views within Cloudant by adding them
via either the Cloudant dashboard or by using the Cloudant HTTP API.
(3) is a service which uses Cloudant in the background, but provides
no direct access to your data using the Cloudant HTTP API; you're
limited to the services exposed by the SDK. Therefore you can't use
many Cloudant features like views or Cloudant Query. Think of
Cloudant more as an implementation detail here, rather than an
exposed component as it is for (1) and (2).
Therefore, (1) or (2) is probably more suitable for your needs as
you mention wanting to use views.
Backend of mobile data service of bluemix is cloudant.For details please refer below link on getting started:
https://www.ibm.com/developerworks/cloud/library/cl-rapiddev-app/
http://www.techrepublic.com/blog/the-enterprise-cloud/managing-your-databases-in-the-cloud-how-cloudant-does-it/
https://www.ibm.com/developerworks/cloud/library/cl-rapiddev-app/
P.S- Cloudant is no-sql(create view wont be supported) DBAAS
For details on no-sql,please follow below link:
http://www.zdnet.com/article/what-is-nosql-and-why-do-you-need-it/
Cloudant is the IBM bluemix mobile data backend. And yes you can build sorted secondary key:value indexes, called "views" using JavaScript MapReduce functions.
Here is an example :
map: function(doc){
if (doc.rep){ emit({"rep": doc.rep}, doc.amount); }
}
reduce: _sum
For more details you can refer these links :
http://examples.cloudant.com/sales/_design/sales/index.html
http://examples.cloudant.com/sales/_design/sales/index.html#basic
http://examples.cloudant.com/whatwouldbiebersay/_design/whatwouldbiebersay/index.html
For mobiledata cloudant is acting behind the scenes. Cloudant is an open source
non-relational, distributed database service of the same name that requires zero-configuration.
Cloudant is based on the Apache-backed CouchDB project and the open source BigCouch
project.
Please follow below link for more details:
https://cloudant.com/cloudant-ibm-bluemix-tutorials-and-demos/

Authentication with AngularJS - NodeJS

I cant figure out how to do a simple Authentication in my AngularJS app.
What would be the best and easiest way to do a normal server side authentication with my Setup:
Yeoman angular generator, running grunt server on :9000.
Does anyone have a good tutorial? or any tips?
Another question, what is the simplest way to store data with this setup? using MongoDB?
Thank you :)
AngularJS is a front-end JavaScript framework, you can use anything of your choice, loving and knowing at the back-end for your application. This question was something like you are asking "I am using HTML5, what should I use at my back-end?" Angluar can be used with many server-side languages, viz. Ruby, Node, PHP.
There is an awesome tutorial talking about Ruby on Rails + Angular by David Bryant Copeland.
If you want to use PHP, you could use any framework which comforts you, there are many
available. CodeIgniter is one of the popular PHP framework.
If you want to use Node for your application, Passport.js could
be something of interest. MEAN Stack is the new thing which is coming up, MEAN stands for MongoDB + Express.js + Angular.js + Node.js. There is a ready Yoeman generator for MEAN stack available.
Again depending upon the requirement you should choose between SQL or NoSQL database. Also depends upto certain extend on the choice of the server-side language.
If you need a scalable database which stores hierarchical data, NoSQL should be your choice. MongoDB is a popular NoSQL database; CouchDB, RethinkDB are other alternatives.
SQL database are used where application needs high transaction. Though we can use NoSQL database for transaction based application, but it is not stable in comparision to SQL databases. MySQL is the most commonly used SQL database.
Angularjs is really not involved in the authentication process.
The basic flow of authentication is quite simple:
You make a post request from your 'Angularjs app' (your client side application) to your server, passing as parameters a pair of username/password.
Then, on your nodejs application (server side) you query your database looking for the username provided and you try to match the password that was sent within the post request with the password you have stored in your database related to that user. If they matches, you set up a cookie on user's client which is related to a session stored in your database.
To make this simpler there are some libraries that help you.
You could use passport.js (http://passportjs.org/) together with express (http://expressjs.com/). Passport will help you setting up with ease the authentication process in a safe way and express will give you tools like the cookie parser, support for session and other tools you will need to use. Express will help you also setting an endpoint where you will post the request for logging in to.
Last thing, for storing data, you can use any database you want.
Nodejs has a relevant number of third party libraries that help interfacing with databases. If you want to use mongodb, this library (https://github.com/mongodb/node-mongodb-native) will make your life easy.
Your best bet would be to use the angular-fullstack generator as it comes with basic authentication -- both local and oAuth -- built in. From there, you can either just use the authentication that is setup for you or you can use it as a reference to help you figure out how its all working.
The easiest setup I am using is:
NodeJS / Express / Passport / Socket.io / MongoDB (can be anything else actually)
AngularJS
Express is handling all the security with Passport (there's a passport method being added to express req automatically that gives you an ability to check whether user is authenticated or not). It's called isAuthenticated and you can use it like below:
function loggedOnly(req, res, next) {
if (req.isAuthenticated()) {
next();
} else {
res.redirect('/');
}
}
Route / & /login are public, but when user is logged in, they redirect to /app.
Route /app is Angular app which is private and redirects to /login when user is not authenticated.
app.get('/', anonOnly);
Socket.io has passport.socketio middleware for automatically refusing unauthorised connections that may occur.
Then, I access user object by doing the following:
io.on('connection', function(socket) {
var user = socket.conn.request.user;
});
To sum up, login logic is handled by static Express views. Moreover, Express prints few constant's to Angular app containing e.g. userData. Quite useful for displaying e.g. userName at some point.
Although it may take some time to set that up, it's definitely worth doing if you want to understand the whole logic of your app. I've given you the names of open-source packages to use, all the details can be found in their readme & guides (lots of them already exists if you google for a while).

Which Database Can be Used With Chrome Extension

I am trying to create a Google Chrome Extension which Needs to store Data from users for login authentication. Can you please advise me which Database I can try to have with the app? I already tried the SQLite but I am not sure that end users can update the tables by inserting or deleting rows? I also saw some posts about Web Databases but didn't find any thing really useful for it! now my question is:
1- Is SQLite capable to be updated by end users(While eht do not have SQLite on their Machine?)
2- If not, what kind of Secure database I can use instead?
Thanks,
In an extension you can use webDB (apps cannot, however), indexedDB, localStorage and/or the chrome.storage api. The later has the added bonus of not being visible if an end user figures out how to inspect your extension with devtools. If you're worried about credentials being stored as plain text, you can always find a js crypto Implementation somewhere.
This seems like a repeat of the question : Connecting to DB from a Chrome Extension?.
It basically says you should use an intermediary webapp for db calls, and use AJAX to communicate between the chrome extension and that app.

Azure MobileServices Live/UAT/Dev environments

I have an azure mobile service that will go live at some point. So I need to create UAT and dev versions which would point to the UAT and dev databases. What I am struggling with is how to create these.
The namespace in my live, UAT and Dev databases need to be the same but if I create a new mobile service called myAppName_UAT, it's going to want to use MyAppName_UAT as the namespace and so will not find any of the tables.
Has anyone overcome this problem? Once the product goes live I'll need to be able to test the mobile apps against the Dev db without affecting live which surely must be a common scenario?
Any advice would be very gratefully received.
Edit: What I'm specifically after is how to manage the multiple environments within the Azure Portal. I can deploy all the other components of my UAT environment but I'm stuck on the mobile service.
I am not asking for a way for my applications to switch config files or to migrate data between databases. Does anyone have any experience of running azure applications with multiple components where they ran multiple mobile services?
Do you use a Version Control? For me, you just need to create branches to separate the 'UAT' and 'dev' versions.
About the databases:
You can use web.config transformations to switch the connection string between your databases.
http://msdn.microsoft.com/en-us/library/dd465326.aspx
How do I use Web.Config transform on my connection strings?
=================================================================================
Update:
Ok, now I understood what you want.
Create your two versions of mobile services:
1-Log in Windows Azure Management Portal (http://manage.windowsazure.com)
2-Create your test mobile services (if you already have then, skip this step):
2.1- New -> Compute -> Mobile Services
2.2- Url - MyMobileServicesTest
2.3- Database -> Create a new (test db).
3-Create your production mobile services (if you already have then, skip this step):
2.1- New -> Compute -> Mobile Services
2.2- Url - MyMobileServicesProduction
2.3- Database -> Create a new (production db).
Right now, you have two different versions.
Using Windows Azure SDK:
//public static MobileServiceClient MobileService = new MobileServiceClient(
// "AppUrl",
// "AppKey"
//);
Pay attention: AppUrl will be "MyMobileServicesTest.azure-mobile.net/" or "MyMobileServicesProduction.azure-mobile.net/". The app key, each environment will have it's own. You can store this settings in a config file and switch according to what you are doing.
More information:
http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-data-dotnet/
Multiple mobile services can share the same database. You only need to specify the same schema name in web.config in each mobile service:
<appSettings>
<add key="MS_MobileServiceName" value="MyAppName" />
</appSettings>
Updated:
The setting above only works in localhost, but not after publishing to live.
Need to do the following trick in order to make it work. Just hard code the schema name into function OnModelCreating. This way the database schema name will not depend on the mobile service name any more:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
string schema = "MyAppName"; // ServiceSettingsDictionary.GetSchemaName();
if (!string.IsNullOrEmpty(schema))
{
modelBuilder.HasDefaultSchema(schema);
}
modelBuilder.Conventions.Add(
new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
"ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
}

A/B Test solutions for a locked source code environment - server side decides which user gets which variation

I've been previously using tools such as Google Website Optimizer to run multi-variation or A/B tests. However right now I am looking for a solution that works for a larger site (400-500 000 unique visitor per month) with a very locked down source code environment. Basically:
The site is balanced over several servers
All code that is to be released on any of those servers must go via version control, unit testing and acceptans testing. All releases must be signed by develop, sys-admin and test executive.
This means that I am not allowed/it's hard to add "new code" (even if it's tested and verified) via Google Website Optimizer or any other of the GUI-paste-your-new-variation-here type of solutions.
We can however on server side decide which users gets which variation. Basically we can push the new version on X of the servers making 10-30% of the users view it for their entire session. The question is: Which tools do we use to measure "success" (i.e improved conversion rate). My idea so far has been:
Tag the new version in Google Analytics using a session variable (and then make reports based on segment) (similar to what is described on http://searchengineland.com/how-to-analyze-ab-tests-using-google-analytics-67404 )
Use Optimizely which has API support:
window.optimizely = window.optimizely || [];
window.optimizely.push(['bucketUser', EXPERIMENT_ID, VARIATION_ID])
What solutions have you tried for locked-down environments? Am I missing some obvious solution?
The site is in .NET/Episerver on IIS.
Regards,
Niklas
You could use the AB-testing capability built into EPiServer CMO.
We ended up going with Google Analytics and adding a session variable such as "abtest" with value "variation-4" and publishing it on certain nodes. It worked fairly well, with some limitations, namely that google analytics funnels doesn't have segment support.
We did something similar and we have found Google Analytics documentation confusing. In the end the following code (made by server) got the work done for us:
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-xxxx-xxxx', {
'custom_map': {'dimension1': 'abTestDesign'}
});
gtag('event', 'abTestDesign_dimension', {'abTestDesign': 0, 'non_interaction': true});
</script>
This code is generated by the server, where the last JS line is either that one of
gtag('event', 'abTestDesign_dimension', {'abTestDesign': 1, 'non_interaction': true});
Seems to be working fairly well on Numbeo.com

Resources