Thursday, October 4, 2018

¿Cómo corregir el mensaje de un commit con GIT?

*Puedes saltarte al primer subtítulo

Seguramente muchos ya han escrito sobre el comando git "amend". Seré una más que lo hace :D

De hecho, hace unos minutos atrás tuve que hacer uso de este valioso comando.

Estuve trabajando esta semana en un feature que terminé agregando varios archivos y modificando otros tantos más (lo sé, no fue buena práctica hacer mis commits a fin del día) Pero a mi me gusta hacer commits cuando realmente es código estable (y además presentable) Por eso únicamente los guardaba en mi equipo local.

Luego, en un notepad, escribí todos mis mensajes de commits y los files que irían a incluir cada uno. Entonces, en una de esas, copié el mensaje equivocado. ¿Cómo corregir el mensaje de un commit con GIT?   Hoy quiero coma

GIT AMEND

Aquí es precisamente donde entra el comando git commit --amend

Ya sea si quieres corregir el nombre de tu mensajito (sobreescribiendo o editando) o si quieres agregar un archivo o file más a tu commit, puedes usar este comando.

Entonces,

git add xxxxx (si quieres agregar x files)

O te vas directo a ejecutar el comando amend,

git commit --amend

(se te abrirá el editor para que cambies tu mensaje)

o si quieres sobreescribir todo el mensaje

git commit --amend -m "Nuevo mensaje"

¿CUÁNDO FUNCIONA?

Lo previamente visto te funcionará para tu último commit que no lo hayas pusheado todavía.
Pero en el caso de que ya hubieras pusheado tu commit antes de corregirlo, después de corregirlo deberás ejecutar el siguiente comando:

git push -f

PRUEBALO

Con el comando git log puedes ver que tu mensaje de commit ha sido modificado


Happy Coding :)

Wednesday, September 5, 2018

i18n for react app

Para configurar internationalization en una aplicación REACT, ursaremos la librería react-intl

1. Ejecutamos el siguiente comando en nuestra aplicación react para instalar la librería:

npm install react-intl

2. Creamos los archivos json donde estarán los labels por cada idioma. Yo los creo en la siguiente ruta:

src\i18n\locales\en.json
src\i18n\locales\es.json


3. Modificamos el archivo index.tsx (si estas usando typescript o index.js si estás usando javascript)
En este archivo haremos algunos imports, wrapearemos nuestra app (IntlProvider), y mandaremos como parámetros el idioma y de acuerdo a eso el archivo json que deberá leer. Sin tantas vueltas, debería quedar así:
4. Agregamos una función util que nos servirá para el tema de standard json notation. La función es flattenMessages:

5. Utilizamos los labels traducidos:
Hacemos un impor en el componente que vayamos a utilizarlo:

<FormattedMessage id="sign.in.forgot.password" />

Como ID nos basaremos en el JSON file que hemos estructurado previamente. También tiene otros parámetros, pero para mi caso me fue suficiente utilizar *id*


Friday, June 22, 2018

Getting Started with MQTT and Mosca in Node.JS

A modo de hacer una introducción a lo que es MQTT y MOSCA, voy a construir una aplicación sencilla que consiste en apagar o encender la luz de mi oficina.

Aqui les dejo un poco de teoría para comprender mejor:

MQTT, por sus siglas significa Message Queue Telemetry Transport. Es un protocolo usado para la comunicación Machine to Machine (M2M) donde dispositivos se comunican entre sí utilizando un patrón publisher/subscriber. Los clientes se conectan a un broker o server, estos clientes subscriben diferentes topics y cada cliente a su vez es capaz de publicar messages. Y el broker es el responsable de enviar esos messages a los clientes que previamente se subscribieron.

En todo el párrafo anterior hice mención a los 4 conceptos más importantes que debes tomar en cuenta para aprender MQTT:

*Publisher/Subscriber
*Messages
*Topics
*Broker

Ah, lo olvidaba, es el protocolo favorito e ideal para soluciones de Internet of Things (IoT, Internet de las Cosas) porque permite conectar un dispositivo a Internet.

Bien, ahora pasemos al siguiente concepto, MOSCA. Desde luego, no es la mosca que conoces, ese insecto cochino que anda posandose sobre los alimentos.

Recuerdas lo que era un broker? Ok, Mosca es un NodeJS MQTT Broker. Está escrito en Javascript asi que solo necesitamos NodeJS para correrlo. Entonces, conmigo vamos a crear un broker privado usando Node.JS

Assumption:
Voy a suponer que ya tienes Node y NPM installado en tu máquina. Y sino, google it how to do it, it's easy!

So, let's start!

// Iniciando el proyecto node
$mkdir mqtt-mosca-app
$cd mqtt-mosca-app
$npm init --y
// Instalando dependencias
$npm i mqtt mosca --save
// espera que termine la instalación y abre el directorio con tu IDE, en mi caso Visual Studio Code
$code .

Creamos 3 archivos:

broker.js
controller.js
lamp.js

// Código para broker.js

var mosca = require('mosca');
var settings = {
port:1883
}

var server = new mosca.Server(settings);

server.on('ready', function(){
console.log("ready");
});

Requerimos el module mosca y seteamos el puerto, por defecto es el 1883. Luego se lo pasamos al servidor o broker. Activamos el broker con el evento "ready" seguido de un callback que nos imprimirá en consola que el broker está listo.


// Código para lamp.js
Necesitamos incluir el mqtt npm library y conectarnos con nuestro broker a través de la función connect, como argumento le pasamos la URL de nuestro broker, en este caso pasa usar nuestro broker necesitas poner tu IP.

Los dos estados que vamos a manejar serán: turn-on y turn-off de apagar y encender las luces. Por defecto, vamos a empezar con las luces apagadas... mmm me gusta eso XD

Luego, vamos a invocar el método on(), este método toma dos parámetros: el evento connect y un callback para subscribir a un topic.

Lamp se va a subscribir a dos topics, de encender y de apagar: lamp/turn-on y lamp-turn-off, también vamos a publicar que lamp está conectado y enviaremos el estado por defecto, te acuerdas? es el turn-off

const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://172.21.19.19');

// states: turn-on, turn-off
var state = 'turn-off';

client.on('connect', () => {
client.subscribe('lamp/turn-on');
client.subscribe('lamp/turn-off');

// inform controller that lamp is connected
client.publish('lamp/connected', 'true');
sendStateUpdate();
});

function sendStateUpdate() {
console.log('sending state = %s', state);
client.publish('lamp/state', state);
};


Entonces, cuando nos digan que nos encendamos, tenemos que preguntar si no estamos encendidos y si es cierto, cambiamos nuestro estado. De manera parecida, cuando nos digan que nos apaguemos. Y publicamos nuestro estado actualizado. El controlador recibirá esta publicación.

client.on('message', (topic, message) => {
console.log('received message %s = %s', topic, message);
switch (topic) {
case 'lamp/turn-on':
return handleTurnOnRequest(message);
case 'lamp/turn-off':
return handleTurnOffRequest(message);
}
})

function handleTurnOnRequest(message) {
if (state !== 'turn-on') {
console.log('turning on the lamp...');
//simulate turn on the lamp after 5 seconds
setTimeout(() => {
state = 'turn-on';
sendStateUpdate();
}, 5000);
}
}

function handleTurnOffRequest(message) {
if (state !== 'turn-off') {
console.log('turning off the lamp...');
//simulate turn off the lamp after 5 seconds
setTimeout(() => {
state = 'turn-off';
sendStateUpdate();
}, 5000);
}
}


// Código para Controller.js

Al igual que en lamp.js, necesitamos requerir el modulo mqtt y conectarnos a nuestro broker privado.

Para saber si la lámpara está encendida o apagada, nos creamos una variable asi como también para saber si el equipo está conectado.

Luego, invocando el método on(), y con el evento connect nos subscribimos en este caso a dos topics: lamp/connected y lamp/state ya que como contrlador, necesitamos saber si la lámpara está conectada y su estado.

const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://172.21.19.19');

var lampState = '';
var connected = false;

client.on('connect', () => {
client.subscribe('lamp/connected');
client.subscribe('lamp/state');
});

Ahora con el evento message, empezamos a recibir los mensajes publicados a los topics que nos subscribimos. Entonces decimos que cuando la lámpara esté conectada, cambiamos el valor de nuestra variable que creamos al inicio a true o a false dependiendo del caso. Y por otro lado, cuando nos llegue el mensaje del estado de la lámpara, cambiamos el valor de nuestra variable ya sea a turn-on o turn-off dependiendo del caso.

//You are supposed to receive some messages published to the topics
that you have subscribed to.
client.on('message', (topic, message) => {
switch (topic) {
case 'lamp/connected':
return handleLampConnected(message);
case 'lamp/state':
return handleLampState(message);
}
console.log('No handler for topic %s', topic)
});

function handleLampConnected (message) {
console.log('lamp connected status = %s', message);
//The message usually arrives as buffer, so I had to
convert it to string data type.
connected = (message.toString() === 'true');
};

function handleLampState (message) {
lampState = message;
console.log('lamp state update to: %s', message);
};

Y eso es todo, ahora vamos a simular ser una webapp o una mobile app que va a pedir que se encienda la luz de mi oficina y se apague. Para encender, nos aseguramos que las luces no estén encendidas y luego publicamos el topic lamp/turn-on, nuestra lámpara nos escuchará (porque ya está subscrita) y hará lo suyo. Para apagarla, lo mismo, nos aseguramos que no estén apagadas y publicamos el topic lamp/turn-off

Con el ejemplo, las luces se apagarán despues de 20 segundos con el setTimeout que estamos programando.

// simulating an outside input (a web app, mobile app, etc)
function turnOnLamp() {
// can only turn on the lamp if we are connected to
mqtt and lamp is not already turn on
if (connected && lampState !== 'turn-on') {
// ask the lamp to turn on
client.publish('lamp/turn-on', 'true');
}
}

function turnOffLamp() {
// can only turn off the lamp if we are connected to mqtt and lamp is
not already turn off
if (connected && lampState !== 'turn-off') {
//ask the lamp to turn off
client.publish('lamp/turn-off', 'true');
}
}

// for demo purposes only
//simulate turning on the lamp
setTimeout(() => {
console.log('***turn on the lamp***');
turnOnLamp();
}, 5000)

//simulate turning off the lamp
setTimeout(() => {
console.log('***turn off the lamp***');
turnOffLamp();
}, 20000)


Para probar, corre primero broker.js, luego controller.js y en seguida lamp.js
Te debería salir así:


Friday, June 15, 2018

How to make ng serve listen other than localhost

Actually, your angular app is running in:

http://localhost:4200/

Now, you can make your angular app run in:

http://172.21.19.19:8080/

It is simply like this:

ng serve --port 8080 --host 0.0.0.0 --disableHostCheck true

That's all!

Sunday, June 10, 2018

How to convert .angular-cli.json to angular.json (Angular 6 Migration)

Error: Local workspace file ('angular.json') could not be found.

Well, after running the following commands for migrating an angular app 5 to angular 6, I realized that the angular-cli.json hadn't been converted as you can see in the screenshot bellow:

npm install -g @angular/cli
npm install @angular/cli
ng update @angular/cli
ng update @angular/core
ng update @angular/material (I didn't execute this because I am not using Angular Material)




So, executing this command, I fixed this error:

ng update @angular/cli --from=1.7.4 --migrate-only


That's it! Now, you can go ahead with *ng serve*
Happy Coding!

Wednesday, May 9, 2018

ESLint - propType is not required

EsLint rules for react



If you have some props not required and ESLint displays an error message, you can add a rule or you can set a default props.



The ESLint rule is:

 "react/require-default-props": 0,

Monday, April 23, 2018

How to upgrade Git on Windows

1. Go to https://git-scm.com/download/win and download the .exe program



2. Execute it and follow the wizard (you do not need to uninstall your previous version of git to upgraded it to the latest)
3. That's it!





Wednesday, April 18, 2018

How can I upgrade Node.js and npm on Windows?

Cómo actualizar Node.js y NPM en Windows?

The most easy way to upgrade your Node.js and NPM on Windows, is go to https://nodejs.org/es/download/current/ and download the Windows Installer, run the .msi, follow the steps but make sure the path you enter is the same as the old one. That's it!

La manera más sencilla de actualizar Node.js y NPM en tu máquina Windows, es descargando el MSI más reciente, que lo encuentras en este link https://nodejs.org/es/download/current/ Sigue el wizard, pero asegurate de ingresar la misma ruta donde se encuentra tu version actual. Probablemente sea: C:\Program Files\nodejs

Let's see...



Wednesday, April 11, 2018

How to post a file version as an artifact in Jenkins

If you are using a Jenkinsfile and want to save a txt file with the build number, you just to use the $BUILD_NUMBER environment variable:

  sh 'echo "build $BUILD_NUMBER" > version.txt'

Then, in post section - always, you can post your version.txt file:

  post {
        always {
            archiveArtifacts artifacts: 'build/ , version.txt'
        }
    }

Here in the example, I am posting two files separated by commas. 

Jenkinsfile


Output


Monday, April 9, 2018

Eslint - FatalProcessOutOfMemory


FatalProcessOutOfMemory
FATAL ERROR CALL AND RETRY LAST
allocation failed - Javascript heap out of memory

I am getting this error after run *yarn run lint* for my create-react-app project.


This is due to the gigantic bundle.

I have something like this:

"lint": "eslint --ext .jsx --ext .js ."

Fix: change that line for this one:

"lint": "./node_modules/.bin/eslint . --ext ./src/*.js --ext ./src/*.jsx"

or you can use this ones:

"lint": "eslint -- --max_old_space_size=4096 --ext .jsx --ext .js ."

"lint": "./node_modules/.bin/eslint --ext .jsx --ext .js ./src"

1024 #increase to 1gb
2048 #increase to 2gb
3072 #increase to 3gb
4096 #increase to 4gb
5120 #increase to 5gb
6144 #increase to 6gb
7168 #increase to 7gb
8192 #increase to 8gb

That worked for me. Just make sure to enter your folder name, the mine is *src*

Friday, April 6, 2018

How to get started with Jenkins and GitLab on Windows

How to get started with Jenkins and GitLab on Windows

If you are really new in this, like me before, I think this guide could help you.
I assume if you are looking for Jenkins, you already know what is Continuous Integration, Continuous Delivery and Continuous Deployment.

But if you don't know yet, don't worry. Here are the definitions:

Continuous Integration. The practice of merging the development work with the main branch constantly so that the code has been tested as often as possible to catch issues early.

The ideal task size is not bigger than a day's work. This way a developer will naturally have at least one integration per day.

Continuous Delivery. Continuous delivery of code to an environment once the code is ready to ship. This could be staging or production. The idea is the product is delivered to a user base, which can be QA's or customers for review and inspection.

Unit test during the Continuous Integration phase can not catch all the bugs and business logic, particularly design issues that is why we need QA, or staging environment for testing.

Continuous Deployment: The deployment or release of code as soon as it's ready. Continuous Deployment requires Continuous Integration and Continuous Delivery otherwise the code quality won't be guarantee in a release.



So, let's move on to the next point.
What is Jenkins? What relationship does Jenkins with the concepts explained lines above?

Jenkins is a Continuous Integration server. Can be used as a simple CI server or turned into the continuous delivery hub for any project. Jenkins helps to automate the non-human part of the software development process, with continuous integration and facilitating technical aspects of continuous delivery.

Enough with the theory. Let's move on to practice.

1. Install Jenkins on your machine. (as a service)
Use the official link: https://jenkins.io/download/
Choose LTS, and Download for Windows.

2. Install the default plugins (includes Git Plugin). Also, install the GitLab Plugin

3. Create a SSH Key pair in GitLab. If you already have one, skip this step. If not yet, use the Generate a new ssh key pair guide from GitLab (User Settings > SSH Keys) This put the keys in C:\Users\MY_USER\.ssh\ (id_rsa for the private key and id_rsa.pub for the public key). You must add the public key as a deploy key to your GitLab project and then add the private key as a Jenkins Credential. This is the next step.

4. Create a credential in Jenkins.
Credentials > System > Add Credentials

Kind: SSH Username with private key
Scope: Global (Jenkins, nodes, items, all child items, etc)
Username: (whatever you want to. Suggest: git)
Private Key: From a file on Jenkins master
File: c:\User\YOUR-USER\ssh\id_rsa
Description: (It is optional)

With this, we are allowing Jenkins to connect to the git host over ssh.

5. Now, we need to setup API Access for Jenkins to get metadata from GitLab.

In GitLab, User Settings > Access Tokens > Add a personal access token.
Copy and save the token because you won't be accessible again.

6. Go Jenkins.
Credentials > System > Add Credentials

Kind: GitLab API token
Scope: Global (Jenkins, ndoes, items, all child items, etc)
API token: (paste here the token)
ID: whatever you want to.
Description: It is optional.

Once the API Access has been setup, we can configure the connection between Jenkins and GitLab. This happens in the Manage Jenkins -> Configure System menu.

In Gitlab section:
Connection name: enter a name.
Gitlab host URL: enter your host.
Credentials: choose the one you just have created
Test Connection, if everything is good, it will show you a Success message.

Now that our connection between Jenkins and GitLab is setup, we need to create a job. You can choose between freestyle jobs or pipeline.

In this guide, we will use a Multibranch Pipeline. (in my case, it works for me because I use develope, master and stable as branches)

In Jenkins, go
New Item > Enter an item name, then select Multibranch Pipeline. Click OK.

Branch Sources section.
Git
Project Repository: copy and paste the URL from GitLab (SSH)
Credentials: Choose the first one we have created.
Click Save.

It is importart your project has the Jenkinsfile in the root. Configure the Jenkinsfile is another topic. But, just for testing, you can have this:



(make sure to change the yarn comand if your project is not using yarn, it could be npm)

The last step is testing.

Go Jenkins, click the job we have created, then click the branch, click Build with Parameters, click Build and wait for building... you can have two output: failure or success.

That's it!


Wednesday, April 4, 2018

How to create a jenkins user

Just browse: Manage Jenkins > Manage Users > Create User

But if you cannot see this path, you must enable:

Manage Jenkins > Configure Global Security > Enable security and Jenkin's own user database should be checked.

That's it!


Tuesday, February 27, 2018

Abrir aplicaciones de Microsoft Office desde CMD - comandos

1. Presiona las teclas windows + r
2. Digita en el cuadro de texto la siguiente palabra:

-Para abrir WORD: winword
-Para abrirl EXCEL: excel
-Para abrir Power Point: powerpnt
-Para abrir Outlook: outlook

Otros atajos

-Para abrir Microsoft Paint: pbrush
-Para abrir el bloc de notas: notepad
-Para abrir el escritorio remoto: mstsc
-Para abrir el mapa de caracteres: charmap

Y bien, todos estos personalmente siempre los usos, me hacen la vida más sencilla... pequeños atajos.

Wednesday, February 7, 2018

Solution for [eslint] Expected linebreaks to be 'LF' but found 'CRLF' issue

Hi, are you using ESLint plugin for your IDE on Windows? And do you have this problem?


Solution:

1. Find the .eslintrc file

2. Add this code snippet


3. And that's it!

Friday, January 19, 2018

Como enviar email desde SQL Jobs - sp_send_dbmail - Parte 2

Hola, retomando la primera parte de esta entrada http://lizzymendivil.blogspot.com/2018/01/como-enviar-email-desde-sql-jobs.html les dejo cómo utilizar el sp propio de SQL SERVER llamado msdb.dbo.sp_send_dbmail



Mi stored procedure es el siguiente, está llamando a una función, dicha función me devuelve todos los datos que yo quiero que se envíe por correo. Luego ejecuta el SP propio de Sql Server el cual a su vez pide ciertos parámetros:

@profile_name es el profile que habiamos creado en la anterior entrada, si está NULL, tomará el profile por defecto.
@recipients a los correos destinatarios, si tienes más de uno, deberán ir separados por punto y coma.
@subject es el asunto del correo
@body es el cuerpo del correo


Asi mismo, se puede enviar archivo adjunto o también se le puede dar formato HTML al body.


Como enviar email desde SQL Jobs - sp_send_dbmail - Parte 1

Hola!

En esta ocasión les compartiré cómo enviar un email desde SQL Jobs en SQL Server utilizando el stored procedure "sp_send_dbmail"

Primero que nada, debemos configurar la "Database Mail", para ello utilizaremos el Wizard (hay otra forma de hacerlo a través de comandos)

CONFIGURAR DATABASE MAIL UTILIZANDO EL WIZARD

Conéctate a Microsoft SQL Server Management Studio, expande Management,click derecho sobre Database Mail y click en Configure Database Mail


Luego selecciona "Configure Database Mail" y veras la siguiente ventana de bienvenida, luego haz click en "Next".



Aparecera la siguiente ventana, selecciona "Set up Database Mail by performing..." y haz en click "Next".



Si el Database Mail no ha sido habilitado todavia, aparecerá la siguiente ventana. Haz click en "Yes" para habilitarlo. Si ya está habilitado, no se mostrará la ventana.



Ahora, ingresa un nombre de perfil y descripción (la descripción es opcional) y haz click en "Add..."


En la siguiente ventana que aparecerá, llena todos los datos solicitados:

E-mail address
Display name (optional)
Replay e-mail (optional)
Server name
Port number
This server requires a secure connection (SSL): YES
Cuando hayas terminado, haz click en "OK".



Luego, se te mostrará una ventana con los datalles de la cuenta SMPT. Haz click en "Next" para continuar.



En la siguiente ventana, deberás hacer check como Public al Profile que acabas de crear ponerle Yes como Default Profile. Haz click en "Next".



La siguiente ventana contiene algunos paráemetros adicionales que pueden ser seteados para controlar cómo se enviará el mail. Puedes dejarlos con los valores por defectos o cambiarlos. Click en "Next".



A continuación, se te mostrará una ventana con las opciones que haz seleccionado anteriormente. Si todo está correcto, haz click en "Finish" o "Back" para realizar algun cambio.




Cuando hayas hecho click en "Finish", la siguiente ventana que verás, te mostrará el estado de la instalación. Cuando haya concluido, haz click en "Close".



HABILITAR DATABASE MAIL EN EL SQL SERVER AGENT

Hasta este punto, tu SQL Server puede enviar correo pero tu SQL Server Agent aún no. Hagamos lo siguiente:

Click derecho en SQL Server Agent y selecciona "Properties":



Ahora, click en el tab "Alert System". Aqui es donde le dirás al Sql Server Agent qué profile de database mail usar.



Debes reiniciar el SQL Server Agent para hacer que tome efecto.



CÓMO CREAR UN SQL SERVER AGENT JOB

Expande SQL Server Agent. Click derecho en "Jobs", luego click en "New Job".



En la página "General", ingresa un nombre, descripción es opcional, y click en Enable en el caso de que quieras que no se ejecute el job antes de programarlo.



Luego, ve a la página "Steps" y click en "New".



En esta ventana, ingresa el nombre del step, elige como Type: Transact-SQL scrip, elige el Database y en Command typea el comando que ejecutará tu job, para este caso será un SP el cual se encargará de enviar el correo.



Ahora ve a la página "Schedule", y haz click en "New".



En esta venanta, ingresa un nombre elige le Schedule type, configura la Frequency and el Daily frequency. Y click en “OK”.



Finalmente click en "OK" y eso es todo!




Eso es todo en cuanto a configuraciones, ahora necesitamos crear el Stored Procedure que enviará el correo y el cual será llamado a traves del job que acabamos de crear. Será la segunda parte de esta entrada.

Monday, January 15, 2018

Ellos saben mas de lo que pensamos

Hola!

Les dejo una nota cómica, exagerada pero nada fuera de lo imaginario o irreal.