Ionic2 Frequent Errors & Solutions

  1. Application Error: “The connection to the server was unsuccessful. (file:///android_asset/www/index.html)”
    Solution 1: Try to add this below line to config.xml
    <preference name="loadUrlTimeoutValue" value="700000" />

  2. Uncaught (in promise): TypeError: Cannot read property ‘name’ of null
    Solution 1:

Publishing your app when using IonicFramework

Now that we have a working app, we are ready to push it live to the world! Since the Ionic team already submitted the Todo app from this guide to the app store, chances are you’ll want to follow this chapter with a new app that you make on your own.

So first, we need to generate a release build of our app, targeted at each platform we wish to deploy on. Before we deploy, we should take care to adjust plugins needed during development that should not be in production mode. For example, we probably don’t want the debug console plugin enabled, so we should remove it before generating the release builds:

$ cordova plugin rm cordova-plugin-console

Android Publishing

To generate a release build for Android, we can use the following cordova cli command:

$ cordova build --release android

This will generate a release build based on the settings in your config.xml. Your Ionic app will have preset default values in this file, but if you need to customize how your app is built, you can edit this file to fit your preferences. Check out the config.xml file documentation for more information.

Next, we can find our unsigned APK file in platforms/android/build/outputs/apk. In our example, the file wasplatforms/android/build/outputs/apk/HelloWorld-release-unsigned.apk. Now, we need to sign the unsigned APK and run an alignment utility on it to optimize it and prepare it for the app store. If you already have a signing key, skip these steps and use that one instead.

Let’s generate our private key using the keytool command that comes with the JDK. If this tool isn’t found, refer to the installation guide:

$ keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

You’ll first be prompted to create a password for the keystore. Then, answer the rest of the nice tools’s questions and when it’s all done, you should have a file called my-release-key.keystore created in the current directory.

Note: Make sure to save this file somewhere safe, if you lose it you won’t be able to submit updates to your app!

To sign the unsigned APK, run the jarsigner tool which is also included in the JDK:

$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore HelloWorld-release-unsigned.apk alias_name

This signs the apk in place. Finally, we need to run the zip align tool to optimize the APK. The zipalign tool can be found in/path/to/Android/sdk/build-tools/VERSION/zipalign. For example, on OS X with Android Studio installed, zipalign is in~/Library/Android/sdk/build-tools/VERSION/zipalign:

$ zipalign -v 4 HelloWorld-release-unsigned.apk HelloWorld.apk

Now we have our final release binary called HelloWorld.apk and we can release this on the Google Play Store for all the world to enjoy!

(There are a few other ways to sign APKs. Refer to the official Android App Signing documentation for more information.)

Google Play Store

Now that we have our release APK ready for the Google Play Store, we can create a Play Store listing and upload our APK.

To start, you’ll need to visit the Google Play Store Developer Console and create a new developer account. Unfortunately, this is not free. However, the cost is only $25 compared to Apple’s $99.

Once you have a developer account, you can go ahead and click “Publish an Android App on Google Play” as in the screenshot below:

New google play app

Then, you can go ahead and click the button to edit the store listing (We will upload an APK later). You’ll want to fill out the description for the app. Here is a little preview from when we filled out the application with the Ionic Todo app:

Ionic Todo

When you are ready, upload the APK for the release build and publish the listing. Be patient and your hard work should be live in the wild!

Updating your App

As you develop your app, you’ll want to update it periodically.

In order for the Google Play Store to accept updated APKs, you’ll need to edit the config.xml file to increment the version value, then rebuild the app for release.

10 Best Node.js Frameworks For Developers

Best Node.js Frameworks for 2015_630

With the coming of Node.js, JavaScript has come to the forefront. It is bound to happen since it is already a well-known programming language used by developers in browsers. And, with Node.js, it has found a way to server-side implementation thus reducing the complexity of using two different languages at both ends. Today, Node.js offers one of the most innovative solutions to building servers and web/mobile applications. Its single-threaded event looping and asynchronous, non-blocking input/output processing feature distinguishes it from other runtime environments. Its scope is rapidly increasing with valuable contributions from the developer community and other technology giants. Right now, several performance-driven frameworks are being developed using primary principles and approaches of Node.js. These frameworks have extended the functionality of Node.js to a considerable extent and have also built newer features.

Today, frameworks like Express.js and Hapi.js are gaining prominence for designing better websites and mobile applications. Hence, it has become important to embrace the latest innovations that are being brought into the tech world by these Node.js frameworks. With this intention in mind, I decided to compile a list of popular Node.js frameworks and their useful applications. I am presenting a list of 10 Best Node.js Frameworks, which are currently redefining the application development field.

1) Hapi.js

Hapi.js is a powerful Node.js web framework for building application program interfaces (APIs) and other software applications. The framework has a robust plugin system and numerous key features, including input validation, configuration-based functionality, implement caching, error handling, logging and more. Hapi.js is used for designing useful applications, such as Postmile, a collaborative list making tool. Besides, it is used for providing technology solutions by several large-scale websites, such as Disney, Concrete, PayPal, Walmart and more.

2) Socket.io

Socket.io is a Node.js server framework for building real-time web applications. Being a Javascript library, it allows event-driven, bidirectional communication between web clients and server. Socket.io works as a client-side library running in the browser and as a server-side library for node.js. The framework allows real-time concurrency for document collaboration and data exchange. Moreover, its key features also includes asynchronous input/ output (I/O) processing, binary streaming, instant messaging (‘Hello World’ chat application) and more.

3) Express.js

Express.js is one of the most essential web frameworks for Node.js. It is a minimalist framework for building a host of web and mobile applications as well as application programming interfaces (APIs). A lot of popular applications and websites like MySpace, Geekli.st, Klout, Segment.io and Yummly are powered by Express.js. Express.js is offers various features, like template engines, simplified multiple routing, database integration and more.

4) Mojito

Mojito is a JavaScript framework based on Yahoo! Cocktails, a mobile application development platform introduced by Yahoo! Developer Network. JavaScript is the only programming language which is used for Yahoo! Cocktails Platform. Since, client and server components are both written in JavaScript, Mojito can run on both the client side (browser) and the server (Node.js).
Mojito is a model-view controller (MVC) framework offering a gamut of features, such as

  • Convenient data fetching.
  • Local development environment and tools (Yahoo! independent stack).
  • Integrated unit testing.
  • Library for simplifying internationalization & localization.

5) Meteor

Meteor is an open-source, model-view controller (MVC) framework for building websites and web/mobile applications. The framework supports OS X, Windows and Linux. It allows writing both client and server parts of an application in JavaScript. Meteor’s in-built set of pre-written, self-contained modules makes writing application codes. Moreover, its reactive programming model allows creating applications using lesser JavaScript code. Besides, Meteor is a powerful framework for building real-time applications. Popular applications built using Meteor are Respondly (a team collaboration app), Blonk (Job search mobile App) and more.

6) Derby

Derby is a model-view controller (MVC) JavaScript framework for both client-side and server-side. It is ideal for creating real-time mobile and web applications. Derby’s Racer, a real-time data synchronization engine for Node.js allows multi-site, real-time concurrency and data synchronization across clients and servers. By leveraging ShareJS, Racer optimizes conflict resolution algorithm and allows real-time editing within an application. Moreover, server rendering is one such feature of Derby that allows fast page loads, search engine support and HTML templates to render in the browser or on the server.

7) Mean.js

Mean.js is a full-fledged JavaScript framework to build web applications using NoSQL database, MongoDB as well as Angular.js for the front-end and Express.js/Node.js for the backend (server). It also leverages the Grunt tool to enable automated testing. Mean.js and Mean.io are both considered a part of Mean stack. Mean stands for MongoDB, Express.js, Angular.js and Node.js. Ziploop is one example of a popular mobile application used for shopping which is designed using Mean stack.

8) Sails.js

Sails.js is one of the most popular real-time frameworks around for building Node.js applications. Sails.js offers a model-view controller (MVC) pattern for implementing data-driven application programming interfaces (APIs). The framework has gained ground for building real-time chat applications, dashboards and multiplayer games. It uses Waterline for object-relational mapping and providing database solutions. Sails.js is built on top of Node.js and uses Express.js for handling HTTP requests. It is ideal for creating browser-based applications as it is compatible with all the Grunt modules, including LESS, SASS, Stylus, CoffeeScript, Jade, Dust, and more. Sails.js supports any front-end approach, such as Angular, Backbone, iOS/ObjC, Android/Java or anything else.

9) Koa.js

Koa.js is a powerful server framework for Node.js to build efficient web applications and application programming interfaces (APIs). Koa.js efficiently uses generators to efficiently deal with call backs and increase error-handling capabilities. This also improves readability of the application.

10) Total.js

Total.js is one of the modern and modular Node.js frameworks supporting model-view controller (MVC) software architecture. It is fully compatible with various client-side frameworks, like Angular.js, Polymer, Backbone.js, Bootstrap and more. Total.js is fully extensible and asynchronous. One great feature of Total.js is that you don’t need any tools like Grunt to compress JavaScript, HTML and CSS. Additionally, the framework has NoSQL embedded database and supports array and other prototypes. It supports RESTful routing mechanism, supports web sockets, media streaming and more.

Conclusion:

Today, these Node.js frameworks are shaping the future of web and application development technology. Some of them like Express.js, Mean.js and Sails.js are here to stay for a while and will also matter in the long run. I am sure that with the on-going development in the field there will be a lot more like these ones in the near future. There are a lot of Node.js frameworks that have still not become very popular. But, if you know any such frameworks which are still relatively rare then do not forget to share some information about them in the comments section below. Lastly, if you are currently working or have previously worked on Node.js frameworks and have experience developing cool web or mobile applications, then you can share your insights or useful links with us. Till then, signing off.

(referenced from: http://www.devsaran.com)

3 JavaScript Libraries to Keep an Eye on in 2015

As developers, we all know that our industry evolves at a very fast pace. So fast, indeed, that it’s often hard to keep up with all the new libraries, frameworks and new versions of the tools we use on a daily basis. Still, it’s important to stay as up to date as possible. Doing so ensures that we remain productive and in line with the expectations of our bosses and clients.

The new year started more than a month ago and some trends have already started to take shape. In this article, I’ll cover three libraries and frameworks worth keeping an eye on in 2015.

React.js

react-logo

React.js, sometimes referred to as simply React, is a JavaScript library for creating user interfaces, and was created by a collaboration between Facebook and Instagram. Currently, it’s maintained by these two companies with the help of other developers, and it’s used by companies like Yahoo, Airbnb, Sony and (of course) Facebook and Instagram.

React.js isn’t a complete framework, so it doesn’t provide all the components you’ll find in other projects like Ember or AngularJS. It encourages the creation of reusable UI components, which present data that changes over time. Many people like to refer to React as the V in MVC. An important difference with frameworks like AngularJS – which uses a two-way data binding model – is that React features a one-way data binding model.

One of the most important concepts of this project is the virtual DOM. You can think of it as a set of elements that you can modify with your data and which, in the end, will modify the page’s real DOM. The virtual DOM is used for efficient re-rendering of the DOM by using a diff algorithm that only re-renders the components changed. This in turn enables the library to be ultra fast.

Another great feature is that it can also render on the server using Node.js. Therefore, you can use the same knowledge you’ve gained both on the client and on the server. This has major performance and SEO benefits. Many developers are using React.js to render a first, static version of the page on the server, which is faster than doing so on the client and is also SEO-friendly. Then they enable fast user interactions and UI updates by using React.js on the client side.

This is just a brief introduction to this library, and I really encourage you to learn more by visiting the React.js website. It contains a lot of useful tutorials that will help you in the learning process.

Meteor

unnamed

Meteor is an open-source JavaScript framework written on top of Node.js, that focuses on real-time web applications. It’s not very new, as it has already reached a stable version (1.0), but lately I’ve been seeing more and more people discussing and adopting it to create their applications.

One of the main pros of Meteor is that it brings the famous Java motto of “Write once, run everywhere” into the JavaScript world. Using Meteor, you write code that runs both on the client and on the server, and you can even turn your web app into a mobile application by using Cordova behind the scenes. This kind of application is referred to as an isomorphic application – meaning an application that can run both client-side and server-side. The backend and frontend share the same code. If you love the fact that you can turn a Meteor application into a mobile app, you may want to read the article A Beginners Guide to Mobile Development with Meteor by David Turnbull.

When you install the framework, you get everything you need to develop both the client and server sides of your application, so it’s really fast to get up and running. Meteor comes with its own CLI that allows you to speed up your workflow. It also allows you to create a demo application on your local machine by typing the following command:

meteor create --example todos

One of my favorite features of this framework is that it’s reactive, meaning that any change to your data is automatically reflected everywhere throughout the app without the need for callbacks. Besides, as I mentioned before, Meteor focuses on real-time applications. So changes made by you or by other users are instantly reflected in the UI.

If this introduction seems appealing to you, I suggest to visit the official Meteor website, or read the articles 7 Reasons to Develop Your Next Web App with Meteor and What You Need To Know About Meteor 1.0, both published here on SitePoint.

Rendr

rendr logo

In recent months, I’ve been reading a lot about isomorphic applications, and Rendr is another library that employs this concept. It’s a small library developed by Airbnb that allows you to run Backbone.js applications on both the client and the server. The advantages are the same as mentioned in the React.js section: serving static and SEO-friendly HTML pages fast.

Being light-weight is one of the goals of this project. As mentioned in this article:

In true Backbone style, Rendr strives to be a library as opposed to a framework.

Rendr also tries to be agnostic about the environment by minimizing code like if (server) {…} else {…}, which is what you’ll find in frameworks like Meteor.

Unfortunately, I’m not aware of real-world applications built using this framework (apart from the one mentioned in the linked Airbnb post), so I’m not sure it’s mature enough to be used in production.

Conclusion

In this article, I’ve described three very interesting projects that are attracting a lot of attention and that are joining the fascinating trend towards isomorphic applications.

In recent weeks I’ve been playing with React.js, and I must confess that I’m loving it. I’m still in the process of learning this library, so I don’t have strong opinions on it yet, and I need to use it in a major project to test it properly. But if it can serve the Instagram user base, I’m sure it can perform reliably in small to medium applications. I do find it funny that, while Google isn’t using its own AngularJS for applications like Gmail, Facebook is adopting React in production.

Have you ever used one or more of these libraries and frameworks? If so, what was your experience with them? And if you haven’t used them, are you willing to give them a try?

How to install an .ipa file on an iPad or iPhone

The Developer .ipa file is intended to allow you to test the app on your iPad or iPhone before you send the .zip file to Apple for review. To test the .ipa file, you need to install it on your iPad/iPhone. Unfortunately, you can’t use AirDrop, Dropbox, or a similar service to install the file. Apple provides 2 ways to do this. One way is to add the .ipa file to your iTunes library on your computer, and then sync your iPad/iPhone with iTunes. But if you have a lot of content on your device, this process can be maddeningly slow. It may take 5 or 10 minutes or more to complete.

A far faster, simpler way is to use Xcode. Xcode is a free Apple development tool used to build apps for Mac and iOS. But you don’t need to know anything about Xcode or app development to use this tool to quickly and easily install an .ipa file on your iPad or iPhone. Here’s how to do it with Xcode 6.1.1

1. Download and install Xcode.

2. Run Xcode. You’ll find it in your Applications folder.

3. Wire your iPad or iPhone to your Mac with a USB cable.

4. In Xcode, choose Window > Devices, or press command-shift-2. You should see your device displayed in the Devices window.

Screen Shot 2014 12 12 at 6 56 15 AM

5. Either drag your .ipa file into the “Installed Apps” section, or click on the plus sign and select your .ipa file. This will install the development app on your device. There is a bug that sometimes causes the error message below to appear. If you get this message, and you have the correct device attached, just click the OK button and try again. It should work the second time.

Screen Shot 2014 12 12 at 6 52 01 AM

How I Develop Mobile Web Apps

For most projects, I perform two or more iterations with the following steps.

Requirements Gathering

As you would suspect, for this step I prefer to go to the people who know the most about what is needed, preferably the end users of the future app or software.

Development Environment Setup

This is where I set up my workstation to develop the project. It entails creating directories for source code, documentation and other resources; setting up source control (I normally use Bitbucket); and installing code libraries, frameworks and third-party software needed for the project.

Low Fidelity UI Prototyping

This is where I create low-fidelity prototypes of the user interface of the app. I useBalsamiq and Pencil as the tools for this step. I prefer short work sessions with the users or clients until they are satisfied with the prototypes.

High Fidelity UI Prototyping

I also make high-fidelity prototypes of the UI, based on the low-fidelity prototypes. I prefer to create these prototypes with jQuery Mobile due to the ease of use of this framework. As with the previous step, I work with users or clients until we agree on the prototypes.

UI Implementation with Mock Data

Once I have UI prototypes that my clients believe are very close to the final product, I start to implement the UI of the app. During this phase I use mock data to populate the screens. I also simulate network connections and other processes that need to be in place in the production app.

The goal here is to have a working UI that users can test on an emulator or physical device. I use emulators such as Ripple and Genymotion, as well as the iOS emulators provided with Xcode.

Once I finish this stage, I know that I can focus on implementing the controllers and services that will drive the UI, with the confidence that there will be little changes to the UI going forward.

Implementation of Client-Side Controllers and Services

The client-side controllers and services drive the app’s UI and perform tasks such as communications with the server and local data access. During this phase, I perform mini-iterations consisting of the following steps:

  • Create behavior-driven tests for the controllers and services layer.
  • Implement the controller and services layer functions.
  • Wire the UI to the controller and remove mock data.

The test-first approach makes it easy to create lean controller and service methods that do what’s needed for the specific task, without code bloat.

It’s simple to create good behavior-driven tests once the UI is well defined. If I need to make changes to the UI down the road, the tests also make it easy to find the places where I need to change the controller or services to respond to the UI changes.

Implementation of Server-Side Endpoints and Services

The server-side endpoints and services store application data and run tasks on behalf of the mobile app. During this phase, I perform mini-iterations consisting of the following steps:

  • Create behavior-driven tests of endpoints with fake data, using Postman or similar tools.
  • Implement the endpoints.
  • Create behavior-driven tests for the services layer (authentication, authorization, data access, etc.).
  • Implement the services layer.

Tests on Emulator and Physical Devices

This phase is all about end-to-end tests of the application on different emulators and physical devices. I first perform functional tests that cover the features of the app; then I move on to non-functional tests, paying particular attention to usability and performance issues.

Here again I use emulators such as Ripple and Genymotion, as well as the iOS provided with Xcode.

Packaging

The packaging step is where I package the application (if needed) so it can be deployed through an enterprise portal or app store.

The Database Timeline

1961 Development begins on Integrated Data Store, or IDS, at General Electric. IDS is generally considered the first “proper” database.” It was doing NoSQL and Big Data decades before today’s NoSQL databases.

1967 IBM develops Information Control System and Data Language/Interface (ICS/DL/I), a hierarchical database for the Apollo program. ICS later became Information Management System (IMS), which was included with IBM’s System360 mainframes.

1970 IBM researcher Edgar Codd publishes his paper A Relational Model of Data for Large Shared Data Banks, establishing the mathematics used by relational databases.

1973 David R. Woolley develops PLATO Notes, which would later influence the creation of Lotus Notes.

1974 Development begins at IBM on System R, an implementation of Codd’s relational databases and the first use of the structured query language (SQL). This later evolves into the commercial product IBM DB2. Inspired by Codd’s research, University of Berkeley students Michael Stonebraker and Eugene Wong begin development on INGRES, which became the basis for PostGreSQL, Sybase, and many other relational databases.

1979 The first publicly available version of Oracle is released.

1984 Ray Ozzie founds Iris Associates to create a PLATO-Notes-inspired groupware system.

1988 Lotus Agenda, powered by a document database, is released.

1989 Lotus Notes is released.

1990 Objectivity, Inc. releases its flagship object database.

1991 The key-value store Berkeley DB is developed

2003 Live Journal open sources the original version of Memcached.

2005 Damien Katz open sources CouchDB.

2006 Google publishes BigTable paper.

2007 Amazon publishes Dynamo paper. 10gen starts coding MongoDB. Powerset open sources its BigTable clone, Hbase. Neo4j released.

2008 Facebook open sources Cassandra.

2009 ReadWriteWeb asks: “Is the relational database doomed?” Redis released. First NoSQL meetup in San Francisco.

2010 Some of the leaders of the Memcached project, along with Zynga, open source Membase.

10 Most Common App Security Mistakes

Why Mobile App Security?

App security mistakes for Android and iPhone are generally a lesser prioritized area for a mobile developer, mostly because due to the time pressure. It does not usually get what it deserves in project plans. Moreover, in case of absence of a security owner in project teams, no one claims responsibility. That’s why mobile app security is a matter of attention left only to the developer’s initiative.

Security and Usability are two concepts that are inversely related. Highly secure solutions require additional processes and flows. However, most business units, working directly with consumers, don’t consider app security as the first priority.

In practice, nobody brings out a security concern unless something really goes wrong in case of “hacking”. Most application developers are not taking care of specific Android security and iPhone security tests. (Application Security Test).

Always keep in mind the principle that No app is %100 safe!

icloud-security-risk-1024x426

What Should You Do for App Security?

Our purpose is to make your app more secure than others by using quick and simple features, hence discouraging the hackers to mess with your mobile application. Make your app ready for mobile security. Here are the 10 Most Common App Security Mistakes:

1. Data Store Approach: First of all, sensitive data should not be stored on the device during runtime as much as possible. Data can be processed in case of need and should be deleted immediately when not needed. In case of a data storage need on the mobile device, data should be encrypted and stored in the documents folder. Passwords should be stored in KeyChain for iOS and KeyStore for Android app security. This is also important for app store security checks.

2. Missing front-end validation: Missing data entry validation causes both security and formatting issues. These may be things like letting alphanumeric values in numeric fields, missing masking on formatted fields, not checking for high risk character values such as <>` ” ()|#. Such missing validations may cause security breaches by allowing remote code execution or unexpected responses.

3. Server Based Controls: Application development is a client side operation. Server side is the place where you should store and manage the data. Server side checks should be applied regardless of channel (mobile, web, etc…) for data security and formatting. We do not mean iCloud keychain or a similar feature, please take care. This is about the app-specific backend security. There are also security concerns for Apple iCloud, however this is Apple’s work to do it more secure!

4. SSL: HTTPS must be used for secure transmission of sensitive information. If possible, a custom certificate should be used instead of the certificates from the built-in device certificate store. The certificate that is unique to the app and the server should be embedded inside the app.

5. Obfuscation: It is very important especially for Android apps to go through obfuscation. If script files are also used in parts of the app, these files should be taken through obfuscation as well.

6. Comment Lines: Explanatory data, included as comment lines may be viewed by others if the application is decompiled. This is very simple but a common mistake both for Android and iOS apps. This does not mean that you shouldn’t use comments during app development, just don’t forget to remove them from the production version of your app.

7. Excessive Permissions: When editing permission preferences for Android apps, only the permissions that are absolutely needed should be enabled. Permissions with access to personal information, such as “access to contacts”, should be avoided as much as possible for Android app security. If anything goes wrong, there is less chance of a data breach.

8. Encryption: The key used in encryption should also be encrypted and stored in secure storage. The installation file should also be obfuscated. Another dangerous practice that should avoided is the downloading of the encryption key from server during runtime.

9. Rooted/Jailbroken Devices: It is not possible to store totally secure data in rooted devices as root permissions provide unlimited access to the device filesystem and memory. However, it is possible for developers to check if the device is rooted or not. This risk should be noted and evaluated based on project scope for all flows and processes.

10. Application Tampering Protection: The application binary files (.apk or .ipa) can be altered and published in different markets by hackers. They may inject malicious code in your app or they may crack mobile apps to bypass license and payment restrictions. Nowadays it’s even possible to crack in-app purchases and license checks just by emulating app store responses. Therefore, application integrity and in-app purchases should be checked with a third-party trusted server to prevent such cases. For this purpose, there are some good solutions available in the market. Again, this is very critical for Google Play and iTunes App Store security.

app_security

If you are developing your app with a Platform-Based Approach (Obj-C, Swift, Java) the items above should be managed entirely by yourself or your team. However, if you’re using a cross-platform native framework approach, most of the items above are covered by the mobile development framework for mobile app security.

We especially suggest you to use cross-platform native frameworks for mobile security industry. You may have already faced the well-known risks of cross-platform hybrid frameworks, such as DOM Payload, Scripting Engine Scope, etc. You can assess security capabilities of the Smartface.

(collected from Smartface)

The Do’s and Don’ts of Building HTML5 Hybrid Apps

In the beginning there was native code and it was good. Then PhoneGap,Appcelerator, Trigger.io, AppGyver and others emerged, ushering in the “native or hybrid” debate.

If you aren’t familiar with the term, a hybrid app is a mobile app written using languages such as HTML5, CSS3 and JavaScript, then compiled into native iOS, Android or other mobile platform code using wrapper technologies such as PhoneGap/Cordova. Additionally, these frameworks have APIs allowing access to native functions such as the camera, GPS, etc.

The allure of HTML5 is hard to deny. If you’re proficient in building web apps, you’re 90% of the way to creating hybrid mobile apps. You can spend weeks learning Swift or Objective C to write your first iOS app or starting building something today that will also run on Android.

Native proponents are quick to say there’s no substitute for natively written apps. Aspects such as speed, stability, smooth transitions and ease of maintenance are major selling points.

Mobile apps concept
Image Source: Mobile Apps Concept via Shutterstock.

Dismal early experiences developing hybrids placed me in the native camp. In 2010, smitten with the promise of “write once deploy everywhere,” I led a team that decided to give PhoneGap a whirl. It didn’t take much time to realize PhoneGap’s limitations. Our client wanted that “native feel,” but it wasn’t possible. Scrolling, fixed headers and transitions were an issue. Performance was awful. The entire project felt like swimming upstream.

That experience forced me to accept that unless we were willing to compromise aspects native apps take for granted, hybrid wasn’t ready for prime time.

Fast forward to 2013. PhoneGap 3 was released. Smartphones such as the iPhone 5 and Nexus 3 demonstrated exponential advances in processing power. OS support of CSS3 had come along considerably. It was time to give hybrid another try at bat.

The result? Mixed. We produced two apps. The first was a relatively simple calculator-style app with some reporting. We purposely avoided transitions between views and other processor-intensive actions. It turned out well—outputting to both iOS and Android was mostly painless. Unless you’re a seasoned mobile developer, you wouldn’t know it was a hybrid.

The second attempt was more challenging. The app was complex and the client had specific requests on how it needed to work. In hindsight, it wasn’t a good hybrid candidate. Despite this, we successfully completed the project. We also learned a ton along the way.

Having since been part of numerous native and hybrid projects, I’ve gained a pretty good perspective on the Do’s and Don’ts of taking a hybrid approach.

First, the good news: yes, hybrid is a viable solution (sorry, native evangelists). Advances in smartphone processing and memory, along with improved frameworks have helped level the playing field. However, there are guidelines one should follow when considering hybrid. Let’s start with the Don’ts.

The Don’ts…

1. Don’t Use Heavy Libraries, Frameworks or Plug-ins
If avoidable, Don’t use heavy libraries like jQuery. If you must use jQuery, opt for the much lighter Zepto.js. Completely avoid jQuery UI and jQuery Mobile. Both these libraries are performance hogs when compiled into mobile apps. jQuery Mobile in particular imposes a lot of rigidness.

2. Don’t Use HTML5 for Apps that are Multi-purpose or Complex
When it first launched, Facebook used a hybrid approach and it was a dismal failure due to performance. Facebook crammed a lot of functionality into the app, weighing it down considerably. When considering hybrid, your concept should be simple.

3. Don’t Load Views All at Once
If your views are a mix of text and graphics, load the text first and the graphics as separate data calls that load sequentially. Speed and performance are paramount to creating an engaging user experience.

4. Don’t Use Hybrid for Animation or Graphic-intensive Apps
For example, interactive games or rich-media.

5. Don’t Expect Your App to Run Perfectly in iOS and Android Out of the Gate
We’ve consistently developed for iOS first, and then re-factored for Android. The “write once run everywhere” mantra just isn’t that simple. Prepare to spend time adjusting your CSS and other formatting to accommodate each OS.

The Do’s…

1. For Data-driven Apps, Do Use Javascript MVC Frameworks Like AngularJS
Angular is particularly well-suited for hybrid apps because it doesn’t rely on heavy libraries like jQuery. Backbone.js has some nice helper libraries like Thorax andMarionette. App.js is a lightweight framework designed for hybrid apps.

2. Do Consider Using a UI Library such as Ionic

Ionic excels at delivering native-like transitions and pairs well with AngularJS.

3. Do Minify HMTL/CSS/JS to Reduce File Size and Improve Performance
Use tools like jscompress.com for Javascript files, and cssminifier.com for CSS. Will Peavy’s HTML minifier will compress your HTML nicely. Be sure to test your app thoroughly after minimizing to ensure everything works.

4. Do Crunch All Your Graphics
There are plenty of graphics optimizers out there. Tinypng.com is great at reducing PNGs without compromising quality.

5. Do Test for Performance
Clunky or inconsistent view transitions and slow load times make an otherwise great app unpolished. If you’re using PhoneGap/Cordova, test your hybrid apps using a tool like Browser-perf. Third-party services like New Relic’s mobile monitoring pinpoints issues across response times, errors, carrier performance and versioning optimization.

6. Do Use Chrome Canary to Emulate Different Environments
Canary’s Developer tools will emulate different devices and network speeds when testing your app.

Business concept

7. Do Take Advantage of Local Storage
By leveraging local storage, your app can re-render views and reduce service calls. Speed is a big issue for hybrid apps and local storage increases performance.

8. Do Consider Learning a Hybrid Development Framework
There are numerous frameworks and platforms out there for developing hybrid apps. I’m particularly impressed with the offerings from AppGyver. Their platform uses a mix of native and hybrid components and is rooted in AngularJS. In evaluating several hybrid frameworks, I’ve found AppGyver’s Steroids platform produces incredibly responsive, native-like apps.

Conclusion

Native has clear advantages, but hybrid apps have come a long way. Recent platforms and frameworks have brought powerful new ways of building apps to the forefront of mobile development. If you’ve tried hybrid in the past with less than spectacular results or are considering it for the first time, there’s no better time in history to give it a try!

Top 10 Mistakes AngularJS Developers Make

Introduction

AngularJS is one of the most popular Javascript frameworks available today. One of AngularJS’s goals is to simplify the development process which makes it great for prototyping small apps, but its power allows scaling to full featured client side applications. The combination ease of development, breadth of features, and performance has led to wide adoption, and with wide adoption comes many common pitfalls. This list captures common AngularJS mistakes, especially when scaling an app.

1 MVC directory structure

AngularJS is, for lack of a better term, an MVC framework. The models aren’t as clearly defined as a framework like backbone.js, but the architectural pattern still fits well. When working in an MVC framework a common practice is to group files together based on file type:

templates/
    _login.html
    _feed.html
app/
    app.js
    controllers/
        LoginController.js
        FeedController.js
    directives/
        FeedEntryDirective.js
    services/
        LoginService.js
        FeedService.js
    filters/
        CapatalizeFilter.js

This seems like an obvious layout, especially if coming from a Rails background. However once the app begins to scale, this layout causes many folders to be open at once. Whether using Sublime, Visual Studio, or Vim with Nerd Tree, a lot of time is spent scrolling through the directory tree.

Instead of keeping the files grouped by type, group files based on features:

app/
    app.js
    Feed/
        _feed.html
        FeedController.js
        FeedEntryDirective.js
        FeedService.js
    Login/
        _login.html
        LoginController.js
        LoginService.js
    Shared/
        CapatalizeFilter.js

This directory structure makes it much easier to find all the files related to a particular feature which will speed up development. It may be controversial to keep .html files with .js files, but the time savings are more valuable.

2 Modules (or lack thereof)

It’s common when starting out to hang everything off of the main module. This works fine when starting a small app, but it quickly becomes unmanageable.

var app = angular.module('app',[]);
app.service('MyService', function(){
    //service code
});
app.controller('MyCtrl', function($scope, MyService){
    //controller code
});

A common strategy after this is to group similar types of objects:

var services = angular.module('services',[]);
services.service('MyService', function(){
    //service code
});

var controllers = angular.module('controllers',['services']);
controllers.controller('MyCtrl', function($scope, MyService){
    //controller code
});

var app = angular.module('app',['controllers', 'services']);

This strategy scales as well as the directory structures from part 1: not great. Following the same concept of grouping features together will allow scalability.

var sharedServicesModule = angular.module('sharedServices',[]);
sharedServices.service('NetworkService', function($http){});

var loginModule = angular.module('login',['sharedServices']);
loginModule.service('loginService', function(NetworkService){});
loginModule.controller('loginCtrl', function($scope, loginService){});

var app = angular.module('app', ['sharedServices', 'login']);

When working on large applications everything might not be contained on a single page, and by having features contained within modules it’s much simpler to reuse modules across apps.

3 Dependency injection

Dependency injection is one of AngularJS’s best patterns. It makes testing much simpler, as well as making it more clear upon which any particular object depends. AngularJS is very flexible on how things can be injected. The simplest version requires just passing the name of the dependency into the function for the module:

var app = angular.module('app',[]);

app.controller('MainCtrl', function($scope, $timeout){
    $timeout(function(){
        console.log($scope);
    }, 1000);
});

Here, it’s very clear that MainCtrl depends on $scope and $timeout.

This works well until you’re ready to go to production and want to minify your code. Using UglifyJS the example becomes the following:

var app=angular.module("app",[]);app.controller("MainCtrl",function(e,t){t(function(){console.log(e)},1e3)})

Now how does AngularJS know what MainCtrl depends upon? AngularJS provides a very simple solution to this; pass the dependencies as an array of strings, with the last element of the array being a function which takes all the dependencies as parameters.

app.controller('MainCtrl', ['$scope', '$timeout', function($scope, $timeout){
    $timeout(function(){
        console.log($scope);
    }, 1000);
}]);

This then minifies to code with clear dependencies that AngularJS knows how to interpret:

app.controller("MainCtrl",["$scope","$timeout",function(e,t){t(function(){console.log(e)},1e3)}])

3.1 Global dependencies

Often when writing AngularJS apps there will be a dependency on an object that binds itself to the global scope. This means it’s available in any AngularJS code, but this breaks the dependency injection model and leads to a few issues, especially in testing.

AngularJS makes it simple to encapsulate these globals into modules so they can be injected like standard AngularJS modules.

Underscore.js is a great library for simplifying Javascript code in a functional pattern, and it can be turned into a module by doing the following:

var underscore = angular.module('underscore', []);
underscore.factory('_', function() {
  return window._; //Underscore must already be loaded on the page
});
var app = angular.module('app', ['underscore']);

app.controller('MainCtrl', ['$scope', '_', function($scope, _) {
    init = function() {
          _.keys($scope);
      }

      init();
}]);

This allows the application to continue in the AngularJS dependency injection fashion which would allow underscore to be swapped out at test time.

This may seem trivial and like unnecessary work, but if your code is using use strict (and it should be!), then this becomes a requirement.

4 Controller bloat

Controllers are the meat and potatoes of AngularJS apps. It’s easy, especially when starting out, to put too much logic in the controller. Controllers should never do DOM manipulation or hold DOM selectors; that’s where directives and using ng-model come in. Likewise business logic should live in services, not controllers.

Data should also be stored in services, except where it is being bound to the $scope. Services are singletons that persist throughout the lifetime of the application, while controllers are transient between application states. If data is stored in the controller then it will need to be fetched from somewhere when it is reinstantiated. Even if the data is stored in localStorage, it’s an order of magnitude slower to retrieve than from with a Javascript variable.

AngularJS works best when following the Single Responsibility Principle (SRP). If the controller is a coordinator between the view and the model, then the amount of logic it has should be minimal. This will also make testing much simpler.

5 Service vs Factory

These names cause confusion for almost every AngularJS developer when starting out. They really shouldn’t because they’re syntactic sugar for (almost) the same thing!

Here are their definitions from the AngularJS source:

function factory(name, factoryFn) { 
    return provider(name, { $get: factoryFn }); 
}

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
      return $injector.instantiate(constructor);
    }]);
}

From the source you can see that service just calls the factory function which in turn calls the provider function. In fact, AngularJS also offers a few additional provider wrappers with value, constant, and decorator. These other objects don’t cause nearly the same level of confusion and the docs are pretty clear on their use cases.

Since service just calls the factory function, what makes it different? The clue is in $injector.instantiate; within this function the $injector creates a new instance of the service’s constructor function.

Here’s an example of a service and a factory that accomplish the same thing.

var app = angular.module('app',[]);

app.service('helloWorldService', function(){
    this.hello = function() {
        return "Hello World";
    };
});

app.factory('helloWorldFactory', function(){
    return {
        hello: function() {
            return "Hello World";
        }
    }
});

When either helloWorldService or helloWorldFactory are injected into a controller, they will both have a hello method that returns “Hello World”. The service constructor function is instantiated once at declaration and the factory object is passed around every time it is injected, but there is still just one instance of the factory. All providers are singletons.

Why do the two styles exist if they can accomplish the same thing? Factories offer slightly more flexibility than services because they can return functions which can then be new‘d. This follows the factory pattern from object oriented programming. A factory can be an object for creating other objects.

app.factory('helloFactory', function() {
    return function(name) {
        this.name = name;

        this.hello = function() {
            return "Hello " + this.name;
        };
    };
});

Here’s an example controller using the service and the two factories. With the helloFactory returning a function, the name value is set when the object is new‘d.

app.controller('helloCtrl', function($scope, helloWorldService, helloWorldFactory, helloFactory) {
    init = function() {
      helloWorldService.hello(); //'Hello World'
      helloWorldFactory.hello(); //'Hello World'
      new helloFactory('Readers').hello() //'Hello Readers'
    }

    init();
});

When starting out it is best to just use services.

Factories can also be more useful when designing a class with more private methods:

app.factory('privateFactory', function(){
    var privateFunc = function(name) {
        return name.split("").reverse().join(""); //reverses the name
    };

    return {
        hello: function(name){
          return "Hello " + privateFunc(name);
        }
    };
});

With this example it’s possible to have the privateFunc not accessible to the public API of privateFactory. This pattern is achievable in services, but factories make it more clear.

6 Not utilizing Batarang

Batarang is an excellent Chrome extension for developing and debugging AngularJS apps.

Batarang offers Model browsing to get a look inside what Angular has determined to be the models bound to scopes. This can be useful when working with directives and to isolate scopes to see where values are bound.

Batarang also offers a dependency graph. If coming into an untested codebase, this would be a useful tool to determine which services should get the most attention.

Finally, Batarang offers performance analysis. AngularJS is quite performant out of the box, but as an app grows with custom directives and complex logic, it can sometimes feel less than smooth. Using the Batarang performance tool it is quite simple to see which functions are taking the most time in the digest cycle. The performance tool also shows the full watch tree, which can be useful when having too many watchers.

7 Too many watchers

As mentioned in the last point, AngularJS is quite performant out of the box. Because of the dirty checking done in a digest cycle, once the number of watchers exceeds about 2,000 the cycle can cause noticeable performance issues. (The 2,000 number isn’t guaranteed to be a sharp drop off, but it is a good rule of thumb. Changes are coming in the 1.3 release of AngularJS that allow tighter control over digest cycles. Aaron Gray has a nice write up on this.)

This Immediately Invoked Function Expression (IIFE) will print out the number of watchers currently on the page. Simply paste it into the console to see how many watchers are currently on the page. This IIFE was taken from Words Like Jared’s answer on StackOverflow:

(function () { 
    var root = $(document.getElementsByTagName('body'));
    var watchers = [];

    var f = function (element) {
        if (element.data().hasOwnProperty('$scope')) {
            angular.forEach(element.data().$scope.$$watchers, function (watcher) {
                watchers.push(watcher);
            });
        }

        angular.forEach(element.children(), function (childElement) {
            f($(childElement));
        });
    };

    f(root);

    console.log(watchers.length);
})();

By using this to determine the number of watchers and the watch tree from the performance section of Batarang, it should be possible to see where duplication exists or where unchanging data has a watch.

When there is data that does not change, but you want it to be templated using Angular, consider using bindonce. Bindonce is a simple directive which allows you to use templates within Angular, but this does not add a watch to keep the count from increasing.

8 Scoping $scope’s

Javascript’s prototype-based inheritance differs from class-based inheritance in nuanced ways. This normally isn’t a problem, but the nuances often arise when working with $scope. In AngularJS every $scope inherits from its parent $scope with the highest level being $rootScope. ($scope behaves slightly differently in directives, with isolate scopes only inherit properties explicitly declared.)

Sharing data from a parent to a child is trivial because of the prototype inheritance. It is easy however to shadow a property of the parent $scope if caution is not taken.

Let’s say we want to have a username displayed in a navbar, and it is entered in a login form. This would be a good first try at how this might work:

<div ng-controller="navCtrl">
   <span>{{user}}</span>
   <div ng-controller="loginCtrl">
        <span>{{user}}</span>
        <input ng-model="user"></input>
   </div>
</div>

Quiz time: when a user types in the text input with the user ng-model set on it, which template will update? The navCtrl, loginCtrl, or both?

If you selected loginCtrl then you probably already understand how prototypical inheritance works.

When looking up literal values, the prototype chain is not consulted. If navCtrl is to be updated simultaneously then a prototype chain lookup is required; this will happen when the value is an object. (Remember, in Javascript, functions, arrays, and objects are objects)

So to get the desired behavior it is necessary to create an object on the navCtrl that can be referenced from loginCtrl.

<div ng-controller="navCtrl">
   <span>{{user.name}}</span>
   <div ng-controller="loginCtrl">
        <span>{{user.name}}</span>
        <input ng-model="user.name"></input>
   </div>
</div>

Now since user is an object, the prototype chain will be consulted and the navCtrl‘s template and $scope will be updated along with loginCtrl.

This may seem like a contrived example, but when working with directives that create child $scope‘s like ngRepeat this issue can arise easily.

9. Manual Testing

While TDD might not be every developer’s preferred development method, every time a developer checks to see if code works or has broken something else he or she is doing manual testing.

There are no excuses for not testing an AngularJS app. AngularJS was designed to be testable from the ground up. Dependency injection and the ngMock module are evidence of this. The core team has developed a couple of tools that can bring testing to the next level.

9.1 Protractor

Unit tests are the building blocks of a test suite, but as the complexity of an app grows integration tests tease out more realistic situations. Luckily the AngularJS core team has provided the necessary tool.

We have built Protractor, an end to end test runner which simulates user interactions that will help you verify the health of your Angular application.

Protractor uses the Jasmine test framework for defining tests. Protractor has a very robust API for different page interactions.

There are other end to end test tools, but Protractor has the advantage of understanding how to work with AngularJS code, especially when it comes to $digest cycles.

9.2. Karma

Once integration tests have been written using Protractor, the tests need to run. Waiting for tests to run, especially integration tests, can be frustrating for developers. The AngularJS core team also felt this pain and developed Karma.

Karma is a Javascript test runner which helps close the feedback loop. Karma does this by running the tests any time specified files are changed. Karma will also run tests in parallel across different browsers. Different devices can also be pointed to the Karma server to get better coverage of real world usage scenarios.

10 Using jQuery

jQuery is an amazing library. It has standardized cross-platform development and is almost a requirement in modern web development. While jQuery has many great features, its philosophy does not align with AngularJS.

AngularJS is a framework for building applications; jQuery is a library for simplifying “HTML document traversal and manipulation, event handling, animation, and Ajax”. This is the fundamental difference between the two. AngularJS is about architecture of applications, not augmenting HTML pages.

In order to really understand how to build an AngularJS application, stop using jQuery. jQuery keeps the developer thinking of existing HTML standards, but as the docs say “AngularJS lets you extend HTML vocabulary for your application.”

DOM manipulation should only be done in directives, but this doesn’t mean they have to be jQuery wrappers. Always consider what features AngularJS already provides before reaching for jQuery. Directives work really well when they build upon each other to create powerful tools.

The day may come when a very nice jQuery library is necessary, but including it from the beginning is an all too common mistake.

Conclusion

AngularJS is a great framework that continues to evolve with the community. Idiomatic AngularJS is still an evolving concept, but hopefully by following these conventions some of the major pitfalls of scaling an AngularJS app can be avoided.

Read more at http://www.airpair.com/angularjs/posts/top-10-mistakes-angularjs-developers-make#xT1gceCgWj42kzKO.99