a

Thursday 13 August 2015

Unit Testing

https://mochajs.org

Assertions

Reference


  1. Include Mocha Javascript Test Framework
  2. Include assert library
  3. import mocha in the controller you want to test. for example in "index.js" you can import using require('ti-mocha');
  4. Define Tests ( you can name it as <View Name>_Test. js example "index_Test.js

var should = require('should');

module.exports = function(win) {

   describe('app.js', function() {

      describe('#myWindow', function() {

            it('Window exists', function() {
                should.exist(win);
         
            });     
        
   });
});
    // run the tests
    mocha.run();
};

4. Include and Call the Test Module from the controller you want to test . 

require('index_Test')(<PassObject>);


To Capture Results at a seperate file rather than console


var outputFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'results.json');
Ti.API.info(Ti.Filesystem.applicationDataDirectory); // To get the App Data directory
outputFile.createFile();

mocha.setup({ 
    reporter: 'ti-json',    //the reporter to use with your tests
    outputFile: outputFile, // write results to the given Ti.Filesystem.File file
    quiet: false             // if true, suppress all console logging

});


To View the Results in console

Prasads-MacBook-Pro:~ prasadkatankot$ cd /Users/prasadkatankot/Library/Developer/CoreSimulator/Devices/80F3352C-678C-49E6-9FD7-07E126DF48D5/data/Containers/Data/Application/C1588187-6C72-435D-8A76-B2BB08B0F3EA/Documents/
Prasads-MacBook-Pro:Documents prasadkatankot$ ls
51fa7aae-bc12-49d7-9222-561d6352ae42.log results.json
Prasads-MacBook-Pro:Documents prasadkatankot$ tail -f results.json


Web Content

Exercise-1

Create a Webview and Include a local HTML file

Solution


<WebView url="mytest.html" height="200"></WebView>

mytest.html (Place in Assets/Android)


<html>
<body>
<div> FROM LOCAL  </div>
</body>
</html>

Exercise-2

Change the style of Webview using CSS

Solution


<html>
<head>

<link rel="stylesheet" type="text/css" href="test.css" />

.......
..........
.............

test.css (Place in Assets/Android)

body {
    background-color: #b0c4de;

}


Exercise-3



Create a Webview and Include a remote HTML file

Solution


<WebView url="http://www.google.com" height="200"></WebView>


Exercise-4



Trigger an Event from Web View and Listen from Native

Solution


Fire Event @ Web

Ti.App.fireEvent('app:fromWebView', { message: 'Message shot from web' });

Listen @Native

             Ti.App.addEventListener("app:fromWebView", function(e) {
                Ti.API.info("Message RECD at Native , which was shot from WEB"+e.message);
          
            });
            
            


Exercise- 5




Trigger an Event from NativeView and Listen from Web

Solution

Same as above

Arrow

Exercise - 1
Create a arrow application from Studio. Verify the app from appcelerator cloud

Solution

Exercise - 2
Run it locally and access local admin

Solution
  1. Navigate to project directory from terminal / Cmd. 
  2. Give command "appc run"
  3.  http://127.0.0.1:8080/arrow

Exercise - 3
Create a Model and test API

Solution


Exercise - 4
Publish the app to Cloud

Solution






















Wednesday 12 August 2015

Local Data Storage

The App Properties module is used for storing application-related data in property/value pairs that persist beyond application sessions and device power cycles.


 Strore and Get a property
Ti.App.Properties.setString('givenName', 'Paul');
Ti.API.info('The value of the givenName property is: ' + Ti.App.Properties.getString('givenName'));

Output all the saved properties

var props = Ti.App.Properties.listProperties();

for (var i=0, ilen=props.length; i<ilen; i++){
    var value = Ti.App.Properties.getString(props[i]);
    Ti.API.info(props[i] + ' = ' + value);
}















Geolocation and mapping



a.    Configure geolocation on Android, iOS, and Mobile Web
b.    Request geolocation permissions, accounting for platform-specific requirements
c.    Obtain the user’s current location and/or continually monitor the user’s location
d.    Perform forward and reverse geocoding
e.    Add a map to your app
f.     Set map options and properties
g.    Add annotations to your map, and set annotation options and properties
h.    Enable event handling for maps and annotations



Install the Google Play Services SDK

The Google Maps v2 module uses Google Maps Android API v2, which requires the Google Play Services SDK. To install the Google Play Services SDK, launch the Android SDK Manager and select to install Google Play services.
  1. To launch the Android SDK manager:
    #If the Android SDK tools folder is in your PATH:
    android
    #If not
    <path_to_android_sdk>/tools/android
  2. After the Android SDK Manager application launches, in the Extras folder, select Google Play services, then click Install X Packages....
  3. A dialog appears confirming your selection. Accept the license and click Install to continue.

Obtain and Add a Google API Key


  1. Create a Google API project and enable Google Map Android API v2 for the project
  2. Obtain and add a Google Maps API key to your project 
  3. For the SHA-1 certificate fingerprint, use JDK keytool command to extract the SHA-1 string from either the debug certificate. For Mac, use following
<ti:app>
    <android xmlns:android="http://schemas.android.com/apk/res/android">
        <manifest>
            <application>
                <!-- Replace "PASTE YOUR GOOGLE MAPS API KEY HERE" with the Google API key you obtained -->
                <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="PASTE YOUR GOOGLE MAPS API KEY HERE"/>
            </application>
        </manifest>
    </android>
</ti:app>

Check for Google Play Services

var MapModule = require('ti.map');
var rc = MapModule.isGooglePlayServicesAvailable();
switch (rc) {
case MapModule.SUCCESS:
Ti.API.info('Google Play services is installed.');
break;
case MapModule.SERVICE_MISSING:
alert('Google Play services is missing. Please install Google Play services from the Google Play store.');
break;
case MapModule.SERVICE_VERSION_UPDATE_REQUIRED:
alert('Google Play services is out of date. Please update Google Play services.');
break;
case MapModule.SERVICE_DISABLED:
alert('Google Play services is disabled. Please enable Google Play services.');
break;
case MapModule.SERVICE_INVALID:
alert('Google Play services cannot be authenticated. Reinstall Google Play services.');
break;
default:
alert('Unknown error.');
}






Alloy

 Describe the role and proper syntax of Alloy Views, Styles, Controllers, Model, and Collections
b.    Implement the Titanium components that comprise an app's UI by using Alloy
c.    Handle user interaction and app-level events in your controllers
d.    Implement media/device queries to target Alloy styles to a specific platform or form factor 
e.    Represent your app's data in Models and Collections
f.     Bind Models and Collections to Views
g.    Save data locally via sync adapters
h.    Create an Alloy Migration and manage database versioning

Exercise - 1
Create a  GREEN (100,100)  View inside RED (50, 50) which is inside BLUE (25,25). Apply styles only using style sheet

Solution
"Label": {
width: 25,
height: 25,
color: "#000"
}, 

"#label": {
color: "#999" /* gray */
}




Exercise - 2
Apply styles using value from Global

Solution

"#label": {
color: Alloy.Globals.viewColor
}



Exercise - 3
Create three views.All views should inherit the BACKGROUNDCOLOR from global styles

Solution

"#label": {
color: Alloy.Globals.viewColor
}



Exercise - 4
Make background color as GREEN for mobileweb and RED for Android

Solution

"Label[platform=android]": {
backgroundColor: "#00f",
text: 'Android'
},

// Any Mobile Web platform
"Label[platform=mobileweb]": {
backgroundColor: "#f0f",
text: 'Mobile Web'
}


Exercise - 5

Using custom properties, assign style

Solution

"#label[if=$.args.fooBar]" : {
'text' : 'Foobar',
'color' : 'blue'
}






Exercise - 6

Use conditional statement as assign styles

Solution

Alloy.Globals.androidTall = (OS_ANDROID && Ti.Platform.displayCaps.platformHeight >= 500); 



#title[if=Alloy.Globals.androidTall]" : {

top: '25dp', // compensate for the status bar on iOS 7

font : { textStyle : Ti.UI.TEXT_STYLE_HEADLINE }

},






Exercise - 7

Creat a SQL Adapter based Model and Save

Solution

function createSQLModel(){
var title = $.book.getValue();
var author = $.author.getValue();
var isbn = $.isbn.getValue();

Ti.API.info (title+'-'+author+'-'+isbn);

var book = Alloy.createModel('library', {Title:title, Author:author,ISBN:isbn})

book.save()
}


Find the DB and query from Shell

Prasads-MacBook-Pro:~ prasadkatankot$ adb shell
root@vbox86tp:/ # cd /data/data
root@vbox86tp:/data/data # ls
training.vmware.com
root@vbox86tp:/data/data # cd training.vmware.com/                             
root@vbox86tp:/data/data/training.vmware.com # ls
cache
databases
lib
shared_prefs
d databases/                                                                  <
root@vbox86tp:/data/data/training.vmware.com/databases # ls
Titanium
Titanium-journal
appcAnalytics.db
appcAnalytics.db-journal
root@vbox86tp:/data/data/training.vmware.com/databases # sqlite3
SQLite version 3.8.6 2014-08-15 11:46:33
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open Titanium
sqlite> .tables
android_metadata  platform        
sqlite> select * from platform;
unique_machine_id|6d4312a1f3f1b78e
hardware_machine_id|6d4312a1f3f1b78e
previous_machine_id|

sqlite> 


/Users/prasadkatankot/Library/Developer/CoreSimulator/Devices/<ID>/data/Containers/Data/Application/<ID>/Library/Private\ Documents/

Prasads-MacBook-Pro:D4BE9353-828D-4EC7-8E36-B48B7E7ED4E6 prasadkatankot$ cd Library/Private\ Documents/
Prasads-MacBook-Pro:Private Documents prasadkatankot$ ls
_alloy_.sql
Prasads-MacBook-Pro:Private Documents prasadkatankot$ sqlite3
SQLite version 3.8.5 2014-08-15 22:37:57
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open _alloy_.sql 
sqlite> .tables




Exercise - 8

Creat a Properties Adapter based Model and Save

Solution


DEFINE PROPERTY ADAPTER MODEL
exports.definition = {
config: {
 columns: {
            "Title" : "text",
            "Author" : "text",
            "ISBN":"int",
            "id":"int"
        },
       defaults : {
             "Title" : "Market",
            "Author" : "Bull",
            "ISBN":345,
            "id":1
        },
adapter: {
type: "properties",
collection_name: "schools"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
// extended functions and properties go here
});

return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
// extended functions and properties go here

// For Backbone v1.1.2, uncomment the following to override the
// fetch method to account for a breaking change in Backbone.
/*
fetch: function(options) {
options = options ? _.clone(options) : {};
options.reset = true;
return Backbone.Collection.prototype.fetch.call(this, options);
}
*/
});

return Collection;
}

};





function assignProperties(){
var title = $.book.getValue();
var author = $.author.getValue();
var isbn = $.isbn.getValue();
Ti.API.info (title+'-'+author+'-'+isbn);

var book = Alloy.createModel('schools', {Title:title, Author:author,ISBN:isbn})


book.save();
}






Exercise - 9

Display Collections in a View

Solution

<Alloy>
<Collection src="library"/>
<View layout="vertical">
<TableView dataCollection="library"  id="leaves98" >
<TableViewRow height="50">
<View  layout="horizontal" backgroundColor="grey" height="50">
<Label text="{ISBN}" valsel="{ISBN}" onClick="editLeave" height="Titanium.UI.SIZE" />
<Label text="{Title}" valsel="{Title}"  onClick="editLeave" height="Titanium.UI.SIZE"  />
<Label text="{Author}"  valsel="{Author}" onClick="editLeave" height="Titanium.UI.SIZE" />
</View>
</TableViewRow>
</TableView>
</View>
</Alloy>


In corresponding controller add following


Alloy.Collections.library.fetch();



Exercise - 10

Migrate Local Database (UPGRADE)

Solution


migration.up = function(migrator)
{
 migrator.db.execute('ALTER TABLE ' + migrator.table + ' ADD COLUMN Age INT;');
};






Exercise - 11
Migrate Local Database (DOWNGRADE)

Solution

migration.down = function(migrator)
{
    migrator.dropTable();
};