Angular 2 Pipes

Angular 2 pipes replaced filters as a method to format and manipulate text for output. We explore some background behind pipes and provide some simple examples to explain these concepts.

Introduction

Pipes are a feature of Angular 2 that allows you to contextually manipulate and format text on the front end. From simple date formatting, to a complete transformation, pipes allow you to separate how you display data provided from the backend.

Prior to Angular 2, text transformation was provided by “filters”. Conceptually the same in usage, Angular 2 gives us a little more power and flexibility to how we can package up the text manipulation power of these smaller components.

Commonly used & built in Pipe examples

Some pipes merely intake a string and return a formatted result, others take parameters to help construct the resulting output.

The best part of using these are literally built into the framework. No extra file library inclusions are required.

UpperCasePipe & LowerCasePipe

UpperCasePipe & LowerCasePipe are two built in pipes that allow you to transform text, as their names would imply, before outputting to the DOM.

These are the most simple of pipes (and really, could be replace with some CSS) but they illustrate the mechanic: The value you wish to transform goes on the left a “pipe” (this “|” character) and then the transformative function goes on the right.

Here are two quick examples:

<p>{{ firstname | lowercase }}</p> // Foo -> foo 
<p>{{ lastname | uppercase }}</p> // Foo -> FOO 

Pretty simple, and lets us explain some more complex setups.

DatePipe & CurrencyPipe

There are also some slightly more complex built in pipes, some of which take in full objects, other take expressions from which to transform the text they transform.

DatePipe

DatePipe formats and transforms a Date object into a string based on a provided expression and locale rules.

Here are some example DatePipe usages with some of the build in expressions:

<p>{{ now | date }}</p> // Nov 15, 2016 
<p>{{ now | date:'medium' }}</p> // Nov 15, 2016, 12:05:08 PM 
<p>{{ now | date:'M-d-y' }}</p> // 11-15-16

CurrencyPipe

Like the DataPipe, CurrencyPipe also formats using a provided express and based on the browser’s locale. I’ll leave you to check the official documentation, but this is a very basic example.

<p>Total: {{ total | currency:'USD':true:'4.2-2'}}</p> // $10.99

Creating Custom Pipes

Creating custom pipes can be a little scary and intimidating at first, but is not hard in principle. We’ll walk you through the basics and provide a few examples to work from.

Structure and formatting your Pipe definition

Creating a pipe is pretty easy, in fact it looks like how you create an angular component. Let’s break down this example:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'foobar'})
export class FooBarPipe implements PipeTransform {
 
    transform(value: string, args: string[]): any {
        return "FooBar" + value;
    }
 
}

After including the Pipe & PipeTransform libraries from angular/core, you simply need to use the @Pipe decorator. The decorator accepts a parameter called “name” which is used to reference your custom pipe in your template code.

Finally, your pipe must implement a method called “transform” which, coincidentally, transforms your provided text or object.

And including into your app module is also quite simple:

import { FooBarPipe } from './foobar.pipe';

...

@NgModule({
 imports: [ BrowserModule ],
 declarations: [ App, FooBarPipe ],
 bootstrap: [ App ]
})
export class AppModule {}

Parameters

As we noted previously, you can also pass parameters to a pipe to affect the how the value piped in is transformed. You can send multiple parameters as well each separated by a colon (“:”) and extract them in your transform method.

Example 1: Prefix “FooBar” to a provided string

This is a simple example of a custom pipe that prefixes “FooBar”:

Example 2: Multiply a provided integer by Number

Show an example where we multiply the output by 42 (provided by the component) and return a result. This will illustrate the idea of stateful pipes.

Example 3: Convert string to Pig Latin

Here is an example of a pipe that converts a provided string to Pig Latin.

Conclusion

Pipes are a useful and easy to learn concept in angular 2. While it’s easy to think they are limited to formatting and displaying text, we have also shown some re-usable examples where a company can have a small arsenal of pipes at their disposal.

Angular 2 Routing

Angular 2 Routing is bit complicated when compared to routing in Angular 1.x but it is very powerful. We hope to clear up some of the common confusion when setting up routing and provide some practical examples as references.

Understanding routing in you application is the key to creating a single page application. Routing is what allows view navigation in your application like ‘detail views’, end user bookmarking and even allows you to set up a ‘logged in’ version of your applications views.

Routing isn’t included by default in Angular 2, in fact you have to explicitly include it as a library. I also will say, it’s not incredibly intuitive to configure. We’ll take some time to explain the history of the router and dive into some of the basic concepts.

Basic Concepts of Routing in Angular 2

Router Library

The router itself is implemented in the optional Router Module, which is kept separate to keep the base library size low. Include it in your main module like this:


import { RouterModule } from '@angular/router';

...
@NgModule({
 declarations: [ ... ],
 imports: [
     RouterModule.forRoot(routes),
     ...
 ],
 providers: [ ... ],
 entryComponents: [AppComponent],
 bootstrap: [AppComponent]
})
export class AppModule {

}

Base HREF

The base HREF is the starting point for your application and is used to create your home route. It’s this starting point that your browser will also use to create a history to prevent ‘breaking the back button’ which is always a sticking point in SPAs.

Here’s the syntax you need to add to you html:

<base href="/">

Configuration & Routes

const routes = [ 
    // Default, or home, path. This matches your Base HREF
    { 
        path: '', 
        component: HomeComponent 
    }, 

    ...

    // Wildcard, or the 'catch-all' route pattern. If the requested
    // route does not match anything above, this route is displayed.
    { 
        path: '**', 
        component: HomeComponent 
    } 
];

Resolves & Guards

Resolves are services that must be completed before allowing the route to be accessed and loaded. This is how we can ensure that the data is available for the route prior to allowing the user to access the route.

A quick example of this would be a UserResolve class that retrieves a list of users before displaying the route.

Guards are a method to prevent a route from being accessed unless a certain state is met.

A quick example of this would be a LoggedInGuard class that prevents a user from accessing a route unless they are logged in.

Child Routes

Child routes are a way to add specific routes to a feature.

Example 1: A One Route Application

Below is an example of an application with a single route. This illustrates including the router module, a base href and a very basic route configuration.

Example 2: A One Route Application with a Resolve

Below is an example of an application with a single route that requires a service to resolve a data retrieval before rendering.

Example 3: A multiple route application with a child route

Below is an example of an application with two routes and a child route.

Conclusion

While it may take some time to completely wrap your mind around routing in angular it’s clearly an important part of creating a real SPA. Don’t be afraid to take and reference your own notes!

Sample Application Using The Erdiko Framework

This time we will show you how to set up a quick and easy application using the Erdiko framework. You can roll the dice and try your luck!

Sometimes we need to create an application from scratch and there are a little set of things to get in mind relative to how and what we want to build: what language, to define the architecture, gather all the assets and (maybe) a long list of items more.

   A great idea is to use the Erdiko framework for building web apps quickly using well known MVC patterns and make the php deployment easy. Here we will create a little web app to roll a dice and get a result in two flavors: using a view and getting the result as AJAX call.

MVC is the separation of model, view and controller, it’s simply a paradigm; an ideal that you should have in the back of your mind when designing classes. Avoid mixing code from the three categories into one class

Roll the dice

    We took a fresh installation of Erdiko framework and created a view to the main page.Here we see 2 buttons:

  • One for go to the ‘get’ request.
  • Another one to get the same request above but using an ajax call, in this case you will not note difference into the current page after click the button because the roll result is coming in background as a json object.

 

new_main

The Model

    For the model we created a super-very-simple class with just only one method, “roll_dice”.

   This method returns a random value and it’s very easy to understand, the value will be used later to select the correct dice image and set up the view.

The Controller

erdiko_app_controller_get_dice_action

    With the goal of keep things simple, we will reuse the Example controller and added one new action: getDiceRequest(). What the action does is create a new Dice model instance and get the random value generated with the call to Dice::roll_dice(). After that, sent the result to the view to be shown in the front end.

    Also to the ajax call we will use the existing AjaxExample controller and made a very similar action: getDice().

erdiko_app_controller_ajax_get_dice_action

   What it does is mimic the action of the getDiceRequest action in Example controller but is managed in different way: the browser will never change the page and the result of the Dice::roll_dice() method is sent encapsulated in a json response.

   On the other side, the view is waiting for this json object in order to change the things quiet. Is for that reason the browser will never open a new tab or hop to a new page.

The View

   For this post finally we created 2 view, the main and the dice request. Both are purely 100% html as we can see:

erdiko_app_controller_index

    We can note how the controller knows how to insert javascript code to the final html render with the public function addJs() and is a good  “glue example”  between php world and html world, and how to keep a minimal separation of concerns.

jscode

A framework follows the Hollywood principle: “Don’t call us; we’ll call you.” It acts as a constraint that solves the particular problem it was designed to solve

    The Javascript part is not so complicated. We take the dice value and map the name of the right picture to show in the view.

    If the request is solved by backend php rendering instead of an ajax response with javascript, we just display the expected image with pure html:

dice_examples_view

Et voilà, the dice number is shown!:

dice_ajax_get_request

    I hope you enjoyed this post. You can apply good design patterns and quickly build a web app with the Erdiko framework. Thanks for reading!

https://github.com/arroyolabs-blog/roll-dice

Docker + xdebug

Presenting various ways to setup and configure your docker container with xdebug and how to integrate with your IDE.

Debugging, an issue that all developers should live with.

There are several strategies we can use to manage debugging, from stopping execution after dump / print the content of the variable we want to inspect (I still with this more often that I’d like to admit) to more sophisticated tools or web-server  modules.

Okay, it does not enough complicated so, now let’s add DevOps. Yeah, if you want to use a tool like xdebug (here is a great tutorial about how to install it Remote PHP Debugging with Xdebug) within Docker containers.

Some questions came to my mind when I stumbled upon this situation: How do I setup the container? How can I expose xdebug outside of my containers? How can I integrate remote debugging with my IDE workflow?

Well, I don’t have the answer for all this questions, but I will show some examples and tips various ways to setup xdebug inside your docker container and connect it with PHPStorm.

Creating Docker container

This step is pretty much the same for all alternatives and OS platforms. Here we will discuss the very basic settings to create a container.

My example will be based on a clean Erdiko project, so I already have the structure to test, umm debug, some code.  To try out the container clone from github, https://github.com/arroyolabs-blog/docker-xdebug

So let’s start creating a custom Dockerfile that will look like this:

FROM php:5.6-fpm
MAINTAINER Leo Daidone <leo@arroyolabs.com>

RUN apt-get update && apt-get install -y \
    libpq-dev \
    libmemcached-dev \
    curl

# Xdebug
# here is the installation
RUN pecl install xdebug \
    && docker-php-ext-enable xdebug
# here I'm copying the config file we will discuss in the next section
COPY ./etc/xdebug.ini /usr/local/etc/php/conf.d/

RUN usermod -u 1000 www-data

CMD ["php-fpm"]

We need to create this file instead of use the official php:5.6-fpm image, because we need to run the pecl install command within the created container. Note that I also copied “xdebug.ini” from etc folder, both, folder and file should exists in the same directory as Dockerfile, otherwise you will need to change the source path to the real location of your custom “xdebug.ini”. I choose this way because I think is easier to maintain an .ini file instead of a bunch of bash command.

Now we will need a docker-compose.yml to orchestrate the whole setup. Let’s break down the example below:

version: '2'
services:
  data:
    image: busybox
    volumes:
      - ../:/var/www/code
      - ./nginx/:/etc/nginx/conf.d

  web:
    image: nginx
    volumes_from: [data]
    links:
      - fpm
    ports:
      - "8088:80"

  fpm:
    build:
      context: .
      dockerfile: Dockerfile-PHP
    volumes_from: [data]
    environment:
      PHP_IDE_CONFIG: "serverName=docker"

I’ve defined three services, data, a busybox with the only purpose of mount and map volumes that will be shared by the other services. One web service that is an official Docker nginx image, the web server I will use in this example, finally, fpm, that will be based on our previous Dockerfile and where we will discuss variations in the next section.

Note that I’m not exposing the 9000 port (the default xdebug port) in any of Docker settings. This is the first trick for Linux, do not expose the port, just use it. That way when you try to use you IDE, you will not see an error like

Can't start listening for connections from 'xdebug': Port 9000 is busy.

Setting up xdebug

xdebug.default_enable=1
xdebug.remote_enable=1
xdebug.remote_handler=dbgp
; port 9000 is used by php-fpm
xdebug.remote_port=9000
xdebug.remote_autostart=1
; no need for remote host
xdebug.remote_connect_back=1
xdebug.idekey="PHPSTORM"

This is the basic configuration I use with the Docker code defined in the previous section. It should work fine on Linux boxes, but I found some issues trying to run it in Mac OS. I will show you some changes I tried that worked on both OS.

First issue I found when I tried to make my project works on Mac was the ports’ binding and interfaces. How can I overcome the port busy error?

After some tries I found a nice trick, I recommend, add an alias to our interface with static IP.

In Mac:

sudo ifconfig en0 alias 10.254.254.254 255.255.255.0

In Linux:

sudo ip addr add 10.254.254.254/24 brd + dev eth0 label eth0:1

Now in order to use this new static IP, we need to add this two new lines in our xdebug.ini:

xdebug.profiler_enable=0
xdebug.remote_host=10.254.254.254

I suggest set to zero all other lines except for “remote_enable” and of course “remote_port“.

Finally, our docker-compose.yml shold looks like this:

version: '2'
services:
  data:
    image: busybox
    volumes:
      - ../:/var/www/code
      - ./nginx/:/etc/nginx/conf.d

  web:
    image: nginx
    volumes_from: [data]
    links:
      - fpm
    expose:
      - "9000"
    ports:
      - "8088:80"

  fpm:
    build:
      context: .
      dockerfile: Dockerfile-PHP
    volumes_from: [data]
    environment:
      PHP_IDE_CONFIG: "serverName=docker"
      PHP_XDEBUG_ENABLED: 1 # Set 1 to enable.
      XDEBUG_CONFIG: remote_host=10.254.254.254

Note that now I’m exposing “9000”, this is because I’m using a different IP address to bind this port. Also I’ve added two new environment vars, one to enable xdebug and other to set the remote host address.

Configuring you IDE

As I mention above, I’m going to use PHPStorm to show you how to setup a Debug client. For practical purpose it will be separated in two sections, the first one based on Linux approach, and other for Mac.

But first let me start with common steps for all platforms:

you will need to go to Settings ( linux shortcut: ctrl+alt+s; Mac shortcut: Cmd+, ) and check in Language & Frameworks / PHP / Debug looks like the image

linux_xdebug

After that go to DBGp Proxy and follow the steps for each platform

preferences

Linux example

Since you are using localhost (127.0.0.1) and xdebug has PHPSTORM as ide_key those two values can be empty here:

linux_dbgp

now you have to go to Debug configuration:

server_dropdown

with the green plus sign, add a new PHP Remote Debug, change Name to docker, fill Ide Key field, and click on periods to add a new server

linux_remote

after you click on periods this new window will be opened. Again, click on green plus sign to add a new server that will be named docker, fill all field as it’s being shown, including Use path mappings check, this is a very important step, you need to let IDE know how to related docker path with local path.

linux_servers

Mac example

Assuming here you are using the tweak settings with IP alias, the steps are the same as linux, just need to change values for the one in screenshots:

preferences_2

run_debug_configurations

Note this time Host field is not 127.0.0.1 but the new alias IP.

servers

Finally, to start debugging just click on the phone icon and green bug icon

server_dropdown

add some breakpoints and happy debug!

 

Thanks for reading, I hope you have enjoyed this article and don’t miss our next entry where I will bring you a tutorial about PHPdbg, and how to use it with Docker.

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!