Category Archives: NativeScript

NativeScript 3.0 Sneak Peek and what it entails for Plugin developers.

For those who are not aware, v3.0 of NativeScript is the next major version that will be released.  It has been being worked on for several months now as it has parts of it have been completely rewritten to enhance speed of the framework in a number of areas.    Some parts of it have undergone radical changes in design, and as such will require changes to plugins to make them compatible.

Unfortunately these changes are a breaking change and will mess up the plugins for a while...

Some pre-release information has trickled out and as such the plugin developers needs to be made aware of these changes, so we can start getting a jump on these changes...

The biggest issue is any plugins that deals with any properties, or stylers has been completely changed.   These plugins will HAVE to be changed to support 3.0.   This means your plugin will no longer be NS <= 2.5 compatible, these are BREAKING changes.

 

Plugin Sites and the Package.json

As an aside if your plugin doesn't have any breaking changes and can continue to work fine in all versions of NS; then I am asking you to add a new flag to your package.json file to flag that this plugin is 3.0 compatible but doesn't require 3.0.

Your package JSON NativeScript section should look like this:

"nativescript": {
   "platforms": {
      "android": "2.3.0",
      "ios": "2.3.0"
    },
    "plugin": {
       "nan": "false",
       "core3": "true",
       "pan": "true",
       "wrapper": "ios",
       "category": "visual"
    }
 },

The additional "plugin" structure is being introduced  to try and capture the data that has been missing from the plugin infrastructure.  At this moment each item is totally optional.   However, this will allow the plugin sites to categories and filter the plugins based on criteria's that are important to subsets of the users using the plugin sites.  Please see: http://fluentreports.com/blog/?p=489 for more details on the new "plugin" structure proposal.

 

Back to the breaking Changes

The first resource is that some of the NativeScript team produced a video last week https://youtu.be/bwO3cYPb4zQ which will give a decent overview of the changes.

The developers working on the 3.0 project gave a run down of the changes and how they benefit us and/or what changes we need to be concerned about.

The second resource, which I find to be a bit more valuable is this document that is in the source repo.  https://github.com/nativescript/nativescript/blob/master/Modules30Changes.md

They used this document in the above video; but since they only covered an overview and this documents has all the nitty-gritty details.

For this to be a smooth transition I really strongly encourage you on the "core3" attribute be used if you are not just bumping your platforms to 3.0.0.      I will be automatically filtering out plugins that I believe are only 2.0 for 2.0 mode and 3.0 for 3.0 mode.  So  having things tagged correctly will help the end users have a much more painless transition.

 

NativeScript: Plugins - Let Fix the Data!

Some of you might not be aware but I wrote the plugins.nativescript.rocks.   I also helped write the plugins.nativescript.org site (if something doesn't work on plugins.nativescript.org; please blame my cohorts in crime, Nathan Walker and George Edwards.   I had NOTHING to do with any bugs!  😛  )

Well, with the new upcoming changes in 3.0 and some data that we have been unable to determine I have decided to request that the plugin authors add a little bit more metadata to the package.json file that comes with the plugin.

So lets look at the existing "nativescript" key.

"nativescript": {
   "platforms": {
      "android": "2.3.0",
      "ios": "2.3.0"
    }
 },

This tells nativescript which version of NativeScript runttimes are supported.   This allows the TNS command line to throw and error/warning if you are not using the proper versions.   This is useful information as this tells us what platforms are supported.   However, this fails when people (like me) write dummy wrappers to support the plugin not crashing on the other platform.     On the plugins site it will say this plugin supports both Android and iOS, but in all reality the plugin only really supports iOS, and actually doesn't really do anything on Android.    I would like to have the plugins site actually reflect this reality rather than you downloading a plugin you thing works on Android and it turns out it doesn't.

In addition since Angular was introduced to the eco-system, there are a large number of plugins that actually do NOT work with NAN (NativeScript Angular) code.   And even some that don't work with PAN (Plain Awesome NativeScript) code.  In addition in the future we might get other frameworks supported like VueJS (VAN?), etc.

So I would like to start capturing the data so that we can do these additional cool things.   And so I am proposing the following additional OPTIONAL meta data to be added.

"nativescript": {
   "platforms": {
      "android": "2.3.0",
      "ios": "2.3.0"
    },
    "plugin": {
       "nan": "false",
       "pan": "true",
       "core3": "true",
       "wrapper": "ios",
       "category": "visual"
    }
 },

nan = NativeScript ANgular will be assumed to be false, unless Angular is detected in the Keywords/name/description.
pan = Plain Awesome NativeScript Will be assumed to be true.
core3 = Supports NS Core Modules 3. Will be assumed FALSE if platforms.ios/.android < 3
Will be assumed TRUE if platforms.ios/andorid >= 3.
wrapper = Using a dummy wrapper Will default to false, use "ios" or "android" to signify platform which is using a wrapper.
category This is the category to put the plugin in.   Valid categories currently are: "Interface", "Processing", "Templates", "Developer", "Utilities"

I am up for other category suggestions.   But at this point these are the primary categories that I use on plugins.nativescript.rocks.

Please note each key is optional; however, your plugin will get extra points for having an category key.  And you will LOSE points if we detect a plugin is using a wrapper and you haven't tagged it, as this is a issue the plugin users really hate seeing faulty data about the plugins support.

I would recommend plugin authors start adding this to any releases of there plugins so that we can capture the data.  This will become critical with the 3.0 release as a large chunk of plugins are not going to be compatible between NS 2 & NS 3.

NativeScript Android Snapshots

For those who haven't deployed any apps in v2.4 of NativeScript; one of the new features that is turned on by default is SnapShots.    Now most the time this is a AWESOME thing, however occasionally this can cause issues.   For example I have one app of mine that this crashes at startup when using SnapShots.

Now the docs do list how to disable snapshots; but it is a lot easier for me to find the notes on my own site than trying to figure out which doc has the info.

The environmental variable you need to adjust is: <strong>TNS_ANDROID_SNAPSHOT</strong>

  • 0 = Force Snapshots off always
  • 1 = Force snapshots on (including in debug mode)
  • Unset = Snapshots only in Release mode

Allowing TypeScript to understand NativeScripts ~/ home path

I know a wide number of you use TypeScript; well one of the irritations I've had with TypeScript -- I just figured out how to solve.   Finally did some research and tests to figure out how to make TypeScript support using ~/ as a normal path for building and determining editor intellisense since this is a special path in NativeScript meaning the home app path.   Using this path in a import / require statement means you can do something like this.

/app/views/login/login.ts ->

import * as animation from '~/support/animation'
and it will load in the file at   /app/support/animation

You can use relative paths, but I find absolute path's a lot easier to read and understand exactly which file is being loaded.   In addition things like my NativeScript-Updater can't use relative path's (do to some low level issues in the iOS runtimes) and determine if a file has been updated.

Ok, so the solution: open your tsconfig.json file and add the following:

"baseUrl": ".",
"paths": {
   "~/*": [
     "./*"
   ]
  }

To the "compilerOptions" key in the json file.

NativeScript 2.4.0 - New Features

ns-version240Some of you might have seen the all New version 2.4.0 has been released today.   This has been a release that has taken a bit of time to get right, but it is finally out!  Wooo Hoooo!!!

Some of the new features

  • NativeScript Workers
  • Per-Side borders
  • Flexbox layout
  • Android Snapshots on Release build (faster app start time)
  • Added "import" to point to the JS file
  • More pseudo selectors: button now supports: pressed, active and highlighted, and views descendants support disabled.
  • Segmented Bar now has a new css property:  selected-background-color
  • TabView now has new CSS properies: tabTextColor, tabBackgroundColor, selectedTabTextColor, and androidSelectedTabHighlightedColor
  • Some CSS properties now support % sizes:  height, width, margin-left, margin-top, margin-right, margin-bottom, margin.
  • Image Capture allows rotation.
  • Camera module now a plugin (Removes a permission)
  • Brand new Theme!
  • Reduce the size of the Android App
  • Much nicer Android crash screen
  • Faster tns prepare
  • Android has ~ 97% support for pure ES6 code.
  • Can create TypeScript typings automagically on android platform using --androidTypings command line.

Lots and lots of bug fixing in all the repo's.

Upgrading (Core):

First of all to upgrade is done is a couple steps:
> npm install -g nativescript@latest
> npm install tns-core-modules@latest --save

For Android:
> tns platform remove android
> tns platform add android

For iOS
> tns platform remove ios
> tns platform add ios

Then you can type tns info and verify that everything says v2.4.x

Common Issues:

  • iOS failing to build, older projects:  v2.4 requires you to have the Info.plist file in the app_resources/ios folder.    The simplist way to fix this is to create a new project and then replace your app_resources with the new app_resources folder.  If you have any resources you have manually added or any changes to any files make sure you copy them out before you delete the old app_resources folder.  I would highly recommend you do NOT merge them as you might get some weird behavior from the old resources in the old format vs the new resources in the newer layout.
  • iOS requires CocoaPods v1.0 or later.   This is not a NativeScript issue so much as the Cocoapod infrastructure no longer allows anything older than 1.0..
  • Android failing to build with some plugins (like NativeScript-Telerik-Ui). with the error Multiple dex files define Landroid/support/v4/accessibility
  • Android failing with snapshot error, install the nativescript snapshot support via
    npm install nativescript-dev-android-snapshot@latest --save-dev
  • TNS no longer building your TypeScript files or livesync'ing any of your TS files.

 

NativeScript - Professional post series

I've been doing NativeScript for a while; and since I'm a contractor/freelancer; and no specific company pays my salary -- I've decided to start putting some of my cool learned tips into the paid category.   Most of these will only qualify if they took me multiple hours to figure out.  Unfortunately nobody pays me for fixing things when they break...  So, if I can use my hard earned knowledge to save you a vast amount of time, what is it worth to you?
All this knowledge is time tested and can save you a vast amount of diagnostic time on why something doesn't work.   So if you think saving you time is worth it; please feel free to sign up and support me; and I will provide the information you need when you need it...
The different series are going to be available on my Patreon site: https://www.patreon.com/NathanaelA
The first series is; NativeScript Platform Differences


You might get an app running perfectly on one platform, and then wonder why it isn't working on the other.   I have started out with a cool post on several issues you might have between iOS and Android using HTTP/HTTPS.

The second series is: Troubleshooting your NativeScript
I have started this series out on dealing with Upgrading from NativeScript  to 2.4 and issues you might face.
The first post in this series deals with a specific iOS upgrading issue.
The second post in this series deal with a specific Android upgrading issue (Error starts with: Multiple dex files), when using several plugins...
The third series is: Ready to Distribute my app...  What now?
The first post in this series deals with a specific iOS Build issues...
The second post in this series deals with a specific iOS Build configuration information.
Some of these posts will be showing up in the next couple day as I have time to finish them off...
And yes; I will continue to post free useful stuff...   😉

NativeScript - Workers

ns-workersOne of the best new features in the brand new 2.4.0 release of NativeScript is WebWorkers.    For those who have seen me around in the community; you will probably all know how long I have been harassing the NativeScript Core Teams to get this done (Since Aug of 2015).  I even went so far as to create a plugin (NativeScript-WebWorkers) that allowed you to spin up more JS threads but with the major limitation that they didn't have access to the native OS side of things, they were only pure JS.    So getting real 100% NativeScript webworkers this release means I am a VERY happy camper!

The feature is fully cross platform (i.e. works on iOS and Android) and allows you to spin up additional JavaScript engines to do all your heavy lifting needs in the background.    Now obviously, the more you spin up the more memory and cpu you will use; so you want to treat them as a precious resource and only spin up those you need.   Let me re-iterate; use these for only heavy duty processes; each worker is another FULL JS engine, which takes a chunk of memory and cpu to just start and maintain.

They still have full access to the iOS and/or Android runtime just like normal.   The only difference between them and the main thread is that you do not have any valid access to the GUI or GUI elements.   You can attempt to modify the GUI, but you will crash your app as you are not allowed in even in a native app to modify the GUI outside the main thread.  Same rules apply to a NativeScript app.

The NativeScript Core Teams modeled the background threads after the web workers model.  They are created, developed and destroyed the same way as a browser web worker would be.   So lets dig in.

Everything is passed via messages between the workers and the main thread; so lets look at a sample demo:

main file

"use strict";
exports.onNavigatingTo = function(args) {
   let myWorker = new Worker('./myWorker.js');
   myWorker.onmessage = function(msg) {
     console.log("Hi I'm a message from the worker: ", msg.data);
     myWorker.terminate();  // We no longer need the worker around, so kill it.
   };
   myWorker.onerror = function(err); {
      console.log("Opps, something went wrong in the worker", err.message);
   };
   setTimeout(function() { worker.postMessage("a Cool Message"); }, 500);
}

myWorker.js
"use strict";
require("globals");
global.onmessage = function(msg) {
  console.log("Got a message form the main thread!", msg.data);
  postMessage("Worker's cool Message");
  // global.close();  // If ran, this would close the worker from inside.
};

global.onerror = function(err) {
  console.log("We can handle our own errors too", err.message);
};

Now as you can see we have two files; the first file is from the main thread it starts the new worker by doing let myWorker = new Worker([path to worker script]); this is how you start a brand new worker.   The new worker will load that JavaScript file and start it up.  Now there are some gotcha's we are going to cover on the worker side that you will want to know about.

  1. You want to require('globals'); as your first or second line.    If you do NOT require the global module, you will not have access to console, setTimeout , setInterval, and any other function you are used to using globally.   So requiring this function is pretty important for most workers.
  2. When you assign .onmessage (or .onerror if you are using it) you must assign them to the global variable.  The new version of the Android engine is enforces "use strict"; properly and having implied "this" variables is NOT allowed.  So as a habit when assigning something to the global scope; implicitly use global.
  3. All messages have a .data parameter that contains the data you sent from the other side.  When you do a postMessage({cool: "wow", I: "am"}); this will be in msg.data.cool and msg.data.I in the onmessage message.  This might catch you, but is easily fixed.  Please make sure that any objects you send across to the other side is fully serializable (i.e. no recursion, no native gui elements) ; if not it will fail unless you use some third party lib to serialize the recursive structure.
  4. Terminate() or Close() the webworker if you are no longer going to use it.  If you are planning on continuing to use it; then leave it running it is cheaper to leave it running (& not doing anything) than to terminate and restart.
  5. If you get an error message like this: Worker Error: Uncaught TypeError: Cannot read property 'prototype' of undefined this can mean it can't find the worker file that you wanted to load.  Using the tilde to say main app folder '~/path/to/worker' is the easiest way to fix it.  OR it can mean that the file that is required is doing something that is causing the worker to crash.
  6. If you see the error: Uncaught TypeError: global.moduleMerge is not a function The solution is to do a require('globals'); at the top of your worker file.

Once you understand these items, you are ready to rock and create cool background threads to do all your busy work so that your main thread never freezes again...

NativeScript Testing: Developer Days Video

I just noticed my video from my presentation was released.  This was the presentation that I did at #NativeScript Developer Day in Sept of 2016.   The subject was Testing your NativeScript app and dealt with both Unit Testing and End to End testing.

I saw a couple of "um" mistakes.    I "um" need to "um" work on "um" removing some "um"'s.  😉

Here are the questions at the end (since like an idiot, I also totally spaced about repeating them) are:
1. What about testing Angular2 NativeScript apps.
2. What about Code Coverage .

Slides Deck:
http://fluentreports.com/blog/wp-content/uploads/2016/09/NativeScript-Testing.pdf

Demo "Carder" App I wrote and used, includes all the tests:
https://github.com/NathanaelA/carder

Detailed Blog posts about this subject covering the video:
Part 1 - Unit Testing
Part 2 - End to End Testing

NativeScript Testing: End to End

 

keyboardI got to give a talk on NativeScript testing to a great group of people at NativeScript Developer Days. 20160920_190247

Despite my silly technical problems at the beginning, we managed to get back on track and I was able to present all the critical information that was needed to get everyone up and running.  I did manage to miss my last slide; so I will make sure to have all that information at the end of each of these posts.

For those who are interested in doing testing and weren't there; or those who were in the talk, and just want to get a quick refresh, or if you just prefer the information written down; then this set of blog posts is for you.   I plan on doing a multi-part series on this as I want to cover what I did in my talk in the first two blog posts; but then expand the series to show Angular Native unit testing, how to unit test controls, and how to write unit tests for the NativeScript core.

You can view the #NSDevDay video here .  You can download my slide deck from the talk here.  And you can download the entire app that I wrote for my talk, including all the tests from here.

The posts currently planned in this series are:

Now as you might have guess even though you can do a lot of tests via unit testing, there are some limitations to unit testing.  You are typically only testing pieces of the whole.  So you really need to make sure the whole app works and the code you used to tie together all the pieces works.  And this is called End to End testing.

In my book, "Getting Started with NativeScript",  I discuss using Appium, for end to end testing.   Since the point where my book was published, one of the NativeScript engineers Hristov Deshev has actually created a really neat plugin.  It actually wraps up all the same steps that I came up for in my book.  Since it is a plugin, it is way easier to use, since it handles all the configuration and installation for you.  You just type tns install appium and it will install everything you need for end to end tests.   In this case all the tests for Appium will be stored in the root /e2e-tests folder since they don't actually need to be part of the Application itself.  Appium uses Mocha (which is the primary reason why I use mocha for my normal unit tests, I like consistency.).  It also uses Chia for the Asserts; so the tests are created the exact same way as I described in the unit testing post; with only a couple minor  changes.

So lets look at your /e2e-tests/carderAppium.js test that I provided in my sample testing application:

var nsAppium = require("nativescript-dev-appium");

The first thing you will notice is that I don't require any of the code from the app; the end to end testing does not run from inside your app; it is 100% external to your app.  So, you are at this point requiring the Appium setup and control driver library that Hristov wrote to wrap the configuration complexity.

describe("Carder app tests", function () {
    this.timeout(100000);
    var driver;

    before(function () {
        driver = nsAppium.createDriver();
    });

    after(function () {
        return driver
        .quit()
        .finally(function () {
            console.log("Driver quit successfully");
        });
    });

We still use the describe; but we have to actually setup the driver (that controls the device) in the before function.  And we tear it down (or close it down) in the after function.   Then we actually do all of our tests...
it("should find the card title", function () {
        return driver
            .elementByAccessibilityId("message")
            .text().should.become('Back of Card');
});

So in the first test, what we have to do is use the driver we created in the before function; pretty much everything uses the driver.  It is the communication channel to the device being tested.   Then the command we use is .elementByAccessibilityId('message').   This command will search the iOS or Android layout for any element in the UI that has the "message" accessibility id attribute set.   Now, in NativeScript this is actually set using the automationText property.  So if you look at my main-dynamic.xml or main-page.xml file; you will see:
<Label row="1" id="message" automationText="message" text="{{ text }}" class="message" tap="scrollOff" textWrap="true"/>

Then once the driver finds this element, it looks at the .text() value and that value should become "Back of Card".   When the app starts up; the first card chosen is the "Back of Card".  So if my app is actually running properly, this test will succeed.

Lets skip to the last test; as understanding it, will explain all the other tests in between. So lets figure out how it works.   Now first thing to understand is in the carder app; the numbers, letters and pips on the card are actually using a font.  So if you were to switch to Arial as the font, the actual underlying character is a "r" for the hearts pip.  So that is why I have "r" and "q" letter used in the tests...

// 'r' is the hearts pip
var heart = 'r';
        
// Setup our xpath
var xpath =  "//"+nsAppium.xpath("Label")+"[@text='"+heart+"']";

// Lets run our checks
return driver.elementByAccessibilityId("prior")
    .should.eventually.exist
    .tap().tap()
    .elementsByXPath(xpath).should.eventually.have.length(2);

As you might have noticed we do another elementByAccessibilityId("prior") -- we are looking for the prior element which is a button in this case (xml is:
<Button automationText="prior" id="prior" text="Prior" tap="prior"/>).

Then once it exists we tap it twice.  As you can see you can keep stacking commands; so in this case we actually stacked tap twice.  This is important to know, because frequently you will want to do different tests to the same element; or multiple actions to the same element.  You can easily chain them.

Next up, we are using the elementsByXPath which searchs the UI for anything that matches the xpath and returns it.  And finally we check the number of elements found.

Appium allows you to set/get values of fields, emulate taps & gestures, act like typing in on a keyboard, or just act exactly like an end user would, and then you can verify the results.  This allows you to build complex tests for your UI that test the entire "user" exposed functionality.

Now lets go into some specific details on some of these commands that you need to be aware of in Appium and NativeScript testing.   The Appium web driver actually has a ton of different selectors; however since Appium was initially developed for the web, only a couple selectors in the Appium documentation actually work for your NativeScript mobile apps.   The two selectors you can use reliably is element(s)ByAccessibilityId and element(s)ByXpath.  "element" returns only the first element found.  "elements" (note the added 's') returns all elements found.    As discussed earlier, AccessibilityId uses the NativeScript automationText value to find item(s).

XPath actually allows you to drill down into the UI and find specific items that may have a specific hierarchy and/or certain parents.  For example; rather than search for all buttons, you can limit the search to buttons that are inside a GridLayout which is inside a StackLayout area.  However, the biggest downside with xpath is that it expects you to have the actual native android or native ios control type name.   For example; on Android the NativeScript Button class is actually using the android.widget.button.  The native class on iOS it is actually using an UIButton.   Now that makes XPath really, really hard to be cross platform test, doesn't it?     So to solve that issue; I have written a cool wrapper to help with this issue. It allows you to pass in your NativeScript class name and it will, depending on the platform you are testing against, will return the real underlying native component name.   So in this specific test case the xpath was "//" = any level of items, we aren't giving any specific parents (so find this anywhere in the layout).  Then my helper class nsAppium.xpath("Label") will give me the actual underlying UI name of a NativeScript Label component, and then finally "[@text='r']" means that element must have a "r" as the text field value.    In the case of the card it should find, the two pips on the edge of the card which should be a "r".  So this test would pass as long as the prior button worked to bring you to a King of Hearts card...

The next thing you need to be aware of in Appium is that you MUST return the driver results. You will see every one of my Appium tests does a return.   In all reality, the entire chain that we are doing is actually a promise chain.  So for the test to actually run and then pass/fail, the final result of the promise chain must be evaluated.  So ALWAYS return the promise chain, or your tests will say they passed without actually knowing for sure that it actually passed or failed.  This is CRITICALLY important you return the final promise!

The final gotcha in Appium is to know is at the top of the test file, the "this.timeout(100000);" is actually very important.  Appium can take a while to actually startup the DRIVER to communicate with the device/emulator.   And you really do not want the test to timeout (which = failure) before it actually starts running it.  So make sure at least for android, that this is a very large value...

A couple notes; Appium launching the driver can be extremely slow.  You have to wait a while before it actually appears to be doing anything.   Second; If you are using my NativeScript-LiveEdit plugin, the watcher now has a cool ability to be able to launch Appium when you hit the "a" button in the watcher window.

Now all of this can be automated and is highly recommended to be automated in something like local git hooks, or some other CI environment.   That way when you commit a change; Unless you have a beefy machine, I would recommend you set it to run on like every 3-5 commits (depending on how frequently you commit, it might be higher). Because Appium is fairly slow to get the whole test started.  At worst case I would recommend you run a Appium at least once a day, several hours before you go home...

If you need help setting up a automatic testing and/or CI environment or you would like some training, please contact me.

Resources:

 

NativeScript: iOS and xCode 8 the wonderful world of breaking changes

native8xcodeFor those who have upgraded to the all new xCode 8, you may have noticed some of the plugins breaking...     The biggest breaking change in NativeScript and xCode 8 is now things deep down in the ObjC runtime that used to be a function call are now a property.

So, for example let say you needed to access UIScreen.mainScreen.

 

 

In xCode 7 this was

var mainScreen = UIScreen.mainScreen();

in xCode 8 this is now:
var mainScreen = UIScreen.mainScreen;

Notice, it is no longer a FUNCTION call.  It is a PROPERTY.   Now how do you make this compatible so your code can run with both xCode 7 and xCode 8.

If you are developing an app; I recommend you use the helper function that Telerik added to NativeScript which they use throughout the core modules.

var utils = require('utils/utils');
var mainScreen = utils.ios.getter(UIScreen, UIScreen.mainScreen);

If you have your own plugin, then I'm going to recommend you embed my code into your own plugin...  The code is basically the same as Teleriks, but you eliminate the require call.
function iosProperty(theClass, theProperty) {
    if (typeof theProperty === "function") {
        // xCode 7 and below
        return theProperty.call(theClass);
    } else {
        // xCode 8+
        return theProperty;
    }
}

Then you use it the exact same way;
var mainScreen = iosProperty(UIScreen, UIScreen.mainScreen);

Happy NativeScripting, and hopefully you can easily get all your plugins updated shortly to support both xCode 7 & 8!