I am still here!

Unfortunately I had no time to write something for a while, the goal of this post is to summarize what did and what I am doing!

Doctor Decks

DoctorDecks.com: Is a program to find good combinations of cards for the game Clash Royale. The product is available in the web but also as a phone app: Windows Universal, iOS and Android.

The web has thousands of visits everyday and the app 1M downloads!

eClasher

eClasher.com is a web with news related to the eSport, a huge success in Spain and Latin America.

Master in Business Intelligence and Big Data

I am studiying a two years master and I am just starting my second semester, I hope that soon I can share with you some interesting stuff about this topic that festinates me!

Advertisements

Swift 2 examples – #11 Loading images from the Photo Library and the Camera

This post is part of my collection: Swift 2 – For Beginners.

In this example we will see how to load photos in our application from the Photo Library and from the camera.

To open the photo library to pickup a photo we need a UIImagePickerController. Our controller can be the delegate. To do that we have to implement the protocols: UINavigationControllerDelegate and UIImagePickerControllerDelegate.

This code creates UIImagePickerController and use the method presentViewController to open the Photo Library:

  func selectImage(){
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self

        imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        imagePickerController.allowsEditing = true

        self.presentViewController(imagePickerController, animated: true, completion: nil)
    }

Once the user selects a photo our controller will be called back. Let’s implement a function that will load the selected image into a imageView:

   // Pick image finished, show selected image in a imageView
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // Show image
        imageView.image = image
        self.dismissViewControllerAnimated(true, completion: nil)
    }

To take a new photo using the camera we just change the value of imagePickerController.sourceType. Instead of PhotoLibrary we use Camera.

We can add a parameter to the previous function to specify the source of our image:

    func selectImage(from source: UIImagePickerControllerSourceType){
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self

        imagePickerController.sourceType = source
        imagePickerController.allowsEditing = true

        self.presentViewController(imagePickerController, animated: true, completion: nil)
    }

Complete example:

import UIKit

class ViewController: UIViewController,

    // 1 Allows navigation to camera or photo library to pick up a photo
    // used to set this controller as delegate of UIImagePickerController
    UINavigationControllerDelegate, UIImagePickerControllerDelegate
{

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBOutlet weak var imageView: UIImageView!

    @IBAction func addFromCamera(sender: AnyObject) {
        selectImage(from: UIImagePickerControllerSourceType.Camera)
    }

    @IBAction func addFromLibrary(sender: AnyObject) {
        selectImage(from: UIImagePickerControllerSourceType.PhotoLibrary)
    }

    // 2 Show image picker or camera app
    func selectImage(from source: UIImagePickerControllerSourceType){
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self

        imagePickerController.sourceType = source
        imagePickerController.allowsEditing = true

        self.presentViewController(imagePickerController, animated: true, completion: nil)
    }

    // 3 Pick image finished, show selected image
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // Show image
        imageView.image = image
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}

TypeScript – Introduction

It is time to start learning the language of the future: TypeScript

There are a lot of online resources to learn the language, here I just share a small piece of code with the basics of the language:

//---------------
// 1 Basic types
//---------------
var myBooleanVar: boolean = false;
var myNumberVar: number = 29;
var myStringVar: string = "Juan Carlos";

// 1.1 Arrays
var myArrayVar: number[] = [1, 2, 3];
var myArrayVar: Array<number> = [1, 2, 3];

// 1.2 Enumerations
enum Direction { Up, Down, Left, Right };
var myDirectionVar: Direction = Direction.Up;

// 1.3 Any
var myAnyTypeVar: any = "I am a text";
myAnyTypeVar = false; // before it was string, now a boolean

// 1.4 Void
function log(msg: string): void {
	console.log(msg);
	// this functions returns nothing
}

//---------------
// 2 Interfaces
//---------------
interface IPerson {
	name: string;
	age?: number; // optional parameter
}

function sayHello(person: IPerson) {
	console.log(person.name);
	if (person.age) {
		console.log("Your age is " + person.age)
	}
}

// myVar has no type but has all the fields that a 
// Person should have. Therefore is a Person (duck typing)
var myVar = { name: "Juan Carlos" };
sayHello(myVar);

// 2.1 Interfaces extends
interface IStudent extends IPerson {
	studentId: number;
}

// 2.2 Interfaces indexes
interface Friends {
	[index: number]: IPerson;
	length: number;
}

// 2.3 Interfaces with functions/methods
interface PeopleService {
	getPersonId(person: IPerson): number;
	// a function that has a Person has parameter and return a boolean
	(newFriend: IPerson): boolean;
}

//---------------
// 3 Classes
//---------------

// 3.1 Interfaces implementation
interface IVehicle {
	move(direction: Direction);
	registrationNumber: number;
}

class Vehicle implements IVehicle {
	registrationNumber: number;

    constructor(id: number) {
		this.registrationNumber = id;
	}

	move(direction: Direction) {
		console.log("Moving" + direction);
	}
}

// 3.2 Classes Extends
class Car extends Vehicle {
	// by default all public
	private numberOfWheels: number = 4;
	speed: number = 120;
	
	// method override
	move(direction: Direction) {
		console.log("Speed = " + this.speed);
		// call base
		super.move(direction);
	}
}

var myCar: IVehicle = new Car(1234);
myCar.move(Direction.Up);

// 3.3 Classes, define class fields in constructor 
// add public or private to the parameter
class Motorbike implements IVehicle {
	private numberOfWheels: number = 2;
	
	// the constructor defines a public field 'registrationNumber'
    constructor(
		public registrationNumber: number,
		// define a private field with the value passed as parameter
		// if no value specified, the field as the value 90
		private speed: number = 90) {
	}

	move(direction: Direction) {
		console.log("Moving the motorbike" + direction);
	}
}

// 3.4 Accesors and static fields
class Plane implements IVehicle {
	// Static field
	static minSpeed: number = 100;
	static speedCorrectionFactor: number = 0.8;
	
	constructor(
		public registrationNumber: number,
		private _speed: number = 300) {
	}

	// speed getter
	get getSpeed(): number {
		// for some reason the public speed is 80%
		// of the realone
        return this._speed * Plane.speedCorrectionFactor;
    }

	// speed setter
    set setSpeed(newSpeed: number) {
		if (newSpeed > Plane.minSpeed) {
			this._speed = newSpeed;
		}
	}

	move(direction: Direction) {
		console.log("Flying! " + direction);
	}
}

Resources:
http://www.typescriptlang.org/Handbook

What’s new in C# 6.0

I just installed Visual Studio 2015 Preview on a Windows 10 tech. preview, the first thing I wanted to try out was C# 6.0.

Source code

VisualStudio2015 in Windows10

VisualStudio 2015 in Windows10

The are a lot of videos and posts on internet about the new features of C# 6.0. The goal of this post is to test them by myself and share my impressions. I will use this post in the future as a personal reference for C# 6.0 new features.

C# 6.0 new feautures

This is the list of new features I have collected so far:

  • Getter only auto properties
  • Auto-Initialization of properties
  • Calculated properties with body expressions
  • Null conditional operators ?.
  • Operator nameof()
  • Strings projections
  • Exceptions filters
  • Await in catch and finally
  • Index initializers

I wrote a small sample class that I will use as an example to test the new features.

This is the C# 5 sample class:

using System;

namespace ConsoleApplication1
{
    public class Person
    {
        public Person(string name, int age)
        {
            if (name == null)
            {
                throw new NullReferenceException("name");
            }

            Name = name;
            Age = age;
            Id = GetNewId();
        }

        public string Name { get; set; }
        public int Id { get; private set; }
        public int Age { get; set; }

        public event EventHandler Call;

        protected virtual void OnCall()
        {
            EventHandler handler = Call;
            if (handler != null) handler(this, EventArgs.Empty);
        }

        public int GetYearOfBirth()
        {
            return DateTime.Now.Year - Age;
        }

        public JObject ToJSon()
        {
            var personAsJson = new JObject();

            personAsJson["id"] = this.Id;
            personAsJson["name"] = this.Name;
            personAsJson["age"] = this.Age;

            return personAsJson;
        }

        #region Get new person id

        private static int lastId;

        private static int GetNewId()
        {
            lastId++;
            Logger.WriteInfo(string.Format("New Id = {0}", lastId));
            return lastId;
        }

        #endregion
    }
}

Applying C# 6.0 new features to a C# 5.0 class:

Now lets go throw the list of new features and apply them to our sample class:

Getter only auto properties

We can remove “private set” from read-only properties, properties with only a “setter” can be initialized only from the constructor or with auto-initialization.

public int Id { get; }     

Auto-Initialization of properties

Using auto initialization we can auto initialize the Id property calling a method. It is also possible to set a default value to editable properties:

public int Id { get; } = GetNewId();    
public int Age { get; set; } = 18;    

Calculated properties with body expressions

It is common to have a lot of single line calculated properties or methods on our code. In lambda expressions it was already possible to write only the value to return. Now this is also possible in normal methods:

Our “GetYearOfBirth” method can be re-write like this:

     
public int GetYearOfBirth => DateTime.Now.Year - Age;

Note that if the method has not parameters we can also avoid the parentheses.

Null conditional operators ?.

Continue reading

WPF – State machine and ICommand

The goal of this post is to test the usage of MVVM Delegate commands together with a state machine.  You can read more about the state machine pattern here, and about commands here.

WPF allows to bind a command to some controls, the ICommand interface has two methods:  one that executes an action and one that returns  a Boolean indicating if the command can be executed or not.

E.g. Command bound to a button: When the button is clicked the action defined within the command is executed, when the command cannot be executed the button is disabled.

This is the ICommand interface.

public interface ICommand {
	event EventHandler CanExecuteChanged;
	bool CanExecute(object parameter);
	void Execute(object parameter);
}

I will use the Microsoft PRISM 5 Delegate ICommand implementation and the stateless state machine.

ICommand + State Machine Trigger

On a state machine there are states and triggers, within one state some triggers are forbidden and other are allowed, when a trigger is fired the state machine could change its state.

Our commands shall be associated to a trigger, the behaviour should be:

  • CanExecute: Shall return true only if the associated trigger can be fired on the current state.
  • Execute: Shall fire the associated trigger, the machine could change its state.

The coffee machine

The application that we will write will be a very simple coffee machine with only one type of coffee:

States

  1. Idle: Machine waiting to be used.
  2. With money: The user entered some money but is not enough to get a coffee.
  3. Can get coffee: The user entered enough money to get a coffee.
  4. Preparing coffee: The coffee is being prepared.
  5. Coffee ready: The user can take the coffee.
  6. Refunding money: The machine is returning the money to the user.

Triggers

  1. Insert money: Fired when the user insert money.
  2. Refund money: Fired when the user press the refund money button and after the user takes the coffee.
  3. Enough money: Automatically fired when the user inserted enough money.
  4. Prepare coffee: Fired when the user select a coffee, (our machine is that simple that has only one…)
  5. Coffee prepared: Automatically fired when the coffee is prepared.
  6. Take coffee: Fired when the user takes the coffee.
  7. Money refunded: Automatically fired when the machine refunded the money.

The diagram

image

Implementation

States

    public enum CoffeeMachineState
    {
        Idle,
        WithMoney,
        CanSelectCoffee,
        PreparingCoffee,
        CoffeeReady,
        RefundMoney
    }

Triggers

    public enum CoffeeMachineTrigger
    {
        InsertMoney,
        RefundMoney,
        PrepareCoffee,
        TakeCoffe,

        // Automatic triggers
        EnoughMoney,
        CoffeePrepared,
        MoneyRefunded
    }

Configuration

        /// &lt;summary&gt;
        /// Configures the machine.
        /// &lt;/summary&gt;
        private void ConfigureMachine()
        {
            // Idle
            this.Configure(CoffeeMachineState.Idle)
                .Permit(CoffeeMachineTrigger.InsertMoney, CoffeeMachineState.WithMoney);

            // Refund money
            this.Configure(CoffeeMachineState.RefundMoney)
                .OnEntry(RefundMoney)
                .Permit(CoffeeMachineTrigger.MoneyRefunded, CoffeeMachineState.Idle);


            // WithMoney
            this.Configure(CoffeeMachineState.WithMoney)
                .PermitReentry(CoffeeMachineTrigger.InsertMoney)
                .Permit(CoffeeMachineTrigger.RefundMoney, CoffeeMachineState.RefundMoney)
                .Permit(CoffeeMachineTrigger.EnoughMoney, CoffeeMachineState.CanSelectCoffee);

            // CanSelectCoffee
            this.Configure(CoffeeMachineState.CanSelectCoffee)
                .PermitReentry(CoffeeMachineTrigger.InsertMoney)
                .Permit(CoffeeMachineTrigger.RefundMoney, CoffeeMachineState.RefundMoney)
                .Permit(CoffeeMachineTrigger.PrepareCoffee, CoffeeMachineState.PreparingCoffee);

            // PreparingCoffee
            this.Configure(CoffeeMachineState.PreparingCoffee)
                .OnEntry(PrepareCoffee)
                .Permit(CoffeeMachineTrigger.CoffeePrepared, CoffeeMachineState.CoffeeReady);

            // CoffeeReady
            this.Configure(CoffeeMachineState.CoffeeReady)
                .Permit(CoffeeMachineTrigger.TakeCoffe, CoffeeMachineState.RefundMoney);

            this.OnTransitioned(NotifyStateChanged);
        }

StateMachine command factory

Continue reading

AngularJS – Controller code structure

The goal of this post is to define a structure to write AngularJS controllers.

I identify three different parts inside the controller:

  • Public methods and variables: On top of the code and just the definition of the methods, the implementation will be inside the private area.
  • Code that run when the controller is created. Right after the public methods.
  • Private methods and variables. Prefixed with ‘_’.

This is the structure schema of my controllers:

app.controller("myController", myController);
 
function myController() {
    'use strict';
    var self = this;
 
    //// ---------------- PUBLIC ----------------
    //// PUBLIC fields
                ...
    //// PUBLIC Methods
		...
    //// ---------------- CODE TO RUN -----------
		...
    //// ---------------- PRIVATE ---------------
    //// PRIVATE fields
		...
    //// PRIVATE Functions - Public Methods Implementation	
		...
    //// PRIVATE Functions
		...
};

This is one of my controllers, a lot of code but someone interested only in its use and not in its implementation can easily read the ‘public’ area only : Continue reading