Providing data via Angular 2 Services

Interaction with data in Angular 2, internally and from external sources, is based around the concept of services. Learning more about services is integral to learning how to create an Angular 2 component or application.

Angular 2’s biggest strength is the reliability of encapsulation and re-use, which means passing data to and between components can be a pain at first. You are highly discouraged from getting data from the DOM, making AJAX calls in your components is a no-no. How are you supposed to get data to your things?

This is where you start to use Angular Services. Services are an injectable class that allows you to keep all your functionality in one place. Here’s the official definition of a service in Angular 2 from the docs:

A service is a class with a focused purpose. We often create a service to implement features that are independent from any specific view, provide shared data or logic across components, or encapsulate external interactions.

You have data you need from an AJAX endpoint? Create a service.

You want to maintain state for an object that multiple components? Create a service.

Want to do anything cool with some data across your application? Create a service.

For those of you familiar with the pattern, Services in Angular 2 are really Singleton Service models. Its a single instance you pass around. It has a state, it has some methods. Its easily mocked and you know where the ‘meat’ of your application is at all times. It allows you to move the data manipulation out of the display code entirely.

Coming from a Vanilla JS background all of this may seem a little over complicated. While simplicity is something to strive for, there are good reasons for this level of abstraction:

  • Encapsulating the functionality of your services is a good practice
  • You can focus on functionality in your components with a well defined service
  • Mocking a service is easier than mocking an environment

Here’s some examples of services in action:

Example 1: A Simple String Returning Service

This is an example of a simple data service providing some data to a component. While extremely simple, it shows how to get data ‘into’ a component from an outside source:

The component itself relies on the service to provide the data to the front end. The value of ‘bar’, displayed in the component’s template actually comes from the service itself. When the component loads, it calls the “getBar” method of the service which returns a simple string.

While this example might seem very trivial, it lays some groundwork for the other examples. A service provides data external from the component in an ‘agreed’ upon way. This contract allows us to take some control of how we get the data away from the component, which should really just focus on how the data should be displayed.

Example 2: A service that allows us to share data between more than one component

This is an example of a service that allows a total of three components to interact together.

If you look at the code in the example, this small ‘app’ has three components that each include the CounterService. This extremely simple service allows us to interact with a single integer variable that can be incremented and decremented via two completely separate component’s buttons.

Again, while maintaining a ‘contract’ we can allow each one of these components to focus on the display and events rather than the actual manipulation of the data.

Example 3: A service that provides data from an AJAX (external) source

This is an example of an AJAX service providing data to a component. A ‘locally’ hosted JSON file is retrieved via AJAX in the service itself and then sent to the component. This component is able to interact with the data entirely through the service itself. This level of abstraction allows the component to strictly focus on the display and styling of the data provided by the service.

 

Promises vs Observables in your AJAX services

Promises are great and a well trod subject, I’ll leave it up to you to read more about their benefits (or you can revisit my previous blog post: http://blog.arroyolabs.com/2016/04/angularjs-2-ajax/). Observables, when compared to promises, allow you to specify not only when something is ‘done’ but when something has changed.

This most definitely comes in handy when you create a service like the example above that allows you to detect when any changes occur from your service.

A Final Note

While the final architecture of your application or bundled component is really a choice you need to make, I hope we were able to clear up some of the basics of using services in Angular 2.

 

Go basics – Control Structures (Part 2)

Presenting two important concepts you’ll need to know for your GoLang journey: Objects and Concurrency. Understanding these will allow us to talk about toolkits, frameworks, ORMs.

Today I’m going to present two important concepts you’ll need to know for your Go journey: Objects and Concurrency. That will allow us to talk about toolkit, frameworks, ORMs and so on, in future posts.

Object-Oriented Programming (OOP)

Overview

Is Go an Object Oriented language? If we use the most simple definition of Object as an abstract data type that has state (data) and provide a behaviour (code), I say Yes.

Since there is no inheritance in Go, we need to think in terms of composition. Except for that, we can find many of the same features like:

  • methods on any type we define, with no boxing or unboxing
  • automatic message delegation via embedding
  • polymorphism via interfaces
  • namespacing via exports

Now let me introduce some concepts with examples that will illustrate it.

Pointers

Go has pointers, but no pointer arithmetic.

x := 5

y := &x

fmt.Println(*y)

Output :

5

y points to x and the value of y is obtained using a * operator. The & operator is used to get the address of a variable.

The new operator is used to allocate memory to a pointer variable.

x := new(int)

*x = 9

fmt.Println(*x)

Output :

9

Structures

Are user-define data types which contains named fields. We can think of them as “object” in Go.

We declare structures using the type and struct keyword. Individual elements of the structure are accessed using the dot operator.

In the next example I also show composition:

type Person struct {
   Name string
   Address Address
   age int
}

type Address struct {
   Number string
   Street string
   City   string
   State  string
   Zip    string
}

Note that Go makes a difference between lower case and capitals in field definitions. The letter case refers to the scope of the field.  Name and Address (above) are public variables and age is a private variable. Capital names are publicly accessible.

This example in PHP looks like:

<?php
class Person {
    public $Name;
    public $Address;
    private $age;
}

class Address {
   public $Number;
   public $Street;
   public $City;
   public $State;
   public $Zip;
}

PHP does not have type hinting at the variable definition level, only the function level.

This type hinting / scalar values gives Go an upper hand when it comes to syntax checking.

Method

We can declare methods on any user-defined type.

A method declaration in Go is just like a function, except it has an explicit receiver, declared immediately before func. This function also takes advantage of named return variables, pre-initializing them for us.

Let’s extend the structures/classes defined in the previous example

func (p *Person) Greet() {
    fmt.Println("Hi, my name is", p.Name)
}

func (p *Person) Location() {
    fmt.Println("I’m at", p.Address.Number, p.Address.Street, p.Address.City, p.Address.State, p.Address.Zip)
}

In PHP:

<?php

class Person {
    public $Name;
    public $Address;
    private $age;
 
    public function __construct($Name,Address $Address, $age)
    {
        $this->Name = $Name;
        $this->Address = $Address;
        $this->age = $age;
    }

    public function Greet()
    {
        print_r("Hi, my name is " . $this->Name);
    }

    public function Location()
    {
        print_r("I’m at "
                . $this->Address->Number 
                . " " . $this->Address->Street
                . " " . $this->Address->City
                . " " . $this->p.Address->State
                . " " . $this->Address->Zip
        );
    }
}

class Address {
    public $Number;
    public $Street;
    public $City;
    public $State;
    public $Zip;

    public function __construct($Number, $Street, $City, $State, $Zip)
    {
        $this->Number = $Number;
        $this->Street = $Street;
        $this->City   = $City;
        $this->State  = $State;
        $this->Zip    = $Zip;
    }
}

Interfaces

An interface type is defined by a set of methods. A value of interface type can hold any value that implements those methods.

package main

import "fmt"
import "math"

type geometry interface {
    area() float64
    perim() float64
}

type rect struct {
    width, height float64
}

type circle struct {
    radius float64
}

func (r rect) area() float64 {
    return r.width * r.height
}

func (r rect) perim() float64 {
    return 2*r.width + 2*r.height
}

func (c circle) area() float64 {
    return math.Pi * c.radius * c.radius
}

func (c circle) perim() float64 {
    return 2 * math.Pi * c.radius
}

func measure(g geometry) {
    fmt.Println(g)
    fmt.Println(g.area())
    fmt.Println(g.perim())
}

func main() {
    r := rect{width: 3, height: 4}
    c := circle{radius: 5}

    measure(r)
    measure(c)
}

And this how it looks in PHP

<?php
interface geometry
{
    public function area();
    public function perim();
}

class rect implements geometry
{
    public $width;
    public $height;

    public function area()
    {
        return $this->width * $this->height;
    }

    public function perim()
    {
        return (2 * $this->width) + (2 * $this->height);
    }
}

class circle implements geometry
{
    public $radius;

    public function area()
    {
        return pi() * pow($this->radius,2);
    }

    public function perim()
    {
        return 2 * pi() * $this->radius;
    }
}

function measure($geometry) {
    print_r($geometry);
    print_r($geometry->area());
    print_r($geometry->perim());
}

$r = new rect();
$r->width = 3;
$r->height = 4;

$c = new circle();
$c->radius = 5;

measure($r);
measure($c);

Concurrency

Concurrency refers not only to CPU parallelism, but also to asynchrony: letting slow operations like a database or network-read run while the program does other work.

Even though, “Concurrency is not parallelism”, if this sentence means nothing to you, I suggest to check out Rob Pike’s excellent talk on the subject. It’s a great explanation with funny examples of gophers working in parallel and concurrent, you will enjoy all 30 minutes.

Go has a rich support for concurrency via goroutines and channels. This is one of the highlights of the language.

goroutines

A goroutine is a lightweight thread of execution.

Goroutines can be described as functions which run concurrently from other functions.

They’re invoked following the go keyword. As the function is invoked it runs concurrently and the rest of the code is executed without waiting for the completion of that function.

In comparison with other languages, we can consider goroutines as “green threads“. What does it mean? Go use multiplexing strategies to group goroutines and run them in a less number of OS threads. The advantages, among others, is that you can run concurrent applications in a single core system, threads are managed by virtual machine or binary library using User space instead of Kernel space, they start faster and with a low stack that can grow based on needs, just to mention some.

Here’s a small example of a goroutine:

package main

import "fmt"

func f(from string) {
    for i := 0; i < 3; i++ {
        fmt.Println(from, ":", i)
    }
}

func main() {
    f("direct")
    go f("goroutine")

    go func(msg string) {
        fmt.Println(msg)
    }("going")

    var input string
    fmt.Scanln(&input)
    fmt.Println("done")
}

Channels

Channels are the pipes that connect concurrent goroutines. We can think on channels as process intercommunication. Go uses cooperative multitasking between goroutines. So if one routine never yields, then the other will never run.

You can send values into channels from one goroutine and receive those values into another goroutine.

We can use channels to synchronize execution across goroutines.

Channels must be created before being used, using the chan keyword.

package main

import "fmt"

func main() {
    messages := make(chan string)
    go func() { messages <- "ping" }()
    msg := <-messages
    fmt.Println(msg)
}

Since I couldn’t find a better example without the need of writing a post explaining its concepts, I bring you a simple one in Java using multi-threading:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

class Server
{
   public static void main(String[] args) throws IOException
   {
      ServerSocket socket = new ServerSocket(9000);
      while (true)
      {
         final Socket s = socket.accept();
         Runnable r = new Runnable()
                      {
                         @Override
                         public void run()
                         {
                            doWork(s);
                         }
                      };
         new Thread(r).start();
      }
   }
   static void doWork(Socket s)
   {
   }
}

Thanks for reading! I hope you enjoy it.

See you on the next post!

Golang food for thought

For most folks switching programing languages is a big deal and it usually takes some production catastrophe or poorly aging codebase to motivate the switch. It’s like when someone has that way too special night with tequila and decides “never again.” For others they switch and/or experiment with other languages like they change their socks. I compiled a list of some good reads by various folks who have switched from other languages to go.

Golang is a hot topic among developers these days.  languages like Golang and node.js are getting a lot of attention.

For most folks switching programing languages is a big deal and it usually takes some production catastrophe or poorly aging codebase to motivate the switch.  It’s like when someone has that way too special night with tequila and decides “never again.”  For others they switch and/or experiment with other languages like they change their socks.

I have read a lot of posts about folks giving up their monolith Ruby on Rails app in favor of Golang (and micro-services in some cases), but saw a number of other languages pop up too. Golang is not the magic bullet for everything, but it does do many things very well. It is fast and concurrent and gives you a lot of powerful networking and infrastructure tools.

Here is a list of links I compiled by various folks who have switched from other languages to Go. Hopefully they are good reads and useful.

Ruby to Golang
http://blog.parse.com/learn/how-we-moved-our-api-from-ruby-to-go-and-saved-our-sanity/
https://www.iron.io/how-we-went-from-30-servers-to-2-go/
https://madebymany.com/blog/replacing-rails-part-1-lets-go
https://medium.com/building-timehop/why-timehop-chose-go-to-replace-our-rails-app-2855ea1912d#.7o3jzlyag

Node.js to Golang
http://blog.digg.com/post/141552444676/making-the-switch-from-nodejs-to-golang

PHP to Golang
https://news.ycombinator.com/item?id=4364820

Scala to Golang
http://jimplush.com/talk/2015/12/19/moving-a-team-from-scala-to-golang/

Python to Golang
http://jordanorelli.com/post/31533769172/why-i-went-from-python-to-go-and-not-nodejs
https://www.whitesmith.co/blog/why-i-started-to-use-golang-more-than-python-or-ruby/

Java to Golang
http://www.javaworld.com/article/2459212/scripting-jvm-languages/why-one-developer-switched-from-java-to-google-go.html

Additional food for thought
https://peter.bourgon.org/go-best-practices-2016/
https://medium.com/@tjholowaychuk/farewell-node-js-4ba9e7f3e52b#.7hj216pfw
http://blog.dimroc.com/2015/05/07/etl-language-showdown-pt2/
http://www.infoworld.com/article/3071623/salary/want-to-boost-your-salary-learn-scala-golang-or-python.html

End to End testing your Vanilla JS App with Protractor

ProtractorJS is a robust and easy to use e2e test framework specifically designed for testing AngularJS applications. With some simple edits and a slight change in thinking, you can also use it to test your non-angular web apps and provide some sanity to your testing strategy across projects.

ProtactorJS is an end to end test framework from Google used to test AngularJS Apps. While similar to existing tools like CasperJS, ProtractorJS is specifically designed for use with AngularJS.
With minimal effort you can use Protractor with your Vanilla JS web app as well. Why would you do this?
For one, using the same test framework for all you apps provides some sanity to writing tests for all of your projects. And you can’t honestly tell me you have all your apps converted to AngularJS already.
Second, it’s gaining popularity and for good reason. It’s a solid testing framework and is relatively easy to set up. Also, it has the backing of a very well known company (cough cough, Google) so it will be around for a long time.
Finally, it’s use of Jasmine and suite structures allow you to write some flexible tests. Encapsulate your logic, group stuff in ways that make sense. No more fragile tests!
Enough stumping, let’s get to the parts you actually care about.

Installation and Set Up

While I’ll point you at the official docs for installation instructions, I’ll provide the basic elements required to installing and running your Protractor tests:
  1. Protractor, Karma & Jasmine
    • Clearly, you need to install Protractor
    • Protractor uses Karma to connect to Selenium
    • Jasmine is used as the testing syntax.
      • You can use other frameworks, but my preference is Jasmine.
  2. Selenium Server & Webdriver
    • Protractor interacts with your tests using Seleniums Server and Webdriver. You can run Selenium locally or use a hosted service like Sauce Labs.
    • Local installation and setup is turn key simple using NPM.
  3. A Web server
    • Since your tests use a real browser to execute, you need a host of some kind.
    • It’s entirely possible to run your tests against an external server (like your staging server), but in practice I like to serve locally. In our example I used the local-web-server NPM package.

Protractor Test Concepts

Again, I’ll point you to the main documentation for longer descriptions of the concepts, I wanted to point out some that need to be discussed when prepping your protractor tests for execution on your VanillaJS app.

Config File

A config file sets up some required variables and tells Protractor how to run its tests. This includes a directory where your tests are held, the testing framework you use to write your tests and the address to the selenium server instance you use to run Karma.

Spec File (Test Suite) – “Describe”

Test suites are groups of testing conditions that focus on a particular section or part of your application. Using Jasmine, these are structure with the “describe” function and a brief string indicating the portion of the application under test.

Test Hooks

Hooks are small functions that are called during test executions. An example is the beforeEach hook we use to set up our tests for use with non-angular code. See the note below on exactly what goes in this hook.

Test Blocks – “It”

Test blocks are identified by an “it” phrase that describes in simple terms what you expect to happen. This is useful for turning user stories into tests like “User Registration Form should validate user input”.
These test blocks do have some minimal setup but are mostly for performing actions and asserting values. Check out our example code to see some of this in action.

Page Objects

Page Objects are similar to test fixtures in other testing frameworks, but thats underselling the usefulness of this concept. Page Objects are small JS objects where you can encapsulate and abstract out common page elements and share between your tests.
Use these to abstract out some commonly tested things, like getting the text or value from a page element. If you use your page object in all your tests, you only have one place to update when a change is made (instead of having to update ALL your test suites).

Running Protractor on your Vanilla JS App

Like we noted above, Protractor was designed for testing AngularJS apps by default. A large difficulty in e2e web app testing is knowing when something has rendered on the page and is ready to have some interaction. AngularJS abstracts how you work with the DOM in JS as well as having some control over how something is determined to be “ready” using Zones.js.
Three major things need to be done to make sure your Protractor test will actually work with out Angular:
  • Expose the web driver in a way you can access the DOM for interaction.
    • Due to the nature of how Angular abstracts the DOM and how it takes over all the app’s event cycles. We need to expose the Selenium Web Driver in a way you won’t hate.
    • Add this line to your onPrepare hook in the config file to assign the web driver to an global variable called “dv”
      • global.dv = browser.driver;
  • Tell the test not to wait for Angular to give the “go ahead, I’m ready” signal.
    • Protractor uses Angular to tell it when the page under test is ready to be tested. We need to skip this in order to test our non-angular app.
    • Add this to each test suite’s beforeEach hook to make sure the test knows to run as we expect
      • dv.ignoreSynchronization = true;
  • Start thinking about your tests with Promises
    • While I’m sure most of us at this point have seen and used Promise style functions. When testing an Angular app, using the default locators is easy. Since we are testing our app using the native web driver, we need to use a promise to allow Selenium to return the DOM element itself. Really though, it’s not that tough.
    • Here is an example where we want to assert the value of an element with the css ID of “foo” using a series of chained promises.
expect(dv.findElement(by.id('foo')).getText()).toEqual(“Bar”);

Plugin – Protractor Utils

Protractor does indeed have a very basic plugin system that gives end users some ways to extend base functionality. I’m still trying to understand this system myself (I haven’t figured out how to use a plugin that isn’t globally installed) I have found one that is very useful called jasmine2-protractor-utils.
I’ll leave some of the longer explanation of this plugin to the author, but my favorite feature is the ability to take a screenshot of the browser in the test on suite or block failure. Once you get things up and running so your tests are running automatically, having some visual artifacts of a failed test will help you replicate and diagnose what and how things went wrong.

Example – Movie Vote

Here is an example (very small) Web App demonstrating a very basic suite of Protractor tests. You can simply clone this repo, install the required packages using the package.json file and run these tests. Simply follow the instructions in the README.md file.
https://github.com/arroyolabs-blog/movie-vote-protractor
For an example of an intentionally failing test, check out the `mv-home-fail.spec.js` test in the tests directory.

Scaling your business with Technology @ SBF

We’ll be at Silicon Beach Fest Friday 8/25 for our CTO panel, “Scaling your business with technology.” If you are in LA please join us.

We’ll be at Silicon Beach Fest Friday 8/25 for our CTO panel, “Scaling your business with technology.”  If you are in LA please join us.

We have a great line up of speakers with some probing questions about how they build and scale their businesses.  Find out what kind of bumps they hit along the way and how they tackled those issues.

John Arroyo, Arroyo Labs, CEO (moderator)

Tina Denuit-Wojcik, Enplug, CTO
Paul Kasinski, Sky Zone, CTO
Erin Neff, The Black Tux, Director of Product
Andy Bauch, Wizely Finance, CTO
Cullen Zandstra, FloQast, CTO
Andres Buritica, CTO of Well Nest; Dodgers / R\GA Accelerator, Mentor

Official Description: CTOs and product experts talk about their journeys growing a business with technology. We will get insight into how certain technologies and concepts helped them handle growth and deal with the challenges of scale.

http://siliconbeachfest.com/

Electron and Angular2: simple App example

In our first post about Electron, we were covering the main topics about what is and how it works. This time we will cover how to create a dummy application using Electron and Angular2 as a front-end framework.

The application tree should be something like this picture:

tree

we can observe:

  • gulpfile and package.json: we will talk later about this 2 files, by now we can just say that are needed to build the application.
  • assets: The package.json is a file useful to give directives to Electron, with this method we can order show/hide the window borders, icon, maximized/minimized, etc.
  • frontend: here we got the content relative to the front end, more especifically all the Angular2 stuffs.
  • main: contains the index.js referenced by assets/package.json and is the start point of our electron application.
  • Tsconfig and typescript files are needed to transcode the typeScript code into javascript.

The main gulp tasks needed to build and “deploy” the application sources:

gulp_file_main_tasks

from this file, the most important tasks are frontend and electron. The first one copy all the content from the source path.

The principal Electron tasks to run the application:

main_electron_gulp_tasks

 

The  second task begins the transcoding and building of the application.

   The electron package.js, it is useful to pass directives at start time, the format of  is exactly the same as that of Node’s modules, and the script specified by the main field is the startup script of your app, which will run the main process. An example of your package.json might look like this:

package_electron

   We need to remember, if the main field is not present in, Electron will attempt to load an “index.js”.

The main index file loaded by electron at first time looks like a common js file:

main_electron

Then, the final product, the application up and running:

app_running

    we realize that is a common web application, the tick here is to work in the look & feel to “hide” that common details (relative to the chromium browser) and make an effort in order to show the appplication like a elaborated desktop app. It is possible to change icon, task bar, menus, system buttons etc. Even if you don’t like the squared and classical window you can hide the background and create a “floating” app with alpha and the shape you want.

   In the sample app we’ve created a minimal environment with an image background and a button in the middle. If you press the button, you will get as result a notification at the notification area, that position will be according to the SO where the app is running, in my case Im running ElementaryOs so the notification area is in the upper-right conner:

notification_electron

The cool part here is, that notification is executing in real native code. The Electron API does the hard work to communicate to the SO what we are trying to do, in our case, show a notification with a text and image.

That’s all for this second part of Electron, you can download the code from here thanks for reading!

 

Unit testing your Javascipt with Jasmine, KarmaJS & Travis CI

Unit testing is an important part of any software project but until recently it was difficult to test your front-end javascript and oft neglected by developers. Using Jasmine, Karma and TravisCI we will show you how to painlessly automate your JS testing.

Javascript is used on over 93% of websites today and used to do all sorts of front end magic. Most likely, your interactions with the web are provided via Javascript.

With any luck you have moved beyond the anti-patterns of yore and you have abstracted your JS functionality into some coherent objects to maintain your sanity. Now it’s time to start testing these pieces of code.

Testing Tools

I explored javascript unit testing using three tools: Jasmine, Karma and TravisCI. Using all three in conjunction seems to get the best results for a larger team.

Jasmine

Jasmine is a very popular javascript unit testing framework, very similar to many other xUnit testing frameworks like phpUnit and jUnit. Many other testing tools like actually use the same syntax (if not use Jasmine outright) so this is a pretty good thing to learn about.

I should note, unlike many other xUnit frameworks, Jasmine is BDD or a Behavior Driven Development framework. This is a fancy way of saying you structure your test suites in a way where you test ‘behavior’ scenarios rather than simple methods and functions.

KarmaJS

Karma is a test runner that executes your unit tests in a ‘real browser’. In short, it runs your Jasmine tests in a real browser via websockets.

This means you can test using a headless browser like PhantomJS or a real browser like Chrome. This really becomes useful when you need to test in multiple browsers, but especially useful when you need to run your tests locally (via Chrome) or remotely on a CI (in our examples below we run the unit tests using Chromium. More on that later).

There’s a little setup involved with Karma, but not too much. Honestly, it took less time to get my Karma config created than it did to write my example unit tests.

Travis CI

Travis CI is a hosted continuous integration tool that will watch your repo and execute your tests on certain conditions like a push or a pull request. It is also is free for your open source, or at least your public, Git Hub repos. Best of all, you can also show a super cool ‘build status’ badges in your github readme page.

Travis CI: Using Chromium

Please note that if you run your KarmaJS tests locally using Chrome, you will need to make sure Travis CI knows to use the open source equivalent Chromium as it fit’s into its ‘free tier’ licensing scheme.

Below are the key things you need to set this up, all of this code can be found in our examples below:

.travis.yml config

We need to tell Travis to install the Chromium browser package when it creates the container. Add the noted entry (‘export CHROME_BIN=chromium-browser’) into the “before_install” section of your travis config.

...
before_install:
 - export CHROME_BIN=chromium-browser
...
karma.conf.js

Next we need to determine if our tests are executed by Travis, and if so, tell Travis to use Chromium (which is aliased to CHROME_BIN from our config above) when exec’ing our tests:

// Config values to allow TravisCI to run chrome in it's container
browsers: ['Chrome', 'ChromeCanary'],
   customLaunchers: {
   // tell TravisCI to use chromium when testing
   Chrome_travis_ci: {
      base: 'Chrome',
      flags: ['--no-sandbox']
   }
},

...

// Detect if this is TravisCI running the tests and tell it to use chromium
if(process.env.TRAVIS){
   config.browsers = ['Chrome_travis_ci'];
}

I think its easiest to look at config from our example code to see exactly where this is placed in your config: https://github.com/arroyolabs-blog/movie-vote/blob/master/karma.conf.js

Example Project: Movie Vote

I created a very basic ‘web app’ (this is a stretch) to learn more about using Jasmine/Karma/CI with javascript.

It’s a simple JS class where a user can up or downvote a movie. While it includes a very basic html page you can run in your browser to see the class in action, the real magic is in the testing.

Here is a link to the Travis CI page showing our passing tests: https://travis-ci.org/arroyolabs-blog/movie-vote

Example Project 2: ng2 3 page SPA

If you are using ng-cli, karma is already configured for you. Running it is super easy and the hardest part is finding a CI solution that works for you.

Check out our super simple example and review the Travis Config to see this in action: https://travis-ci.org/arroyolabs-blog/effective-funicular

Conclusion

Testing is a very important part of software development and can be fun and easy once you get things set up to run automatically. Hopefully after reading this post you will have a good idea of how to integrate unit testing into your JS projects.

Go basics – Control Structures

Hello readers, in this episode we’re going to talk about languages structures, as a preface to future post where I will show you all this stuff in action, with OOP and concurrency examples and reviewing some toolkits and frameworks.

Of course, this is not an exception, on each topic of this post I will show you an example of how it can be used and a comparison with languages to make it easy to understand for those whom come from PHP, C, Java, etc.

Loops and Bifurcations 

For

Go has only one looping construct, the for loop.
The basic for loop has three components separated by semicolons:

– the init statement: executed before the first iteration
– the condition expression: evaluated before every iteration
– the post statement: executed at the end of every iteration

The init statement will often be a short variable declaration, and the variables declared there are visible only in the scope of the for statement.

The loop will stop iterating once the boolean condition evaluates to false.

Note: Unlike other languages like C, Java, or Javascript there are no parentheses surrounding the three components of the for statement and the braces { } are always required.

Following there’s some examples that shows each variation with its equivalent in PHP:

While loop in GO
var counter int = 0

for counter < 100 {

    counter += 1

}
PHP Version
<?php 
while($counter < 100){ 
     $counter++; 
}
 Foreach in Go
import "fmt"

for key, value := range list {
    fmt.Printf("%d => %s\n",key, value)
}
PHP Version
<?php 
foreach($list as $key=>$value){     
    echo "{$key} => {$value}\n"; 
}
Common For loop in Go looks like C
for i := 0; i < 10; i++ {
	fmt.Println("The value of i : ", i)
}

If-else

The if statement in Go, like For statement, does not need to be surrounded by  ( ), but the braces { } are required.

Like for, the if statement can start with a short statement to execute before the condition.

Variables declared by the statement are only in scope until the end of the if.

As many other languages, it support the else statement.

 Chained if statement in GO
if value, ok := m[key]; ok {
    fmt.Println("value is:", value)
}
PHP Version
if( isset($_POST['id'])) {
    $id = $_POST['id'];
}
If-else in Go
if _string == "my example" { 
    fmt.Println("this is ",$string) 
} else {
    fmt.Println("this is no my string") 
}
If-else in PHP
<?php
if($_string == "my example"){
   echo "this is ".$string;
} else {
   echo "this is no my string";
}

switch

This is a multiple choice statement that allows us to select between more than two options, and most of the time faster than if-else.

The differences against other languages is that each case body breaks automatically, unless it ends with a fallthrough statement,

and Switch without a condition is the same as switch true.

This construct can be a clean way to write long if-then-else chains.

Switch in Go
switch i {
	case 0 : fmt.Println("Zero")
	case 1 : fmt.Println("One")
	case 2 : fmt.Println("Two")
	case 3 : fmt.Println("Three")
	case 4 : fmt.Println("Four")
	case 5 : fmt.Println("Five")
	case 6 : fmt.Println("Six")
	case 7 : fmt.Println("Seven")
	case 8 : fmt.Println("Eight")
	case 9 : fmt.Println("Nine")
	default : fmt.Println("Unknown Number")
}
Switch in PHP
<?php

switch $i {
	case 0 : 
               echo "Zero";
               break;
	case 1 : 
               echo "One";
               break;
	case 2 :
               echo "Two";
               break;
	case 3 : 
               echo "Three";
               break;
	case 4 : 
               echo "Four";
               break;
	case 5 :
               echo "Five";
               break;
	case 6 :
               echo "Six";
               break;
	case 7 : 
               echo "Seven";
               break;
	case 8 : 
               echo "Eight";
               break;
	case 9 : 
               echo "Nine";
               break;
	default : 
               echo "Unknown Number";
}

Functions

Functions are defined using the keyword func followed by the function name, arguments and the return values.

func say_hello() {
    fmt.Println("Hello From the function")
}

Parameter

Functions may have a return value. This value can also be named.

Simple function in Go
func Add(first, second int) (result int){ 
    return first + second 
}
Same example in PHP
<?php
function add($first, $second) {
   return ($first + $second);
}

Multi-types result

This is one of Go goodies that does not has equivalence in other common languages like PHP or C. In Go we can return multiple values of different types, also naming each returned parameter. Let me show an example:

func divide(n,d int) (result float, err error) {
    if d == 0 {
        err = errors.New("")
    } else {
        result = n / d
    }
    return result, err
}

Variadic

Functions can take 0 to undefined variables of a particular data type.

func sum(args ...int) (total int) {
	total := 0
	for _, i := range args {
		total = total + i
	}
	return total
}

Closure

Go supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.

func Sequence() func() int {
    i := 0
    return func() int {
        i += 1
        return i
    }
}

nextValue := Sequence()

fmt.Println(nextValue()) // 1
fmt.Println(nextValue()) // 2
fmt.Println(nextValue()) // 3
fmt.Println(nextValue()) // 4

Do not miss the second part of this post where we will use this concepts while discuss OOP and concurrency.

Moving to Slim PHP

After developing Erdiko for over 4 years we are making some big changes for the next major release. We are modifying the framework to support Slim. Erdiko will soon be built on top of the great features of the Slim PHP micro framework.

We have been developing our open source micro framework for 4 years now.  We haven’t publicized it much but we’ve poured hundreds of hours into it and use it considerably on client projects. The framework and many of its modules are used and liked in the PHP community.

We are ready to take Erdiko to the next level and in the process of architecting a new Erdiko framework.  The next version will be more modular, better tested and, most importantly, built on top of an existing micro framework.

When we started Erdiko the other micro frameworks weren’t there yet, thats part of the reason we start Erdiko.  Silex and slim were in infancy, lumen didn’t exist (and Laravel was just starting to get more notice), and heck composer was less than a year old and wasn’t on many people radar yet.  Fast forward a few years and we now find a very different landscape for PHP and JavaScript development.

Speaking of this landscape, the fact that we can and do move much of the app to the front-end with powerful JavaScript frameworks means the duty of the back end has changed.  You no longer need to add ridiculous layers of front-end logic in your PHP classes and templates.  This shift alone means you need to rethink what you need from a php framework.

Thats where micro frameworks soar…places where you need a fast backend and leveraging a smarter front-end (e.g. SPA with JavaScript).  Add the great SaaS tools at your disposal as well and you have all the ingredients to make performant websites that you can grow your business with.  You don’t need a big bloated full stack in most cases.  If you do, often the built in feature X just won’t cut it and you end up integrating a 3rd party package or writing that component yourself anyways.

Now back to the topic at hand, what’s the deal with SlimPHP?  After reviewing numerous frameworks it became apparent that SlimPHP was the best of bunch for the kind of code we like, community we like and of course the kind of features and performance we like.  It’s router, http objects and flexibility has Erdiko beat.  We also looked at and experimented with Silex, lumen and some others before making the decision.

Erdiko adds the MVC and theming support to a typical micro framework.  We’ve developed some useful components and feel that adding these on top of an existing framework will make development even more efficient and flexible.

Erdiko has some special features that will aim to make development more enjoyable and lead to better applications.  We have been distilling pieces of Erdiko that will be moved and improved to work with Slim.  Right now we feel the configuration, theme engine and controller support will make the cut.  Actually quite a bit of erdiko will exist in the new framework, but we will strive to leverage slimphp and the slim paradigm whenever possible.  On the model side we have included wrappers for powerful ORMs so that developers can pick the best one for the job and install with one command.

Electron and cross-platform applications

These days with the latest new technologies applied to apps we want everything faster, accessible and lightweight. To accomplish these goals, companies find that the developers do their job with tools that  require  low effort and can be used in many places.

Then, developers went to work and improve a kind of automatic programming with open source. For this reason, developers at Github started to work on developing something quick and comfortable without the need to learn another programing language. They wanted a framework to get a piece of product without reworking the same application on multiple platforms.

Chromium and the open source

Cheng Zhao, Electron’s director, realized the advantages of Google Chromium and their open source, at the beginning developed by Google Inc. to the community of developers who needed their own browser, without realizing about the potential which was delivering to Github’s developers. Later on, they started working on that for long weeks to get the Chromium core.

Finally, with the job done and successfully tested, it was launched in April of 2015. A few months later, Microsoft launched Windows10 with the possibility of installing applications from the Windows store (web based) then. For that reason, they believed in the great potential of this project.

But, what is Electron?

Electron is an open source project (GNU) written by  Cheng Zhao, an engineer working at GitHub  in Beijing  for the Atom text editor team. Its combines Google Chromium and NodeJS´s features in one codebase. Because of that, Electron updates with their releases. Under the hood, together they share the same Javascript engine V8, and it means that we, as developers, could use both context at the same time (something that, with a regular web app would be impossible)

NodeJS has supported Mac, Windows and Linux equally from the version 0.6 and Google Chromium is also cross-platform. The Electron’s API philosophy is that it only adds features supported by all platforms.  For example, on Windows, applications can put shortcuts in the JumpList of task bar, and on Mac, applications can put a custom menu in the dock menu. Electron conveniently allows developers to send notifications with the HTML5 Notification API, using the currently running operating system’s native notification APIs to display it.

Forget to develop one web application written in asp.NET and another one in C# for desktop, now with Electron you can develop only one NodeJS application and rebuild for desktop platform. Besides, it is an open source and you can improve some aspects such as performance or your custom features.

The project at present.

The team released Electron when they launched Atom two years ago, known as Atom Shell, the framework they’d built Atom on top of. In those days was the ‘driving force’ behind the features and functionalities that Electron provided as they pushed to get the initial Atom release out.

Today as a dedicate project, Electron is a growing community of developers and companies building a lot of apps (just in the past year it has been downloaded over 1.2 million times) and releasing the mature 1.0 version.

electron-downloads

In the last times Electron has since been used to create applications by companies as Microsoft, Slack, Docker etc. we can inspect a few of them here.

Angular2 and the future of HTML5 on desktop

  • The main process  provides platform specific API’s and taking care about the application lifecycle
  • Meanwhile the render process  provides functionality for the user interface, in this case Chromium with all it’s advantages such as Chrome Developer Tools available right inside of your desktop app.
  • Angular2 currently has become one the most popular open source javascript frameworks in the world:
    – Its modular so we can choice what part of Angular use
    – its modern, is targeted on ES6 and “evergreen” modern browsers, no hacks or workarounds are needed, allowing developers to focus on the code related to their business domain.
    – its focused on mobile devices which means that we can port a current mobile applications to desktop just wrapping up in Electron.

Looks like Electron + Angular2 is a pretty good combination.

In the next post about Electron we will make a real code basic application to demonstrate the use of this nice stack.

My two cents

There are a lot of good features but here are some collected pros and cons:

Pros:

  • No cross-browser compatibility issues
  • No loading of remote assets (then no latency)
  • Reuse of npm modules, out of the box
  • hardware access
  • Native-ish features (system dialogs, file selection dialogs, notifications, printer, etc)

Cons:

  • The size, the Electron API Demos for linux compress takes 41MB (it could be worst, giving account that is a complete and customizable browser).