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!

 

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.

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

Go basics – Data Types

Today we are going to walk thru basics of Go language. Starting with a list of supported data types and defining custom types.

I’ll try to show you some examples of how to deal with basic Go stuff and compare with PHP as a reference.

Data types

Integer

Integers are numbers without a decimal component. Go lang support four types for integer based on the amount of bits can address, and three  extra types based on machine architecture.

Since computers use a base-2 for representation, 8, 16, 32 and 64 tell us how many bits each of the types use. Then for the first sub set of integers Go also split them on signed and unsigned.

Signed Integers: int8, int16, int32, int64.

Unsigned Integers: uint8, uint16, uint32, uint64.

Also, a byte is an alias for uint8 and a rune for int32.

For the second sub set, the machine dependent integers we have: uint, int and uintptr.

Floating Point Numbers

Generally known as Real Numbers, represents those numbers with decimal component.

Go has two floating point types : float32 and float64.

It also has two complex number types : complex64 and complex128.

String

This data type is represented by a sequence of characters with a definite length.

Literals in Go can be created in 2 ways, with double quotes, that allows the use of special characters like \n and \t, but cannot contain new lines, or with backticks quotes, that permits the use of new lines.

You can concatenate two or more strings, like lots of languages except PHP that use a dot (.), with plus sign (+), and each individual character can be obtained using indexes.

var example string = "weird\t string\n sample!”

otherway := `weird

sample!`

In comparison with PHP, here are a couple of examples of string operations:

 PHP
$part_1 = "weird"; 
$part_2 = "string"; 
$part_3 = "sample!";
Length in PHP
$stringLength = strlen($part_1); // 5
Length in Go!
var string_length int = len(example) 
Concatenations in PHP
$full_str = "{$part_1} {$part_2}";
$full_str .= $part_3
Concatenations in Go!
var full_str string
full_str = part_1 + " " + part_2

Boolean

Booleans are a special 1 bit integer type used to indicate True or False.

The logical operators which can be used on booleans are:

and &&

or ||

not !

Arrays, Slices, Maps

Array is a set of elements of an specific type. [n]T is an array of n elements of type T, where n is the length of the set and T represents the type, i.e. to create an array of ten element length of string, it should looks like [10]string.

Examples:

  var a [10]int

  x := [5]float64 {
       34,
       63,
       56,
       84,
       23
  }

The above example in PHP looks like:

$x = array(34, 63, 56, 84, 23);

or just

$x = [34, 63, 56, 84, 23];

Slice is a segment, not fixed of an Array.

Creation of slice is via make command.

x := make([]int, 5)

It also can be initialized from array by indexes.

 

x := a[3:] //the first 3 elements of a

x := a[2:5] // specific range, elements from 2 to 5

A map is an unordered collection of key-value pairs. Also known as an associative array, a hash table or a dictionary, maps are used to look up a value by its associated key.

var x map[string]int

x["Hello"] = 1

Custom Data Types

Struct:

A structure is a user defined data type which contains named fields. In Go structs are used to represents object by the association of method to pointer of this type.

type dog struct {
	breed string
	age int
	owner string
}

type cow struct {
	age int
	farm string
}

The dot operator is used to access each field by name. The above example in PHP will look like:

<?php
class Dog {
    private $breed;
    private $age;
    private $owner;
}

class Cow {
    private $age;
    private $owner;
}
Interfaces:

In Go an interface is two things: it is a set of methods, but it is also a type.
The interface{} type, the empty interface, is the source of much confusion. The interface{} type is the interface that has no methods. Since there is no implements keyword, all types implement at least zero methods, and satisfying an interface is done automatically, all types satisfy the empty interface. That means that if you write a function that takes an interface{} value as a parameter, you can supply that function with any value.

We’ll talk about Loops, Control Structures and some design patterns in future posts. Thanks for reading

Talk about API first development

image

It was a pleasure speaking at the WAPRO event by Uncoded earlier this month.  I got to speak about API first architectures and open source mash ups with Erdiko.

API first is a technology paradigm for building apps that is emerging as an excellent way to think about your application and how it grows.  We’ve been a big fan of it for a while now.

The early days of web software (websites) were desktop first.  With the rise of smart phones and tablets it moved to a Mobile First paradigm.  We’re now seeing a shift to API First.

What does that mean?

It means that you are designing your app at the data and interaction level first.  This will inform your mobile UI, desktop UI, and public/partner APIs.

We will write more on this topic in posts to come.   Till then, download the slides from my talk in Long Beach, CA.

http://arroyolabs.com/downloads/talks/WAPRO-Talk.pdf

Tutorial: Doctrine DBAL (PHP Database Abstraction Layer)

This tutorial will show you how to connect a database using Doctrine DBAL.  The examples are for Erdiko, but could be applied to any PHP framework that uses composer.

Installation

If you have not installed Erdiko, please go to http://erdiko.org/getStarted.html#installation

To install Erdiko via Composer. simply run

composer create-project erdiko/erdiko my-project-name

After you have installed Erdiko (or your other favorite framework), it is very easy to install Doctrine.

via composer:

composer require doctrine/dbal 2.3.*

Alternatively, you can do it by hand by modifying the composer.json file in the root folder.  You just need to add this line:

{“require”: {“doctrine/dbal”: “2.3.4”}}

Then run ‘composer update’ to install Doctrine DBAL.

Basic usage

1. Getting a connection

We can get a connection through the DoctrineDBALDriverManager class.

$connectionParams = array(
    ‘dbname’ => ‘database_name’,
    ‘user’ => ‘user_name’,
    ‘password’ => ‘user_password’,
    ‘host’ => ‘localhost’,
    ‘driver’ => ‘pdo_mysql’
);
$conn = DoctrineDBALDriverManager::getConnection($connectionParams, $config);

Now, you are ready to retrieve and manipulate data.

2. Data Retrieval And Manipulation

After you have established a connection with database, it is easy to manipulation data.

In this tutorial, we create a table “Products" and create three fields for it.

The three fields are Name, Qty, and Price.

Inserting Data

$sql = “INSERT INTO Products (Name, Qty, Price) VALUES (‘Mango’, ’10’,5)”;
$stmt = $conn->query($sql);

Retrieving Data

$sql = “SELECT * FROM Products”;

$stmt = $conn->query($sql);

while ($row = $stmt->fetch()) {

    echo $row[‘Name’].’, Qty: ’.$row[‘Qty’].’, Price: ’.$row[‘Price’];

}

The output should be “Mango, Qty:10, Price:5”.

Advanced usage:

To perform fancy data manipulation or query, we will need to set up the class loader before establishing a connection.

Setting up class loader

We can open the Example controller(Example.php) under Erdiko/app/controllers/.

In the Example controller, we will need to add the following line before the class scope and it will allow the program to access the class ClassLoader.

use DoctrineCommonClassLoader;

Then, we can add the following code to a page.

$classLoader = new ClassLoader(‘Doctrine’);

$classLoader->register();

$config = new DoctrineDBALConfiguration();

Note: 

It is not a good practice to set connection parameters every time we get a connection with database.  A better way to do it would be storing all these parameters to a config file and creating a data model to read the config file.

For example, we can create a db.json config file under Erdiko/app/config/local/

In the db.json, we can set the connection parameters.

{

      “data":{       

          “dbname": ‘database_name’,

          “user": ‘user_name’,

          “password": ‘user_password’,

          “host": ‘localhost’,

          “driver": ‘pdo_mysql’

     }

}

Then, we can create a data model and it should looking something like below.

public function getDbConfig($dbConfig)

{

     $config = Erdiko::getConfig(“local/db”);

     $connectionParams = array(

         ‘dbname’ => $config[“data"][“dbname”],

         ‘user’ =>  $config[“data"][“user”],

         ‘password’ =>  $config[“data"][“password”],

         ‘host’ =>  $config[“data"][“host”],

         ‘driver’ =>  $config[“data"][“driver”],

     );

     return $connectionParams;

}

The getDbConfig function will make the program easy to maintain and also reduce the amount of code.

Now, getting a connection will be only required the following line:

$conn = DoctrineDBALDriverManager::getConnection($connectionParams, getDbConfig(‘data’));composer create-project erdiko/erdiko project-name

D3 & MeteorJS

A talk John and I gave on D3 & MeteorJS at our last MeteorJS LA Meetup. We touched on some D3 basics, and discussed some challenges we faced integrating it with MeteorJS.

code available at: https://github.com/ArroyoLabs/meetups

demo: http://d3demo.meteor.com/

Is there a business model in bookmarking?

My favorite bookmark site Springpad, recently announced it is shutting its doors.  This is a bit sad, but not too surprising.  I use it everyday, yet talking with some of my peers I realize that many don’t even know it exists and some question why it exists at all.

My previous bookmarking service was delicious.  It was at the time the best service, but when there were scares of it going away I switched to Springpad.  It didn’t die, instead it just suffered slow stagnation under yahoo ownership.

with the death of Springpad I see new boosts in users happening for Evernote and Pocket…both great services.

There have been others, Glass, this was before google glass.  it was a private bookmark and sharing app.  A great set of engineers but they couldn’t define a market niche nor define a viable business model.  They were a really smart team and had some cool tech, but not an end product that had legs.