coding, javascript, nodejs

Parse Server – providing ip of a client

Very handy code that can be used for analytics (reversing to approximate location)

let ip = request.headers[‘x-forwarded-for’] || request.connection.remoteAddress || request.socket.remoteAddress || request.connection.socket.remoteAddress;

This is for cloud defined functions for your custom rest API

Share This:

javascript, mobile

Requesting permission for android using React Native

A great new way of requesting and checking for permission on android is no longer challenging.

Available in RN 33+

https://github.com/facebook/react-native/commit/0fb2ccfcc3e6babe28d7d1bcf4635ef2f9191eb1

Permissions you can request that will prompt a user:

this.PERMISSIONS = {
READ_CALENDAR: ‘android.permission.READ_CALENDAR’,
WRITE_CALENDAR: ‘android.permission.WRITE_CALENDAR’,
CAMERA: ‘android.permission.CAMERA’,
READ_CONTACTS: ‘android.permission.READ_CONTACTS’,
WRITE_CONTACTS: ‘android.permission.WRITE_CONTACTS’,
GET_ACCOUNTS: ‘android.permission.GET_ACCOUNTS’,
ACCESS_FINE_LOCATION: ‘android.permission.ACCESS_FINE_LOCATION’,
ACCESS_COARSE_LOCATION: ‘android.permission.ACCESS_COARSE_LOCATION’,
RECORD_AUDIO: ‘android.permission.RECORD_AUDIO’,
READ_PHONE_STATE: ‘android.permission.READ_PHONE_STATE’,
CALL_PHONE: ‘android.permission.CALL_PHONE’,
READ_CALL_LOG: ‘android.permission.READ_CALL_LOG’,
WRITE_CALL_LOG: ‘android.permission.WRITE_CALL_LOG’,
ADD_VOICEMAIL: ‘com.android.voicemail.permission.ADD_VOICEMAIL’,
USE_SIP: ‘android.permission.USE_SIP’,
PROCESS_OUTGOING_CALLS: ‘android.permission.PROCESS_OUTGOING_CALLS’,
BODY_SENSORS: ‘android.permission.BODY_SENSORS’,
SEND_SMS: ‘android.permission.SEND_SMS’,
RECEIVE_SMS: ‘android.permission.RECEIVE_SMS’,
READ_SMS: ‘android.permission.READ_SMS’,
RECEIVE_WAP_PUSH: ‘android.permission.RECEIVE_WAP_PUSH’,
RECEIVE_MMS: ‘android.permission.RECEIVE_MMS’,
READ_EXTERNAL_STORAGE: ‘android.permission.READ_EXTERNAL_STORAGE’,
WRITE_EXTERNAL_STORAGE: ‘android.permission.WRITE_EXTERNAL_STORAGE’,
};

Share This:

javascript

Animations and transitions on websites need to be smooth

Today, there are many gorgeous sites designed with animations and modern browser support in mind. We’re not talking about video but rather pictures and popups gliding on the screen to show you something important. You probably see previews or an app or a picture that  shows content that’s easy on the eye.

Even with a modern computer or mobile devices, these animations be appear choppy. I will describe solution to this:

 

Velocity is an animation engine with the same API as jQuery’s $.animate(). It works with and without jQuery. It’s incredibly fast, and it features color animation,transforms, loops, easings, SVG support, and scrolling. It is the best of jQuery and CSS transitions combined.

Velocity was built to augment where Jquery and Jquery Transit have left off. See CSS transitions that use your video card.

 

You can find velocity.js here Velocity JS code and documentation

Share This:

cloud, javascript

Using MomentJs Timezone in Parse.Cloud.code

Parse Cloud Code comes with a few handy modules, however momentjs presently is very old (1.x) on parse cloud code. Here are the steps how to integrate momentjs and momentjs-timezone (latest and greatest).

Step 1

Within your project copy momentjs.js (version 2.X) and moment-timezone.js file to /cloud directory.

Step 2

Modify moment-timezone.js first few lines:


(function (root, factory) {
"use strict";

module.exports = factory(require(‘cloud/moment.js’));

}(this, function (moment) {

What this does is loads your updated momentJs for moment-timezone to use

Step 3

Use the updated script within your code like this


var moment = require('cloud/moment-tz');

Share This:

javascript

Add async to script tag and enjoy 10% performance in page load

Chrome 41+ supports

 

<script async src="app.min.js">

 

Which allows script(s) to be parsed in parallel to other scripts therefore end user will experience slightly faster page load.

Share This:

javascript, Uncategorized

AngularJS Pluralize – build a friendly message, good ui practice

Have you noticed that some web apps creators absolutely ignore common grammar in message or labels?

Well it is common.

You have 1 messages.

Or it might be cooler and human like but still:

You have one messages.

 

What you’d want to do in your AngularJS application is use a wonderful directive that is baked in and helps you avoid such mishaps.

 

<ng-pluralize count="report.CriteriaSelected.length"
                 when="{'0': 'No criterion is selected',
                     'one': '1 Criterion is selected',
                     'other': '{} Criteria selected’}"

What this will nicely take care for you are the conditions when Nothing is selected or you have 1 or many conditions where a different text is used.

Thereby avoiding using “message(s)”.

 

Going further, i would suggest using internationalization i18n for your labels in such cases so that it makes sense in other languages.

 

This feature exists for a while now.

 

Enjoy

Share This:

architecture, javascript, nodejs

Official nodejs.org is dead?, long live IOJS

It appears that IOJS (io.js, a form of node.js ) has gained an incredible momentum and credibility. As a seasoned nodeJS engineer i would be strongly swayed towards iojs give that it has all the important committee members (committers to nodejs).

My recent observation of this fork is that they release every 4 days ! That’s an impressive frequency.

Although some are uncertain about this fork in hopes that official (rather original) nodejs may all of a sudden resolve their differences and release 0.12 or perhaps even Nodejs 1.0, we shall see what happens in the next few months.
At one point a plan was to release NodeJS 0.12 in March 2014 , prediction is that it could be this year.

Meanwhile , Strongloop is gaining ground as a promenant NodeJS consulting firm with an array of tools (from monitoring , web ide generating rest apis, etc).

 

To add to this note, folks are realizing that NPM INSTALL may be something devops have missed and insecure (or plain old malware) modules can be installed ( might be even root).

 

 

Feb 11 UPDATE: Official NodeJS 0.12 was released just few days ago albeit without mention of generators. Great news!

 

Share This:

coding, javascript

Creating great looking UI with bootstrap – wizard

Creating friendly and intuitive UI is paramount in web development.

Here is a tip for an angular App that uses bootstrap.ui (angular directives for bootstrap) and bootstrap:

 

Accordion

 

The above UI uses this easy CSS for styling that number:

 

.number {
    background: #69C8C7;
    display: inline-block;
    width: 25px;
    height: 25px;
    border-radius: 30px;
    text-align: center;
    color: #fff;
    line-height: 25px;
    margin-right: 8px;
}

 

And html for the controller and a route contains this markup:

 

<accordion >
	<accordion-group >
	<accordion-heading>
	<p><span class="number">1</span>
		<span class="fa fa-check-circle" ng-show='false'></span> Headline</p>

	</accordion-heading>
	Fill out some information
</accordion-group>

<accordion-group >
<accordion-heading>
<p><span class="number">2</span>
	<span class="fa fa-check-circle" ng-show='false'></span> More options</p>

</accordion-heading>
Fill out some information and select options.
</accordion-group>

</accordion>

 

Notice the check circle can be replaced  when for example you’ve filled out all the data indicating to the user they are done with that section. Implemention and logic is up to you.

 

For more information on Bootstrap UI (these are directives for your angular app)

 

 

 

 

 

Share This:

coding, javascript

EmberJS – ongoing – part 3

Here is a situation:

API – Build on Rails , follows ActiveModel pattern (e.g. first_name)

EmberJS App – model uses camelized style for properties (e.g. firstName)

EmberJS requires an adapter for pulling data from some source (e.g. an API)
We have to use adapter that will deal with ActiveModel pattern

ApplicationAdapter = DS.ActiveModelAdapter.extend

Here is the caveat: Upgrading to Ember 1.8.1 will cause this error:

TypeError: undefined is not a function
at Object.func (http://localhost:4200/assets/vendor.js:49499:18)
at Object.Cache.get (http://localhost:4200/assets/vendor.js:25100:38)
at decamelize (http://localhost:4200/assets/vendor.js:49541:31)
at RESTSerializer.extend.keyForAttribute (http://localhost:4200/assets/vendor.js:63962:16)
at apply (http://localhost:4200/assets/vendor.js:32847:27)
at superWrapper [as keyForAttribute] (http://localhost:4200/assets/vendor.js:32419:15)
at null. (http://localhost:4200/assets/vendor.js:66421:31)
at null. (http://localhost:4200/assets/vendor.js:68910:20)
at cb (http://localhost:4200/assets/vendor.js:29082:22)
at OrderedSet.forEach (http://localhost:4200/assets/vendor.js:28880:13)

You might have to override an ActiveModelSerializer to handle the issue, however stick to Ember 1.7 and it’ll work.

Not loving the experience with Ember/EmberCLI

Share This:

javascript

AngularJS – being aware of environment

 

Single Page Apps can be awesome

Single Page app is not a myth, its real and its awesome.

But strong , fast tools are definitely something a developer should always use. Grunt and Gulp are extremely useful for running tasks that optimize web resources, run automatic tests , monitor changes and refresh your browser as you tinker with the next big thing but also run any custom task you desire.

I had a challenge with an AngularJS app that was strictly using an API from a another domain and we had several environments (local, stage, prod – typical right? ) . Clearly those environment use different settings, and have different urls.

AngularJS provides nice ways of settings variables available across your app through injection.

Here is an example that creates a module ‘app.config’ (or appname of your choice) and sets constant (using this string you can inject and use it)

Define constants within AngularJS app

angular.module("app.config", [])

.constant("ENV", {
  "name": "development",
  "apiEndpoint": "http://localhost:5000",
  "basePath": "http://app.dev"
});

 

Inject and use variables within the app (CoffeeScript)

 

angular.module('app.controllers', ['restangular', 'app.config'])
.config (RestangularProvider, ENV)->
    RestangularProvider.setBaseUrl(ENV.apiEndpoint)
    RestangularProvider.setDefaultHttpFields(withCredentials:true)

At this point i can inject and use ENV throughout controllers and as you can see above in config state of initializing an Angular app. Since i’m using Restangular to interact with an API i needed to set a base url.

What happens on automated deployments? Solution

I’ve had a chance to use codeship and jenkins for building codebase and running tests, etc. Deploying to Staging or production would require that you replace config module with variables dependent on the environment. You don’t have to do anything manually. Here is the solution if you’re using Grunt.

NPM you need to install:

grunt-ng-constant

This is your Gruntfile.coffee (just a portion that is of interest, loading and using ng-constant) :

#Gruntfile

grunt.loadNpmTasks('grunt-ng-constant')

ngconstantConfig = 
      # Options for all targets
      options:
        space: "  "
        wrap: ""use strict";nn {%= __ngModule %}"
        name: "app.config"

      # Environment targets
      development:
        options:
          dest: "<%= yeoman.app %>/scripts/shared/config.js"

        constants:
          ENV:
            name: "development"
            apiEndpoint: "http://localhost:5000"

      stage:
        options:
          dest: "<%= yeoman.app %>/scripts/shared/config.js"

        constants:
          ENV:
            name: "stage"
            apiEndpoint: "http://staging-api.someurl.com"

Set configuration for grunt :

 grunt.initConfig
     ngconstant: ngconstantConfig

In regular JavaScript this is simply :

 

grunt.initConfig({ ngconstant: ngconstantConfig });

 

One more simple step (setting up the task)

env = process.env.NODE_ENV || 'development'

grunt.registerTask "build", ["clean:dist","ngconstant:"+env, "copy:ngconfig"...

This will register a task in a development environment “ngconstant:development” which will trigger NPM grunt-ng-constant to generate a file config.js that would include all the variables you defined in ngconstantConfig object for a specific environment.

 

Possible issue and solution

At least in my project (coffeescript) config.js was generated but too late and wasn’t picked up by other task that packaged everything into one file. My solution was to write a small task named “copy:ngconfig” that simply copied the generated file explicitly

This is simply copying config.js into Temporary location which then available for other task to package.

        copy:
            ngconfig:
                files: [ 
                    
                    src: ["<%= yeoman.app %>/scripts/shared/config.js"]
                    dest: ".tmp/scripts/shared/config.js"
                ]

 

Voila , your application will environment specific values on any environment

Next time your code is pulled into stage or production , it can run> grunt build   and code will be optimized, packaged into “dist” folder and deployed to optimally Amazon CDN

 

Share This: