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).