<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Code Crafters Blog]]></title><description><![CDATA[Some days you win, some days you learn.]]></description><link>https://ghost-azure3fff.azurewebsites.net/</link><generator>Ghost 0.11</generator><lastBuildDate>Fri, 01 May 2026 11:43:35 GMT</lastBuildDate><atom:link href="https://ghost-azure3fff.azurewebsites.net/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[IoT - Creando un Sistema IoT de Monitoreo y Control Ambiental (Parte 2)]]></title><description><![CDATA[<p>En esta entrega, vamos a detallar el proyecto que construiremos a lo largo de esta serie. Se trata de un sistema IoT de monitoreo y control ambiental compuesto por varios dispositivos interconectados. El sistema consta de tres tipos de unidades: <strong>Sensor Unit</strong>, <strong>Central Unit</strong> y <strong>Actuator Unit</strong>. Vamos a explorar</p>]]></description><link>https://ghost-azure3fff.azurewebsites.net/iot-creando-un-sistema-iot-de-monitoreo-y-control-ambiental-parte-2/</link><guid isPermaLink="false">744394a3-7c7a-4b58-a290-63ef7259254c</guid><dc:creator><![CDATA[Daniel Ferrer]]></dc:creator><pubDate>Fri, 24 May 2024 16:05:21 GMT</pubDate><media:content url="http://blog.codecrafterslab.com/content/images/2024/05/Diagrama-IoT.png" medium="image"/><content:encoded><![CDATA[<img src="http://blog.codecrafterslab.com/content/images/2024/05/Diagrama-IoT.png" alt="IoT - Creando un Sistema IoT de Monitoreo y Control Ambiental (Parte 2)"><p>En esta entrega, vamos a detallar el proyecto que construiremos a lo largo de esta serie. Se trata de un sistema IoT de monitoreo y control ambiental compuesto por varios dispositivos interconectados. El sistema consta de tres tipos de unidades: <strong>Sensor Unit</strong>, <strong>Central Unit</strong> y <strong>Actuator Unit</strong>. Vamos a explorar cada uno de estos dispositivos y cómo interactúan entre sí y con la nube.</p>

<h2 id="descripcindelproyecto">Descripción del Proyecto</h2>

<h4 id="sensorunit">Sensor Unit</h4>

<p>Las <strong>Sensor Units</strong> son los dispositivos encargados de recopilar datos ambientales. Cada <strong>Sensor Unit</strong> incluye los siguientes componentes:</p>

<ul>
<li>Sensor de humedad</li>
<li>Sensor de temperatura</li>
<li>Sensor de calidad del aire</li>
<li>MCU (Microcontrolador) que lee los datos de los sensores y los envía a la <strong>Central Unit</strong>.</li>
</ul>

<p>La comunicación entre las <strong>Sensor Units</strong> y la <strong>Central Unit</strong> se realizará utilizando la tecnología <strong>LoRaWan</strong>, que permite la transmisión de datos a larga distancia con bajo consumo de energía.</p>

<h4 id="centralunit">Central Unit</h4>

<p>La <strong>Central Unit</strong> es el corazón del sistema y actúa como un <strong>LoRaWan Gateway</strong>. Sus funciones principales son:</p>

<ul>
<li><strong>Recepción de datos:</strong> Recibe las lecturas de las <strong>Sensor Units</strong> a través de <strong>LoRaWan</strong>.</li>
<li><strong>Procesamiento de datos:</strong> Analiza los datos recibidos para determinar el estado ambiental.</li>
<li><strong>Comunicación con la nube:</strong> Utiliza <strong>WiFi</strong> y el protocolo <strong>MQTT</strong> para enviar los datos procesados a un servidor en la nube.</li>
<li><strong>Configuración remota:</strong> Recibe configuraciones y parámetros desde una aplicación web alojada en la nube.</li>
<li><strong>Visualización local:</strong> Incluye una pantalla para mostrar los datos actuales de las mediciones en cada estancia y el estado de los relés.</li>
</ul>

<h4 id="actuatorunit">Actuator Unit</h4>

<p>La <strong>Actuator Unit</strong> es responsable de realizar acciones basadas en las decisiones tomadas por la <strong>Central Unit</strong>. Sus componentes y funciones incluyen:</p>

<ul>
<li><strong>MCU</strong> que recibe mensajes desde la <strong>Central Unit</strong> vía <strong>LoRaWan</strong> .</li>
<li><strong>Relé</strong> que controla dispositivos como ventiladores o humidificadores.</li>
<li><strong>Ejecutar acciones:</strong> Activa o desactiva el relé según las órdenes recibidas de la <strong>Central Unit</strong>.</li>
<li><strong>Comunicación</strong> entre los Dispositivos <strong>LoRaWan</strong></li>
<li><strong>Sensor Unit</strong> a <strong>Central Unit:</strong> Utiliza <strong>LoRaWan</strong> para transmitir datos de humedad, temperatura y calidad del aire.</li>
<li><strong>Central Unit</strong> a <strong>Actuator Unit:</strong> Utiliza <strong>LoRaWan</strong> para enviar comandos de control a la <strong>Actuator Unit</strong>.
WiFi y MQTT  </li>
<li><strong>Central Unit</strong> a la nube: Usa <strong>WiFi</strong> para conectarse a internet y <strong>MQTT</strong> para enviar datos ambientales al servidor en la nube.</li>
<li><strong>Nube a Central Unit:</strong> La configuración y los parámetros se envían desde la aplicación web a la <strong>Central Unit</strong> usando <strong>MQTT</strong>.
Infraestructura en la Nube  </li>
<li>El sistema en la nube constará de los siguientes componentes:
<ul><li><strong>Backend (Web API):</strong> Gestionará las peticiones y la lógica de negocio, exponiendo los datos y configuraciones necesarios.</li>
<li><strong>Frontend (Angular):</strong> Proporcionará una interfaz web interactiva donde los usuarios podrán ver las mediciones en tiempo real y ajustar los parámetros del sistema.</li>
<li><strong>Job de Azure:</strong> Se encargará de gestionar la comunicación con el broker <strong>MQTT</strong>, asegurando que los mensajes se envían y reciben correctamente.</li>
<li><strong>Application Insights:</strong> Se utilizará para almacenar <strong>logs</strong> y realizar análisis posteriores de posibles errores, facilitando la monitorización y el mantenimiento del sistema.
Flujo de Trabajo  </li>
<li><strong>Lectura de Datos:</strong> Las <strong>Sensor Units</strong> toman lecturas de humedad, temperatura y calidad del aire.</li>
<li><strong>Transmisión de Datos:</strong> Las lecturas se envían a la <strong>Central Unit</strong> vía <strong>LoRaWan</strong>.</li>
<li><strong>Procesamiento de Datos:</strong> La <strong>Central Unit</strong> procesa los datos para determinar las condiciones ambientales y muestra los resultados en su pantalla.</li>
<li><strong>Subida a la Nube:</strong> Los datos procesados se envían a la nube usando <strong>WiFi</strong> y <strong>MQTT</strong>.</li>
<li><strong>Configuración Remota:</strong> Los usuarios pueden ajustar parámetros y configuraciones desde una aplicación web.</li>
<li><strong>Acciones en Actuator Unit:</strong> La <strong>Central Unit</strong> envía comandos a la <strong>Actuator Unit</strong> para activar o desactivar dispositivos como ventiladores o humidificadores.</li></ul></li>
</ul>

<h3 id="diagramadelsistema">Diagrama del Sistema</h3>

<div align="center">  
<img width="100%" src="https://i.ibb.co/KXnLd6p/Diagrama-Io-T.png" alt="IoT - Creando un Sistema IoT de Monitoreo y Control Ambiental (Parte 2)">  
</div>

<p><tr>  </tr></p>

<h3 id="conclusin">Conclusión</h3>

<p>En esta serie de publicaciones, guiaremos paso a paso cómo construir cada uno de estos dispositivos, configurar las comunicaciones y desarrollar la interfaz web para gestionar el sistema. En la siguiente entrega, entraremos en la selección de los componentes necesarios para construir las <strong>Sensor Units</strong>, la <strong>Central Unit</strong> y las <strong>Actuator Units</strong>. ¡Vamos a sumergirnos en el emocionante mundo de la IoT!</p>

<p><a href="https://ghost-azure3fff.azurewebsites.net/iot-una-breve-historia-parte-1/">Volver a la primera parte</a></p>]]></content:encoded></item><item><title><![CDATA[IoT - Una breve historia (Parte 1)]]></title><description><![CDATA[<p>La tecnología de Internet de las Cosas (IoT) ha estado en desarrollo durante décadas, pero es en la era actual, impulsada por la rápida expansión de la conectividad 5G, que ha comenzado a florecer y captar la atención generalizada. Sin embargo, su origen se remonta mucho más atrás en el</p>]]></description><link>https://ghost-azure3fff.azurewebsites.net/iot-una-breve-historia-parte-1/</link><guid isPermaLink="false">f6aec6ab-3c97-4f2b-b591-b934ed4efacd</guid><dc:creator><![CDATA[Daniel Ferrer]]></dc:creator><pubDate>Tue, 14 May 2024 12:23:24 GMT</pubDate><content:encoded><![CDATA[<p>La tecnología de Internet de las Cosas (IoT) ha estado en desarrollo durante décadas, pero es en la era actual, impulsada por la rápida expansión de la conectividad 5G, que ha comenzado a florecer y captar la atención generalizada. Sin embargo, su origen se remonta mucho más atrás en el tiempo.</p>

<div align="center">  
<img src="https://pbs.twimg.com/media/E3XizOwXMBEk3hI?format=jpg&name=small">  
</div>  

<p align="center"><i>La primera tostadora conectada, precursora de la IoT moderna.</i></p>  

<p>La semilla de la IoT se plantó en los laboratorios de investigación y desarrollo a finales del siglo XX, cuando los primeros dispositivos conectados comenzaron a emerger en entornos controlados como laboratorios y campus universitarios. Estos dispositivos, a menudo rudimentarios en comparación con los de hoy, sentaron las bases para lo que se convertiría en una red interconectada de objetos físicos capaces de recopilar y compartir datos.</p>

<p>A medida que la tecnología avanzaba, la IoT encontró aplicaciones en una variedad de campos, desde la automatización industrial hasta la gestión de la cadena de suministro y la salud digital. Sin embargo, su adopción masiva fue limitada por la disponibilidad y la velocidad de las conexiones de red.</p>

<p>Con la llegada de la tecnología 5G, la IoT está experimentando un renacimiento. Las conexiones ultrarrápidas y de baja latencia proporcionadas por el 5G están desbloqueando todo el potencial de la IoT, permitiendo la proliferación de dispositivos inteligentes en hogares, ciudades, industrias y más allá.</p>

<p>Al sumergirnos en esta emocionante era de la IoT habilitada por 5G, es esencial comprender cómo estos avances tecnológicos se traducen en la creación práctica de dispositivos IoT modernos. Nos adentraremos en el mundo del hardware y los microcontroladores, componentes fundamentales de este ecosistema tecnológico.</p>

<p>Es importante destacar la diferencia entre una CPU (Unidad Central de Procesamiento) y una MCU (Microcontrolador). Las CPUs, como las que encontramos en nuestras computadoras personales, son dispositivos de propósito general diseñados para ejecutar una amplia variedad de aplicaciones. Por otro lado, las MCUs son chips integrados que combinan una CPU con memoria, E/S y otros periféricos en un solo paquete. Las MCUs son ideales para aplicaciones embebidas donde el tamaño, el consumo de energía y el costo son consideraciones importantes.</p>

<p>Al embarcarnos en este proyecto, hemos decidido descartar plataformas de desarrollo como Arduino. Aunque Arduino es popular y fácil de usar, está diseñado principalmente para proyectos de aficionados y prototipos. Para un dispositivo IoT robusto y escalable, necesitamos tecnologías más industriales como los microcontroladores STM32, ESP32 o las MCUs de Texas Instruments.  </p>

<div class="kg-table-container">  
  <table class="kg-table" border="1">
    <thead>
      <tr>
        <th class="kg-table-cell">Características</th>
        <th class="kg-table-cell">Arduino Mega</th>
        <th class="kg-table-cell">STM32F4</th>
        <th class="kg-table-cell">ESP32</th>
        <th class="kg-table-cell">Texas Instruments MSPM0G3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="kg-table-cell"><strong>Tipo de microcontrolador</strong></td>
        <td class="kg-table-cell">Microcontrolador de 8-bit o 32-bit</td>
        <td class="kg-table-cell">Microcontrolador ARM Cortex-M de 32-bit</td>
        <td class="kg-table-cell">Microcontrolador Xtensa de 32-bit</td>
        <td class="kg-table-cell">Microcontrolador de 16-bit o 32-bit</td>
      </tr>
      <tr>
        <td class="kg-table-cell"><strong>Velocidad de reloj</strong></td>
        <td class="kg-table-cell">16 MHz</td>
        <td class="kg-table-cell">Hasta 180 MHz (dependiendo del modelo específico)</td>
        <td class="kg-table-cell">Hasta 240 MHz</td>
        <td class="kg-table-cell">Varía según el modelo, hasta varios cientos de MHz</td>
      </tr>
      <tr>
        <td class="kg-table-cell"><strong>Memoria Flash</strong></td>
        <td class="kg-table-cell">256 KB</td>
        <td class="kg-table-cell">Desde 512 KB hasta varios MB</td>
        <td class="kg-table-cell">Entre 512 KB y 4 MB</td>
        <td class="kg-table-cell">Varía según el modelo, desde KB hasta varios MB</td>
      </tr>
      <tr>
        <td class="kg-table-cell"><strong>Memoria RAM</strong></td>
        <td class="kg-table-cell">8 KB</td>
        <td class="kg-table-cell">Desde 64 KB hasta 1 MB</td>
        <td class="kg-table-cell">Hasta 520 KB</td>
        <td class="kg-table-cell">Varía según el modelo, desde KB hasta varios MB</td>
      </tr>
      <tr>
        <td class="kg-table-cell"><strong>GPIO</strong></td>
        <td class="kg-table-cell">54</td>
        <td class="kg-table-cell">Depende del modelo, típicamente entre 16 y 168</td>
        <td class="kg-table-cell">Depende del modelo, típicamente entre 34 y 82</td>
        <td class="kg-table-cell">Varía según el modelo, típicamente entre 10 y 200</td>
      </tr>
      <tr>
        <td class="kg-table-cell"><strong>Conexiones SPI</strong></td>
        <td class="kg-table-cell">4 (Con pins MISO, MOSI, SCK)</td>
        <td class="kg-table-cell">Depende del modelo, generalmente múltiples interfaces SPI disponibles</td>
        <td class="kg-table-cell">4 (Con pins MISO, MOSI, SCK)</td>
        <td class="kg-table-cell">Depende del modelo, generalmente múltiples interfaces SPI disponibles</td>
      </tr>
      <tr>
        <td class="kg-table-cell"><strong>Conexiones I2C</strong></td>
        <td class="kg-table-cell">2 (Con pins SDA, SCL)</td>
        <td class="kg-table-cell">Depende del modelo, generalmente múltiples interfaces I2C disponibles</td>
        <td class="kg-table-cell">2 (Con pins SDA, SCL)</td>
        <td class="kg-table-cell">Depende del modelo, generalmente múltiples interfaces I2C disponibles</td>
      </tr>
      <tr>
        <td class="kg-table-cell"><strong>Conectividad</strong></td>
        <td class="kg-table-cell">USB, UART, I2C, SPI, Ethernet</td>
        <td class="kg-table-cell">Puerto USB, UART, I2C, SPI, Ethernet, etc.</td>
        <td class="kg-table-cell">Wi-Fi, Bluetooth, Ethernet (en algunas variantes)</td>
        <td class="kg-table-cell">Varía según el modelo, puede incluir USB, UART, I2C, SPI, Ethernet, etc.</td>
      </tr>
      <tr>
        <td class="kg-table-cell"><strong>Soporte de desarrollo</strong></td>
        <td class="kg-table-cell">Amplia comunidad de usuarios y documentación disponible</td>
        <td class="kg-table-cell">Amplio soporte de la comunidad y documentación disponible</td>
        <td class="kg-table-cell">Comunidad activa y documentación disponible</td>
        <td class="kg-table-cell">Soporte de la comunidad y documentación disponible</td>
      </tr>
      <tr>
        <td class="kg-table-cell"><strong>Lenguajes de programación</strong></td>
        <td class="kg-table-cell">Principalmente Arduino IDE con lenguaje basado en C/C++</td>
        <td class="kg-table-cell">C/C++, soporte para múltiples IDEs como STM32CubeIDE</td>
        <td class="kg-table-cell">C/C++, soporte para múltiples IDEs como Arduino IDE, PlatformIO</td>
        <td class="kg-table-cell">C/C++, algunos modelos pueden admitir otros lenguajes como TI-RTOS, Energia, etc.</td>
      </tr>
      <tr>
        <td class="kg-table-cell"><strong>Aplicaciones típicas</strong></td>
        <td class="kg-table-cell">Proyectos de hobby, prototipos simples</td>
        <td class="kg-table-cell">Aplicaciones industriales, sistemas embebidos avanzados</td>
        <td class="kg-table-cell">Proyectos IoT, sistemas embebidos avanzados</td>
        <td class="kg-table-cell">Aplicaciones industriales, sistemas embebidos, dispositivos IoT</td>
      </tr>
    </tbody>
  </table>



Los microcontroladores STM32 ofrecen un equilibrio excepcional entre potencia y eficiencia energética, con una amplia variedad de modelos que pueden adaptarse a las necesidades específicas de nuestro proyecto. Por otro lado, los ESP32 son conocidos por su conectividad Wi-Fi y Bluetooth integrada, lo que los hace ideales para aplicaciones IoT que requieren comunicación inalámbrica. Además, las MCUs de Texas Instruments son altamente confiables y se utilizan ampliamente en aplicaciones industriales y comerciales.

Al elegir estas plataformas más industriales, podemos garantizar la fiabilidad, el rendimiento y la escalabilidad de nuestro dispositivo IoT. En las próximas entregas, exploraremos en detalle cómo utilizar estas herramientas y lenguajes de programación como C/C++ para desarrollar nuestro dispositivo desde cero.

Además del hardware y los microcontroladores, otro componente fundamental en los dispositivos IoT son los sensores y actuadores. Estos dispositivos juegan un papel crucial al interactuar con el entorno físico, recopilar información, procesarla y actuar en consecuencia.

Los sensores son dispositivos que detectan cambios en el entorno físico y convierten estos cambios en señales eléctricas que pueden ser procesadas por el microcontrolador. Existen una amplia variedad de sensores diseñados para medir diferentes variables, como temperatura, humedad, luz, presión, movimiento, entre otros. Estos sensores permiten que nuestros dispositivos IoT capturen datos del mundo real y respondan de manera inteligente a su entorno.

<img src="https://dz2cdn1.dzone.com/storage/temp/16064064-types-of-sensors.png">

Por otro lado, los actuadores son dispositivos que realizan acciones físicas en respuesta a las señales del microcontrolador. Estos pueden incluir motores, válvulas, relés, entre otros. Los actuadores son esenciales para llevar a cabo acciones en el mundo físico basadas en los datos recopilados por los sensores. Por ejemplo, un actuador podría abrir una válvula para liberar agua en un sistema de riego automatizado después de que un sensor de humedad detecte que el suelo está seco.

<img src="https://dz2cdn1.dzone.com/storage/temp/16064089-types-of-actuators.png">

La interacción entre sensores y actuadores permite que nuestros dispositivos IoT no solo recopilen información del entorno, sino que también tomen decisiones y realicen acciones en tiempo real. Esta capacidad de percepción y respuesta es lo que hace que los dispositivos IoT sean tan poderosos y versátiles en una amplia gama de aplicaciones.

En las próximas entregas, exploraremos cómo integrar sensores y actuadores en nuestro proyecto de IoT y cómo programar el microcontrolador para interactuar con ellos de manera efectiva. ¡Prepárate para sumergirte en el emocionante mundo de la Internet de las Cosas, donde la tecnología se conecta con el mundo físico de formas innovadoras y transformadoras!  
<tr>

<div align="right">  
<a align="right" href="https://ghost-azure3fff.azurewebsites.net/iot-creando-un-sistema-iot-de-monitoreo-y-control-ambiental-parte-2/">Ir a la segunda parte</a>  
</div></tr></div>]]></content:encoded></item><item><title><![CDATA[[ESP] Despliegue en Azure desde Visual Studio 2017]]></title><description><![CDATA[Video con dos casos de despliegue, uno de ellos usando slot.]]></description><link>https://ghost-azure3fff.azurewebsites.net/despliegue-en-azure-desde-visual-studio-2017/</link><guid isPermaLink="false">c4cfdab7-470a-4d27-9ffb-87aa78f24864</guid><category><![CDATA[azure]]></category><dc:creator><![CDATA[Daniel Mazzini Vidal]]></dc:creator><pubDate>Tue, 07 Nov 2017 00:20:02 GMT</pubDate><media:content url="http://blog.codecrafterslab.com/content/images/2017/10/Captura-de-pantalla-2017-10-28-a-las-13.45.55.png" medium="image"/><content:encoded><![CDATA[<img src="http://blog.codecrafterslab.com/content/images/2017/10/Captura-de-pantalla-2017-10-28-a-las-13.45.55.png" alt="[ESP] Despliegue en Azure desde Visual Studio 2017"><p>El siguiente video es una muestra de las dos opciones más básicas que tienes para hacer un despliegue en Azure desde Visual Studio 2017.</p>

<p><script src="https://fast.wistia.com/embed/medias/1owz2wp642.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_1owz2wp642 videoFoam=true" style="height:100%;width:100%">&nbsp;</div></div></div></p>]]></content:encoded></item><item><title><![CDATA[Try class: Handling exception in a functional way with C# 7]]></title><description><![CDATA[<p><img src="https://ghost-azure3fff.azurewebsites.net/content/images/2017/05/4543895219_8d78eba86f_z.jpg" alt="try again">
While watching a Coursera course of functional programming, I saw a Scala class that I liked in concept and implementation. It's a utility class and is called Try. Now that C# 7 includes pattern matching I thought it was time to review it and pass it to C#.</p>

<p>The Try</p>]]></description><link>https://ghost-azure3fff.azurewebsites.net/try-class-handling-exception-in-functional-way-with-c-7/</link><guid isPermaLink="false">2e3fbd98-a5cf-4a39-ac12-d275bcb7adf4</guid><category><![CDATA[functional programing]]></category><category><![CDATA[english]]></category><dc:creator><![CDATA[Daniel Mazzini Vidal]]></dc:creator><pubDate>Tue, 05 Sep 2017 21:08:44 GMT</pubDate><media:content url="http://blog.codecrafterslab.com/content/images/2017/05/4543895219_8d78eba86f_z-1.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://blog.codecrafterslab.com/content/images/2017/05/4543895219_8d78eba86f_z-1.jpg" alt="Try class: Handling exception in a functional way with C# 7"><p><img src="https://ghost-azure3fff.azurewebsites.net/content/images/2017/05/4543895219_8d78eba86f_z.jpg" alt="Try class: Handling exception in a functional way with C# 7">
While watching a Coursera course of functional programming, I saw a Scala class that I liked in concept and implementation. It's a utility class and is called Try. Now that C# 7 includes pattern matching I thought it was time to review it and pass it to C#.</p>

<p>The Try class <mark>represents the result of a function with the expected value or an exception</mark>. The purpose is that you can leave your clean code exception management and errors.</p>

<p>But, previous to talk in details about Try, let me to do an introduction to Monad and other implementations.</p>

<h2 id="monadmaybeandtry">Monad, Maybe and Try</h2>

<p>First, all this term have relation with functional programming, and the way to resolve problems with this paradigm. To an introduction to the topic, <a href="http://blog.codecrafterslab.com/practical-introduction-to-functional-programming/" target="_blank">you can follow this link.</a></p>

<p><em>Monad</em> When using sequenced operations, with monad you can structure the code. Another term most descriptive to this is computation builder. The monad allows us to create pipelines that process data in steps, with additional process rules provided by the monad. Also, can be seen as a functional design pattern for building generic types.</p>

<p><code>Maybe&lt;T&gt;</code> is a container of type T that may be present or not. It's a monad implementation. It has only one implementation.</p>

<p><code>Try&lt;T&gt;</code> represents an operation. If it's successful return T, else some subclass of 'Exception'. As Maybe, it's a monad implementation. You create two different subType of Try<t>, <code>Success&lt;T&gt;</code> when the operation is Ok, and <code>Failure&lt;T&gt;</code> when found errors or handling exceptions. Internally, the Failure<t> contains the exception.</t></t></p>

<h3 id="problem">Problem</h3>

<p>First, to understand the need, I will present the original scenario with an elementary example. We have a function that finds data in the database and then passes that data to another process as arguments. Simple, but a pipeline. For simplicity, it'll be synchronous.</p>

<pre><code class="language-cs">var dbResult = repository.GetData("parameter");  
var result = anotherProcess(dbResult);  
</code></pre>

<p>The code above is not bad, but it's too much optimistic. The search operation can at least give a timeout. When you start programming with try-catch block, the code is no longer expressive, as the next code.</p>

<pre><code class="language-cs">customer dbResult;  
try  
{
   dbResult = repository.GetData("parameter");
}
catch (TimeOutException toEx)  
{
   //cut to simplify
}
catch (Exception toEx)  
{
   //cut to simplify
}
var result = anotherProcess(dbResult);  
</code></pre>

<h3 id="solution">Solution</h3>

<p>The Try class helps us to <strong>encapsulate the result and the exception</strong>, and whether it is one thing or another is as easy as it is a concrete class or another.</p>

<p>The syntax we use when using a try is as follows:  </p>

<pre><code class="language-cs">Try t = f1(x);  
Try y = f2(t);  
</code></pre>

<p>So, in the end, is a <strong>monad</strong>, as the class Maybe, where f1 would be the ToMaybe and f2 would be the projection of the person's address  </p>

<pre><code class="language-cs">Maybe personaMaybe = persona.ToMaybe();  
Maybe direccionMaybe = personaMaybe.Select(p=&gt;p.Direccion);  
</code></pre>

<p>Like the class Maybe can be put in the chain of operations or pipelines, and catching the exception in the same chain. In the case that was an exception, we have to ensure that the first exception is encapsulated and don't lose the reason and callStack of the original exception.</p>

<h3 id="implementingtry">Implementing Try</h3>

<p>The implementation has three parts, an ITry interface, one class that represents the successful result and another class representing a failure</p>

<pre><code class="language-cs">public interface ITry&lt;T&gt;  
{
    T Value { get; }

    ITry&lt;U&gt; Select&lt;U&gt;(Func&lt;T, ITry&lt;U&gt;&gt; mapper);
}
</code></pre>

<p>In this case, i add only one operation - Select - to make a mapping between to types.</p>

<p>In the case of the class that represents the failure, the exception comes by the constructor</p>

<pre><code class="language-cs">public class Failure&lt;T&gt; : ITry&lt;T&gt;  
{
    private readonly Exception ex;
    public Failure(Exception ex)
    {
        this.ex = ex;
    }

    public T Value
    {
        get { throw new InvalidOperationException("Can't get value for failed Try"); }
    }

    public ITry&lt;U&gt; Select&lt;U&gt;(Func&lt;T, ITry&lt;U&gt;&gt; mapper)
    {
        return ex.ToFailed&lt;U&gt;();
    }

    public Exception GetException()
    {
        return ex;
    }
}
</code></pre>

<p>Please, take a minute to see the Select method.This method is inside the failure class, then don't execute the mapper, on the contrary, the function returns the same exception that was passed in the constructor. Thereby you don't miss the exception that causes the failure, nor the callStack.</p>

<pre><code class="language-cs">public class Success&lt;T&gt; : ITry&lt;T&gt;  
{
    public Success(T newValue)
    {
       Value = newValue;
    }
    public T Value { get; private set; }

    public ITry&lt;U&gt; Select&lt;U&gt;(Func&lt;T, ITry&lt;U&gt;&gt; mapper)
    {
        if (mapper == null)
        {
            return new Failure&lt;U&gt;(new ArgumentNullException(nameof(mapper)));
        }
        try
        {
           return mapper(Value);
        }
        catch (Exception ex)
        {
            return new Failure&lt;U&gt;(ex);
        }
    }
}
</code></pre>

<p>The last step, create a extension class to simplify the creation of Failure or Success instance.</p>

<pre><code class="language-cs">public static class TryExtension  
{
    public static ITry&lt;T&gt; ToSucess&lt;T&gt;(this T data)
    {
        return new Success&lt;T&gt;(data);
    }

    public static ITry&lt;T&gt; ToFailed&lt;T&gt;(this Exception ex)
    {
        return new Failure&lt;T&gt;(ex);
    }
}
</code></pre>

<p>In the client side, you must know if you had success or not the operations. For this reason, <mark>you need patterns matching, the new feature in C#7</mark>. The result would be something like this.  </p>

<pre><code class="language-cs">var searchResult = customerRepository.GetCustomer(index);  
var processResult = ProcessData(searchResult);

switch (processResult)  
{
    case Success&lt;CustomerDTO&gt; success:
    {
        Console.WriteLine(success.Value.CustomerId);
        break;
    }
    case Failure&lt;CustomerDTO&gt; fail:
    {
        Console.WriteLine($"Problems when get customer. Error : { fail.GetException().Message}");
        break;
    }
}
</code></pre>

<p>The switch command can be replaced by if command since we have only two options.</p>

<p>All the <a href="https://github.com/CodeCraftersLab/blog/tree/master/TrySln" target="_blank"> source code you can be found on Github.</a></p>

<h1 id="conclusion">Conclusion</h1>

<p>One important property of Try class is the ability to pipeline or chain, operations and caching exceptions along the way. This class provides some default behaviour in the case of failure. It's error handling, in a functional way. <br>
The last changes on C# 7 allow us to access some high-level features to apply functional programming.</p>

<p>Picture <a href="https://www.flickr.com/photos/smemon/4543895219/in/photolist-7VwDK2-bTjjwM-qBcKDG-ggTDHj-fciM7e-eJm52P-DVK8k-dELbDy-78BLq-bjDRBn-j8CkzQ-56cv4m-7AjDaP-iLpCax-qStGPi-t99zzK-bDH3V2-jqBCkR-26uJov-4yjiHT-axiDj9-7h7fE8-dxHZK4-eGZwL4-de24hb-a8fCT5-pse1sG-bBMEdY-nzz6Mh-qiP46M-smfG8V-ctG6yG-ZEqg-ruWGxb-rnVTKw-fvsAnQ-pCgzjp-8NK6XG-dbG7yi-bCQ64E-dK9BqY-dduGJq-9SXRZW-9WtbLt-nUoafT-dazkH5-7V6vuW-8anMNN-fNAJKh-qDQ6cu" target="_blank">try again</a> by <a href="https://www.flickr.com/photos/smemon/" target="_blank">Sean MacEntee</a>, is licensed under <a href="https://creativecommons.org/licenses/by/2.0/" target="_blank">Creative Commons BY-2.0.</a>.</p>]]></content:encoded></item><item><title><![CDATA[Scaffolding a solution with dotnet CLI]]></title><description><![CDATA[<p>When you work on different projects and also sometimes you have to do an architecture, there comes a time when you realise that it would be great to create a solution template with your projects and dependencies.</p>

<p>You could <a href="http://blog.codecrafterslab.com/scaffolding-solucion-dotnet-cli/">read this post in Spanish here</a></p>

<p>More than once I wanted</p>]]></description><link>https://ghost-azure3fff.azurewebsites.net/scaffolding-a-solution-with-dotnet-cli/</link><guid isPermaLink="false">08a31c14-2431-429a-9eaa-42094b77e22c</guid><category><![CDATA[.net cli]]></category><category><![CDATA[dotnet cli]]></category><category><![CDATA[scaffold]]></category><category><![CDATA[english]]></category><dc:creator><![CDATA[Abel]]></dc:creator><pubDate>Tue, 02 May 2017 21:09:17 GMT</pubDate><media:content url="http://blog.codecrafterslab.com/content/images/2017/03/scaffolding.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://blog.codecrafterslab.com/content/images/2017/03/scaffolding.jpg" alt="Scaffolding a solution with dotnet CLI"><p>When you work on different projects and also sometimes you have to do an architecture, there comes a time when you realise that it would be great to create a solution template with your projects and dependencies.</p>

<p>You could <a href="http://blog.codecrafterslab.com/scaffolding-solucion-dotnet-cli/">read this post in Spanish here</a></p>

<p>More than once I wanted to create a template in visual studio that had the typical thing that you need to make a solution in three layers. The times I wanted to do I found a problem, the cost/benefit ratio. It's very costly to create a template for a solution - it's already difficult for a project template - utility time may be relatively small (think about the times they changed from Visual Studio 2012 to Visual Studio 2017 to just create a web project). Also, Visual Studio changes support for templates arbitrarily amongst versions. Then came out <a href="http://yeoman.io/">yeoman</a> with their <a href="http://yeoman.io/generators/">generators</a> and I forgot a bit about this.</p>

<h2 id="dotnetclitotherescue"><strong>Dotnet CLI ... to the rescue</strong></h2>

<p>But seeing what could be done from the dotnet CLI command line, I took it back with new hopes. And I want to share my results.</p>

<p>First, my problem about cost benefit was solved in full. It took me 30 minutes to see it was doable and 3 hours until I had the script I will show you. And unlike a Visual Studio template, this also works for me on Mac and Linux.</p>

<p>The idea is to create the backend skeleton for a typical 3 layer architecture in .NET. <br>
The requirements are:</p>

<ol>
<li>The solution must have the following projects:
<ul><li>Web API</li>
<li>Messages used in the web API signature</li>
<li>Application layer,</li>
<li>Business layer,</li>
<li>Data layer,</li>
<li>Entities,</li>
<li>Testing projects.</li></ul></li>
<li>All projects must be linked to the solution.</li>
<li>Each project will have references to the other projects it uses. In addition, when necessary they will have references that are in nuget.</li>
<li>Also, I want you to have a directory structure that separates the test code from the application code.</li>
<li>Another thing I have to add to projects is gitignore, so I will download it from the repository that is on GitHub where there are different gitignore dependent on the development tool you use.</li>
<li>Restore references for all projects.</li>
<li>I will compile the solution. Not just a project.</li>
<li>Open the solution with Visual Studio Code.</li>
</ol>

<p>The final idea is to open a bash and write "Bash createBackend3Layer.sh SolutionName".</p>

<h2 id="whatdoyouneedtohaveinstalled"><strong>What do you need to have installed?</strong></h2>

<ul>
<li>.Net Core</li>
<li>The latest .net core SDK.</li>
<li>If you have any problem, download the latest dotnet CLI build from the repository releases on GitHub.</li>
</ul>

<h2 id="letsgoforit"><strong>Let's go for it !!</strong></h2>

<p>If you want to follow the article with the downloaded code, <a href="https://github.com/CodeCraftersLab/blog/blob/master/scaffoldingSolution/crearBackend3Capas.sh">you have it in this GitHub repository</a>.</p>

<h4 id="variabledeclaration"><strong>Variable declaration</strong></h4>

<p>We take the name of the solution that was put as a parameter and we'll create the solution file inside a folder with the same name. If the solution is called "CodeCrafters", there will be "CodeCrafters / CodeCrafters.sln". Same as if you did with Visual Studio. <br>
For each project, I'll use three variables for</p>

<ul>
<li>The project name</li>
<li>The folder where the project will reside</li>
<li>The path where the project file will reside</li>
</ul>

<p>Remember that at this point I am already fulfilling the requirement of placing the code in one directory and tests in another. The code will reside in the src folder and the tests in the test folder</p>

<pre><code>SolutionName=$1;  
SolutionFile="$SolutionName/$SolutionName.sln";  
gitIgnorePath="$SolutionName/.gitignore";  
projExt=".csproj";

WebApiName="$SolutionName.WebApi";  
WebApiPath=${SolutionName%%/}/src/$WebApiName;  
WebApiProj=${WebApiPath%%/}/$WebApiName$projExt;  
</code></pre>

<h4 id="creatingthesolution"><strong>Creating the solution</strong></h4>

<p>We'll tell dotnet CLI to create a solution in a directory called the same as the solution. <br>
Just a detail, to be able to differentiate the steps that will be executed from the script of the rest of values ??that will be written in the console I put the first ones of light green colour.</p>

<pre><code>echo -e "\033[1;92m Create solution \033[0m"  
dotnet new sln -n $SolutionName -o "$SolutionName"  
</code></pre>

<h4 id="createtheprojects"><strong>Create the projects</strong></h4>

<p>In the GitHub script you have all the projects, but here I am giving an example of the three types of projects that are created. <br>
As for directories, the idea is that the API Web Project is in "CodeCrafters / src / CodeCrafters.WebApi / CodeCrafters.WebApi.csproj" <br>
In all of them, I am putting the same framework. In your 2.0 version, you can make the framework come as an optional parameter.😁 <br>
Class library projects can be projects that reference net Standard, and you can specify as a framework the netstandard from 1.0 to 1.6</p>

<pre><code>dotnet new webapi -n $WebApiName -o "$WebApiPath" -f netcoreapp1.1  
dotnet new classlib -n $AppLayerName -o "$AppLayerPath" -f netcoreapp1.1  
dotnet new xunit -n $AppLayerTestName -o "$AppLayerTestPath" -f netcoreapp1.1  
</code></pre>

<h4 id="useagitignore"><strong>Use a gitignore</strong></h4>

<p>There is <a href="https://github.com/github/gitignore">a repository in GitHub that has the different gitignore</a> depending on the tools you use. With the following command line, you can download it from Github and save it in the root folder of the solution.</p>

<pre><code>curl -o $gitIgnorePath 'https://raw.githubusercontent.com/github/gitignore/master/VisualStudio.gitignore'  
</code></pre>

<p>This same mechanism can be used for other files in common use, such as a settings file of StyleCop.</p>

<h4 id="linktheprojectswiththesolution"><strong>Link the projects with the solution.</strong></h4>

<p>You can not leave projects as islands, they belong to a solution and you have to link them. In this line below you look for all the projects and execute the command that links them to the solution.</p>

<pre><code>for refProj in `find $SolutionName -name '*.csproj'` ;  
  do dotnet sln $SolutionFile add $refProj ;  
done
</code></pre>

<p><strong>Note</strong>: This command can be used to execute all test projects. I invite you to make a script that compiles on your computer and run the tests. You already have 50%, you can not complain 😁</p>

<pre><code>for unitTestProj in `find $SolutionName -name '*UnitTest.csproj'` ;  
  do dotnet test $unitTestProj ;  
done 
</code></pre>

<h4 id="crossprojectreferences"><strong>Cross-project references</strong></h4>

<p>To show that the WebApi project requires the Business Layer project you have to execute the following command</p>

<pre><code>dotnet add $WebApiProj reference $BLayerProj 
</code></pre>

<h4 id="externalreferences"><strong>External References</strong></h4>

<p>You can download the external packages from a nuget server, but first look at which references each project brings by default. <br>
For example, the API Web project already brings the MVC package.</p>

<pre><code>dotnet add $DALayerProj package Microsoft.EntityFrameworkCore --package-directory $SolutionName/packages 
</code></pre>

<p>If you are looking for packages that are not in nuget you must specify the URL with the -s parameter.</p>

<pre><code>dotnet add $DALayerProj package Microsoft.EntityFrameworkCore -s https://dotnet.myget.org/F/dotnet-core/api/v3/index.json  
</code></pre>

<p>With everything so far you would have enough, but let's continue to obtain the maximum grade. 👍</p>

<h4 id="restorepackages"><strong>Restore packages</strong></h4>

<p>The nuget packages that you need were already downloaded in the previous step, but those that are predetermined in the projects, such as Microsoft.AspNetCore weren't. Let's download now.</p>

<pre><code>for proj in `find $SolutionName -name '*.csproj'` ;  
  do dotnet restore $proj ;  
done 
</code></pre>

<h4 id="compilethesolution"><strong>Compile the solution</strong></h4>

<p>Here we build the solution, not just a project. When compiling it already detects the dependency between projects.</p>

<pre><code>dotnet msbuild $SolutionFile
</code></pre>

<h4 id="optionalopensolutioninvisualstudiocode"><strong>(Optional) Open solution in Visual Studio Code</strong></h4>

<p>If you have VSCode in your command path, loading the solution is very easy</p>

<pre><code>code $SolutionName
</code></pre>

<h4 id="recommendeduploadafirstversiontoalocalgit"><strong>(Recommended) Upload a first version to a local git</strong></h4>

<p>In Mac and Linux, git comes already integrated into bash, in windows you have to install it. The idea is that you can start a local repository of git and make the first commit with the solution as I left after running the whole script.</p>

<pre><code>pushd $SolutionName  
git init  
git add --all &amp;&amp; git commit -m "Code generate by @CodeCraftersEs"  
popd  
</code></pre>

<p>"But Daniel ... this last one was not among the requirements ..." Well, I always like to surprise my clients giving something more than they wait for. 😁</p>

<h3 id="conclusion"><strong>Conclusion</strong></h3>

<p>Three years ago I did an Angular demo and I used yeoman from the command line to create an MVC web solution. Some saw it as "a step back" because it should be all visual and integrated into Visual Studio.</p>

<p>I think dotnet CLI has opened a different door, one that .net programmers are not as used as node programmers with npm, and it is the use of command line. This is no longer a DevOps thing that makes a script in PowerShell to do something in Azure. Now we can create solutions, add projects, download references, and those commands that we already knew - like <a href="https://github.com/CodeCraftersLab/blog/blob/master/scaffoldingSolution/AddMigration.sh">Add-migration and UpdateDatabase of Entity Framework</a> - and join them in a single script.</p>]]></content:encoded></item><item><title><![CDATA[Practical introduction to functional programming]]></title><description><![CDATA[<p><img src="https://ghost-azure3fff.azurewebsites.net/content/images/2016/12/senoCoseno.png" alt=""></p>

<p>but... <strong>¿why I should learn functional programming?</strong></p>

<p>You could <a href="http://blog.codecrafterslab.com/introduccion-practica-a-la-programacion-funcional/">read this post in Spanish here</a>.</p>

<p>For your professional life, it is very good that you handle at least three types of languages</p>

<ul>
<li>Object Oriented (c #, java)</li>
<li>Dynamic (javascript, python)</li>
<li>Functional (scala, f #, Haskell)</li>
</ul>

<p>Because behind the language itself, is the</p>]]></description><link>https://ghost-azure3fff.azurewebsites.net/practical-introduction-to-functional-programming/</link><guid isPermaLink="false">4c64bb9d-91a5-4d66-845b-5fe6922675cc</guid><category><![CDATA[functional programing]]></category><category><![CDATA[english]]></category><dc:creator><![CDATA[Daniel Mazzini Vidal]]></dc:creator><pubDate>Tue, 02 May 2017 20:38:00 GMT</pubDate><media:content url="http://blog.codecrafterslab.com/content/images/2016/12/senoCoseno.png" medium="image"/><content:encoded><![CDATA[<img src="http://blog.codecrafterslab.com/content/images/2016/12/senoCoseno.png" alt="Practical introduction to functional programming"><p><img src="https://ghost-azure3fff.azurewebsites.net/content/images/2016/12/senoCoseno.png" alt="Practical introduction to functional programming"></p>

<p>but... <strong>¿why I should learn functional programming?</strong></p>

<p>You could <a href="http://blog.codecrafterslab.com/introduccion-practica-a-la-programacion-funcional/">read this post in Spanish here</a>.</p>

<p>For your professional life, it is very good that you handle at least three types of languages</p>

<ul>
<li>Object Oriented (c #, java)</li>
<li>Dynamic (javascript, python)</li>
<li>Functional (scala, f #, Haskell)</li>
</ul>

<p>Because behind the language itself, is the way to solve the problem. And that's what costs the most about functional programming. I'm not talking about one being superior to the other, but that they are two different paradigms and it's good that you have them in your mental toolbox.</p>

<h2 id="whatdoyouneedtoknowtocontinuereading">What do you need to know to continue reading?</h2>

<ul>
<li>Be familiar with object-oriented programming's (hereinafter OOP) concepts like class, objects, polymorphism, and inheritance</li>
<li>Must read C#</li>
</ul>

<h2 id="whatdoyounotneed">What do you not need?</h2>

<ul>
<li>Be an expert on OOP</li>
<li>Being a ninja of C #</li>
<li>Know something of Haskell, Scala, F # and other functional languages.</li>
</ul>

<h2 id="whydoihavetotrustinmaths">Why do I have to trust in maths?</h2>

<p>In Wikipedia, if you are looking for functional programming it says</p>

<blockquote>
  <p>In computer science, functional programming is a paradigm of declarative programming based on the use of <strong>mathematical functions</strong> ...</p>
</blockquote>

<p>What do maths have that will help me become a better programmer? Why do I have to trust them when they almost ruin my teenage years? :)</p>

<p>Let's start with a simple example. A function that returns the Value Added Tax (hereinafter VAT) for a given amount. <br>
First, we define the function, in maths, it will be <code>VAT(amount, percentageVAT) = amount * (percentageVAT / 100)</code> whereas in C # it will be  </p>

<pre><code class="language-cs">public decimal GetVat(double amount, double percentageVAT)  
{
   return (amount * (percentageVAT/100));
}
</code></pre>

<p>Now we call the function defined with the value 100 and 21</p>

<p>Doing maths: <code>VAT(100, 21)</code> and in C # var result = <code>GetVAT (100, 21);</code></p>

<p>From this example, we are able to see <strong>3 things in common that maths and this function of C # have</strong></p>

<ul>
<li>They are only dedicated to calculating the VAT.</li>
<li>The only dependence they have are the input parameters.</li>
<li>For a set of input parameters, only one output value corresponds to those. No matter how many times I put 100 and 21, I'll always get back 21.</li>
</ul>

<h2 id="firstthesofsolid">First: The S of solid.</h2>

<p>Doing maths, adding only adds. You can combine different formulas, but each one is dedicated to his own, it has only a responsibility, that is to say, they are Single responsibility, the S from SOLID</p>

<p>Now let me put a typical object-oriented programming function, add an invoice detail to an invoice.</p>

<pre><code class="language-cs">void AddLine(InvoiceLine newInvoiceLine)  
{
    this.lines.Add(newInvoiceLine); // 1
    this.totalPrice += newInvoiceLine.Total; //2
}
</code></pre>

<p>One of the properties of OOP is encapsulation, and this function acts very well because it hides what happens after adding. But as you have noticed, it does two tasks, 1 - add an item and 2 - recalculate the total.</p>

<p>The first thing you think about is to separate it into two methods</p>

<pre><code class="language-cs">void AddLine(InvoiceLine newInvoiceLine)  
{
  this.lines.add(newInvoiceLine);
}
void UpdateTotal(InvoiceLine newInvoiceLine)  
{
  this.totalPrice += newInvoiceLine.Total;
}
</code></pre>

<p>But the problem with this solution is that you generate a dependency between the functions, forcing to place the second call after the first one so that the internal state remains coherent. The real problem is... total is a materialized result, we need to change to a functional result.  </p>

<pre><code class="language-cs">decimal GetTotal()  
{
   decimal total = 0;
   foreach(var line in this.lines)
   {
      total += line.Total;
   }
   return total;
}
</code></pre>

<p>Now we can remove the <code>totalPrice</code> variable because it is being replaced by the GetTotal function.</p>

<p>We can make the GetTotal function a little different, so it has a more functional style without using the total internal variable, to do this we will use Linq.  </p>

<pre><code class="language-cs">decimal GetTotal()  
{
   return this.details.Sum(item =&gt; item.Price);
}
</code></pre>

<p>Even better, as a read-only property  </p>

<pre><code class="language-cs">public decimal Total  
{ 
       get { return Details.Sum(l =&gt; l.Total); } 
}
</code></pre>

<p>And now, you can write the first functional programming's lesson. <strong>When refactoring to functional programming, the internal state of objects is reduced.</strong></p>

<p>Now we have the first completed objective. Each function has a unique responsibility.</p>

<h2 id="secondnosideeffects">Second: No side effects.</h2>

<p>When a function causes a change to something out of its range, it is called a side effect. Because of this, the function has to receive everything necessary to be able to complete its responsibility by means of parameters.</p>

<p>Continuing with the example of the invoice, imagine that you have a method named cancel. The moment you cancel the invoice you update the balance of the customer.  </p>

<pre><code class="language-cs">private Customer customer;  
public void Cancel()  
{
    this.state = StateKind.canceled;
    this.customer.UpdateBalance(this.GetTotal());
}
</code></pre>

<p>Now let's put a scenario where the customer has a balance of <nobr>500 €</nobr>  and cancels an invoice of <nobr>100 €</nobr>.  </p>

<pre><code class="language-cs">customer.Balance; // 500€  
invoice.Cancel();  
customer.Balance // 600€  
</code></pre>

<p>This is a clear example of a side effect and a function that is not mathematical because it does not always return the same result. How can I do so that Cancel becomes a no-side-effect?</p>

<p>Let's return again to the subject of responsibility. It is not the responsibility of cancelling the invoice to update the customer's balance.  </p>

<pre><code class="language-cs">public void Cancel()  
{
    this.state = StateKind.canceled;
}
</code></pre>

<p>The Customer class will be in charge of receiving an invoice to cancel and thus update your balance. After verifying that the invoice is cancelled, it will adjust the balance.  </p>

<pre><code class="language-cs">public class Customer  
{
   void CancelInvoice(Invoice invoice)
   {
      if (invoice.State == StateKind.canceled;)
      {
         this.UpdateBalance(invoice.Total);
      }
   }
}
</code></pre>

<p>With this design, we have two good news. <br>
1. The Cancel method no longer needs the customer class. Maybe it is needed on another part of the invoice class, but no longer on this method. This makes the Bounded context of the customer object for the billing system more limited. And maybe we will need an integration event to notify Customer bounded context. <br>
2. In the customer class, the UpdateBalance method can now be a private method.</p>

<p>Returning to the previous example we now have  </p>

<pre><code class="language-cs">customer.Balance; // 500€  
invoice.Cancel();  
customer.Balance; // still is 500€  
customer.CancelInvoice(invoice);  
customer.Balance; //now is 600€  
</code></pre>

<p>We have moved the responsibility to the customer so it makes two calls sequentially.</p>

<p>Although this design is better, it is not 100% functional, because the Cancel method modifies a variable (state) that is not received as a parameter.</p>

<h2 id="thirdpurefunctionsorreferentialtransparency">Third: pure functions or referential transparency</h2>

<p>In maths, all functions are referentially transparent. The cosine of a 90-degree angle remains 0, no matter how many years have passed and how many times you repeat it, it will always be <code>Cos (90) = 0</code>. No matter how you pass the reference Cos (89 + 1) or Cos (91- 1), it will be the same result.</p>

<p>Let's go back to the AddInvoice function. Although it is perfectly valid in object-oriented programming, in terms of referential transparency it is not, because it changes the internal state when adding an item to the list.  </p>

<pre><code class="language-cs">void AddLine(InvoiceLine newInvoiceLine)  
{
  this.lines.add(newInvoiceLine);
}
</code></pre>

<p>If we want this function to be a pure and non-side-effect one we need to changes same things:</p>

<p>1 - Expose the properties of the invoice object by the constructor. We going to pass the new state to a new instance. <br>
2 - The internal list of lines change from List to InmutableList. In this way, when we change the collection returns a new immutable list instance. <br>
3 - Create a local function to manage changes in the collection and return an invoice or the same object if we don't have changes. <br>
4 - Adding the item to the immutable collection, and use the previous function. <br>
5 - Change the 'void' by Invoice.</p>

<p>Let's do it. First step. In the future steps, we need to create another invoice instance and pass the new state. One note, When I speak of the state of an object I mean the value of all properties, not just the state property. I'm using one IEnumerable, in this way call this constructor is easier. Inside, I convert it to immutable.  </p>

<pre><code class="language-cs">public Invoice(IEnumerable&lt;InvoiceLine&gt; lines, StateKind state)  
{
    this.lines = lines.ToImmutableList();
    State = state;
}
</code></pre>

<p>The second step. Change the internal variable as ImmutableList, but keep the public as an IEnumerable.  </p>

<pre><code class="language-cs">private ImmutableList&lt;InvoiceLine&gt; lines;  
public IEnumerable&lt;InvoiceLine&gt; Lines  
{
     get { return lines; } 
}
</code></pre>

<p>Third step. Local function. If the immutable instance is different, then create a new Invoice. The property state doesn't change, we create the new invoice instance with the same value we have right now.  </p>

<pre><code class="language-cs">private Invoice WithLines(IEnumerable&lt;InvoiceLine&gt; value)  
{
      return Object.ReferenceEquals(lines, value)
         ? this
         : new Invoice(value, State);
}
</code></pre>

<p>Steps 4th and 5th. When we add an item to the immutable list returns a new instance of an immutable collection, and pass it to the before function.  </p>

<pre><code class="language-cs">public Invoice AddLine(InvoiceLine newOrderLine)  
{
    return WithLines(lines.Add(newOrderLine));
}
</code></pre>

<p>We have the internal function, then we can add remove line functionality.  </p>

<pre><code class="language-cs">public Invoice RemoveLine(InvoiceLine invoiceLine)  
{
    return WithLines(lines.Remove(invoiceLine));
}
</code></pre>

<p>What happend with the property State in the Cancel method? <br>
Ok, we change it.  </p>

<pre><code class="language-cs">public Invoice Cancel()  
{
    return (State == StateKind.canceled)
        ? this
        : new Invoice(Lines, StateKind.canceled);
}
</code></pre>

<p>Second note, <strong>when you try to make functional transparency the immutability of the data as goes without saying</strong>. That is, <strong>immutability is a consequence of the referential transparency</strong> that is used in maths.</p>

<p>Ok, right now the invoice class is immutable, all the property are read-only and any change returns a new Invoice instance.</p>

<p>Now, we are going to do the same in Customer class. Change the constructor, the properties to read-only and the method return a new instance.  </p>

<pre><code class="language-cs">public class Customer  
{
    public Customer(decimal balance)
    {
        this.Balance = balance;
    }

    public decimal Balance { get; private set; }
    public Customer CancelInvoice(Invoice invoice)
    {
        return (invoice.State == StateKind.canceled)
            ? AddToBalance(invoice.Total)
            : this;
    }

    private Customer AddToBalance(decimal total)
    {
        return new Customer(Balance + toTake);
    }
}
</code></pre>

<p>Now let's see how these functions are called. We will start assuming that the detail list has 2 items, one of 5 € and another of <nobr>15 €</nobr>, and the new one we want to add which has a price of <nobr>20 €</nobr>.  </p>

<pre><code class="language-cs">List&lt;InvoiceLine&gt; lines = new List&lt;InvoiceLine&gt;  
{
    new InvoiceLine(1, 5),
    new InvoiceLine(1, 15)
};
Invoice invoice = new Invoice(lines, StateKind.incomplete);  
var invoiceWithNewItem = invoice.AddLine(new InvoiceLine(1, 20));  
Console.WriteLine($"older total -&gt; {invoice.Total}");  
Console.WiteLine($"new total -&gt; {invoiceWithNewItem.Total}");  
</code></pre>

<p>What's really important here is that no matter how many times you run Total for invoice variable, it'll return 20 always because a) any method that modifies the object invoice return a new invoice instance, b) because the total calculation does not keep any internal data.</p>

<p>Now, we're trying with customer objects  </p>

<pre><code class="language-cs">Customer customer = new Customer(500);  
var invoiceCanceled = invoice.Cancel();  
var customerWithInvoiceCanceledProcessed = customer.CancelInvoice(invoiceCanceled);  
Console.WriteLine(customer.Balance); //500  
Console.WriteLine(customerWithInvoiceCanceledProcessed.Balance); //520  
</code></pre>

<p>You can <a href="https://github.com/CodeCraftersLab/blog/blob/master/introFunc/InmutableCollectionTest/Program.cs">find the code here</a>.</p>

<h2 id="conclusionsandnextstepschallenges">Conclusions and next steps/challenges</h2>

<p>We saw a very practical introduction to functional programming - so I hope :) - and how maths can help us to program through functions that:</p>

<ul>
<li>Just have a single responsibility.</li>
<li>Have no side effect.</li>
<li>Use referential transparency.</li>
</ul>

<p>We saw how this impacted on the design of our application. And how it helps us to think differently when solving a problem.</p>

<p>But we have only scratched the surface, it leaves us with some questions that will be seen in other articles such as:</p>

<p>1 - There is no doubt that immutable data are safe, but what about performance? If I have to add 1000 items to the invoice it will create a thousand different instances of the list to finish up using the last one. What about memory? <br>
2 - If the methods do not save the state that is going to be mutated, what happens to the index variables of the for command or to the item variable in a foreach command?</p>]]></content:encoded></item><item><title><![CDATA[Inverted index with Redis]]></title><description><![CDATA[What is a reverse index with Redis and how to use on Redis]]></description><link>https://ghost-azure3fff.azurewebsites.net/reverse-index-with-redis/</link><guid isPermaLink="false">613b4669-a273-444f-a369-192b37bc9d36</guid><category><![CDATA[redis]]></category><category><![CDATA[english]]></category><dc:creator><![CDATA[Daniel Mazzini Vidal]]></dc:creator><pubDate>Mon, 01 May 2017 19:35:00 GMT</pubDate><content:encoded><![CDATA[<blockquote>
  <p>Redis is a NoSQL database of key-value type. When we say this, it
  comes to our head the fact that being key value only serves for
  Cache-type implementations, but fortunately it is not. </p>
</blockquote>

<p>We will see how to create an inverted index that is used for full-text type searches. </p>

<p>You could <a href="http://blog.codecrafterslab.com/indice-inverso-con-redis/">read this post in Spanish here.</a></p>

<p>But first of all, <strong>what is an inverted index?</strong> It is an index that is kept in a separate file - for this reason, the inverted index is also <br>
known as inverted file - and it can refer to more than one source.</p>

<p>To give a practical example, in the Domain Driven Design book, we find the word continuous on page 15 when it talks about continuous learning and on page 341 when it talks about continuous integration. While in the Continuous Delivery book is on page 36. An inverted index would be a document where only the references of the word continuous would be maintained by importance order. For example, it can be believed that if someone searches for the word continuous almost surely is looking for continuous integrations, so the Continuous Delivery book will serve more, then we'll put the second reference of the Domain Driven Design book and finally the reference that talks about continuous learning.</p>

<style type="text/css">

.tg  {border-collapse:collapse;border-spacing:0;border-color:#999;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:0px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#F7FDFA;border-top-width:1px;border-bottom-width:1px;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:0px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#26ADE4;border-top-width:1px;border-bottom-width:1px;}
.tg .tg-yw4l{vertical-align:top}
.tg .tg-6k2t{background-color:#D2E4FC;vertical-align:top}
</style>  

<table class="tg">  
  <tr>
    <th class="tg-yw4l">Document</th>
    <th class="tg-yw4l">Order</th>
    <th class="tg-yw4l">Chapter</th>
    <th class="tg-yw4l">Page</th>
    <th class="tg-yw4l">Paragraph</th>
    <th class="tg-yw4l">Position</th>
  </tr>
  <tr>
    <td class="tg-yw4l">Domain Driven Design</td>
    <td class="tg-yw4l">3</td>
    <td class="tg-yw4l">1</td>
    <td class="tg-yw4l">15</td>
    <td class="tg-yw4l">4</td>
    <td class="tg-yw4l">1</td>
  </tr>
  <tr>
    <td class="tg-6k2t">Domain Driven Design</td>
    <td class="tg-6k2t">2</td>
    <td class="tg-6k2t">14</td>
    <td class="tg-6k2t">341</td>
    <td class="tg-6k2t">1</td>
    <td class="tg-6k2t">1</td>
  </tr>
  <tr>
    <td class="tg-yw4l">Continuous Delivery</td>
    <td class="tg-yw4l">1</td>
    <td class="tg-yw4l">2</td>
    <td class="tg-yw4l">36</td>
    <td class="tg-yw4l">4</td>
    <td class="tg-yw4l">5</td>
  </tr>
</table>

<p>The aim is to have much faster searches regarding full-text search type, and against it will take much longer to add a document because all words have to be analyzed, words that do not have semantically value (a, al, If, etc.) must be discarded and new files must be created for new words or indexes must be updated if they already exist.</p>

<h3 id="howdowedoitwithredis"><strong>How do we do it with Redis?</strong></h3>

<p>For each word we create an ordered list being the word to search the key of the list. In the ordered list we add the position of the ranking that will occupy and a reference or alias of the position where it is.</p>

<pre><code>ZADD continuous 3 refDDD1
ZADD continuous 2 refDDD2
ZADD continuous 1 refCD1
</code></pre>

<blockquote>
  <p>Note: I am using the Redis commands directly so that you can play it
  with the redis-cli.exe that is in the installation directory of Redis
  itself. I do not want to limit the example to a platform and a single
  driver. </p>
</blockquote>

<p>The result after processing the entries for continuous, integration and learning would be this</p>

<p><img src="http://blog.codecrafterslab.com/content/images/2016/12/Indice-inverso-1.PNG" alt="enter image description here"></p>

<p>To make an autocomplete type search, we add the necessary <strong>n-gram</strong>. As an example, I will do it with the first reference  </p>

<pre><code class="language-sh">    ZADD c 1 refCD1
    ZADD co 1 refCD1
    ZADD con 1 refCD1
    ZADD cont 1 refCD1
    ZADD conti 1 refCD1
    ZADD contin 1 refCD1
    ZADD continu 1 refCD1
    ZADD continuo 1 refCD1
    ZADD continuou 1 refCD1
    ZADD continuous 1 refCD1

    ZADD c 2 refDD2
    ZADD co 2 refDD2
    ZADD con 2 refDD2
    ....
</code></pre>

<p>Then each alias is placed as the key of a hash structure with the other values that we are interested on, which are on the search, such as a document, chapter, and page.  </p>

<pre><code class="language-sh">    HMSET refDDD1 document “Domain Driven Design” chapter 1 page 15 paragraph 4 position 1
    HMSET refDDD2 document “Domain Driven Design” chapter 14 page 341 paragraph 1 position 1
    HMSET refCD1 document “Continuous Delivery” chapter 2 page 36 paragraph 4 v5
</code></pre>

<h3 id="andnowletssearch"><strong>And now let's search!</strong></h3>

<p>When we have all the words with their n-grams, we have to apply the search algorithm. Let's take the example someone writes "con" as a keyword.  </p>

<pre><code class="language-sh">    zrange con 0 4
</code></pre>

<p>With this command, we will get the first five words (the start and end position are included) from the sorted list which has the "con" key. As it is an ordered list the result will be:  </p>

<pre><code class="language-sh">    refCD1 
    refDDD2
    refDDD1
</code></pre>

<p>We take these values ??and look for each value as a hash to get the name of the document  </p>

<pre><code class="language-sh">    HGET refCD1 document
</code></pre>

<p>The result of this last command will be  </p>

<pre><code class="language-sh">    Continuous Delivery
</code></pre>

<h3 id="performance"><strong>Performance</strong></h3>

<p>According to the Redis documentation, the <a href="https://redis.io/commands/zrange">zrange command</a> is an operation with a cost O (log (N) + M) cost where N is the number of records that has the ordered list (ie our inverse index) and M the number of items that we want to return.</p>

<p>While the <a href="https://redis.io/commands/hget">HGET command</a> has an O (1) complexity, that is, it has the same cost, no matter how large the hash.</p>

<p>If in the example we had to return not only the name of the document but also the title, paragraph, etc ... we would have to use the <a href="https://redis.io/commands/hgetall">command HGETALL</a>, this command has a cost of O (N), that is to say, it increases the more properties Of the document we saved.</p>

<p>If what you like are numbers of an application in production, I tell you ... for a ranking of 150,000 positions, with an average of 16 words per position that included the name of the product and synonymous words, a ZRANGE is made that takes 30 Records and then 30 HGET searches to obtain the product title, that is <strong>31 searches, and it takes 4 milliseconds</strong> in an i7 to 2.3 Ghz and it does not take more than 400 Mb of RAM.</p>]]></content:encoded></item><item><title><![CDATA[FAQ about patterns]]></title><description><![CDATA[FAQ about patterns]]></description><link>https://ghost-azure3fff.azurewebsites.net/faq-about-patterns/</link><guid isPermaLink="false">6fe48517-303c-45da-8b81-2c09de72f02f</guid><category><![CDATA[english]]></category><category><![CDATA[patterns]]></category><dc:creator><![CDATA[Daniel Mazzini Vidal]]></dc:creator><pubDate>Mon, 01 May 2017 18:53:23 GMT</pubDate><media:content url="http://blog.codecrafterslab.com/content/images/2017/03/faq-2027970_640.png" medium="image"/><content:encoded><![CDATA[<img src="http://blog.codecrafterslab.com/content/images/2017/03/faq-2027970_640.png" alt="FAQ about patterns"><p><em>Today I want to write about some questions people are asking me about the patterns' subject.</em></p>

<p>You could <a href="http://blog.codecrafterslab.com/faq-sobre-patrones/">read this post in Spanish here</a>.</p>

<h3 id="whatarethey"><strong>What are they?</strong></h3>

<p>Patterns are <strong>verified solutions to recurring problems</strong> in design and software development. For a solution to be considered a pattern, it must have some characteristics, such as to demonstrate that it can be applied in different technologies, meaning that it is an <strong>agnostic and reusable knowledge</strong> that can be broken down into well-defined roles or responsibilities, and has demonstrated its effectiveness under certain circumstances. These circumstances have been given the name of forces and are the reasons to use the pattern and to identify it from a different one.</p>

<h3 id="whyihavetoknowthem"><strong>Why I have to know them?</strong></h3>

<p>Luckily, there is not a single reason! But there are several reasons for you to know them.</p>

<p><strong>Because you do not need to re-invent the wheel</strong>. Patterns try to avoid the repetition to search for solutions from problems already known, so you do not re-invent the wheel.</p>

<p><strong>Because you will go on the shoulders of giants.</strong> Yes, yes ... You will be applying solutions that hundreds of architects with a lot of experience have used and refined over the years.</p>

<p><strong>Because they will help you to structure your code.</strong> Patterns have well-defined roles or participants. For example, in an Observer pattern, there is the observer and the observed subject. This way you will avoid programming everything together in a single class.</p>

<p><strong>Because they will be part of your developer jargon.</strong> This is like police saying "it's a 3218" and understand it they alone. With patterns, you will say "You have to do an Abstract Factory" and all the developers should know what you are talking about. Moreover, they should think about the different roles of the pattern.</p>

<p><strong>Because you will formalize the design.</strong> Neither reaching to the extreme case of "To a hammer, all problems look like nails", nor pretending to eradicate creativity, what patterns search for is if your solution has encountered a problem that has an already tested solution. If you have a tree structure in your solution you should encounter yourself with a Composite pattern.</p>

<p><strong>Because they are becoming more known.</strong> In recent years, I have seen how different languages and frameworks were adding patterns. Some of them are:</p>

<ol>
<li><strong>Iterators</strong> (foreach) in OO languages.</li>
<li><strong>Abstract Factory</strong> in ADO.NET to create connections and commands.</li>
<li>WPF and <strong>command</strong> to execute UI actions.</li>
<li>Aspnet and the radical change in the use of <strong>MVC</strong> to handle HTTP requests.</li>
<li>Js Frameworks which have <strong>observables</strong> or are MV* (Knockout, Angular, Aurelia, Vue, to name a few) to keep the HTML updated.</li>
<li>Rx.Net and the use of <em>*observables</em>.</li>
<li>NodeJs and its <strong>event loop</strong>. If you want to know why Node is so fast you should know this pattern.</li>
<li>Redux and its <strong>immutable state</strong>.</li>
</ol>

<p>If someone approaches you and tells you that patterns are a waste of time and are used by only 4 geeks, you already have arguments to say that it is not the case.</p>

<p><strong>Because they will be the best professional investment you can make.</strong> This is not a Javascript framework that appears today and in 6 months appears another one, and you have to be jumping from a "Getting Started" to another. This is a basic knowledge that you then apply in different programming languages. If you still have doubts I'm going to tell you my experience. I learned about patterns before the year 2000. At that time I was programming Visual Basic 6, that was not 100% object oriented because it had interfaces, and it hadn't inheritance. I started to develop patterns that were based on interfaces like the adapter or strategy pattern with VB, and for those languages which used inheritance, I started to write them in Java until on 2001 I could start doing on C #. About 2 years ago, I had to work on a project where I applied user interface patterns with typescript. <strong>How much technological knowledge can you use after 15 years?</strong></p>

<h3 id="butiamalreadydoingthis"><strong>But I am already doing this !!</strong></h3>

<p>It's possible that if you structure your code well you are already using some pattern without knowing it. If you are in that group, you are a machine! Now learn the pattern's name and you will be able to communicate better with other programmers.</p>

<h3 id="doineedtoknowthemall"><strong>Do I need to know them all?</strong></h3>

<p>No, it's not necessary. My advice is to first try to link the problem - or as I said at the beginning, the forces - and the name of the pattern that solves it. When you have the problem, remembering the name you can search the internet to see some implementation in a blog or in GitHub. Then start to learn well the ones you see more often.</p>

<p>What you must know is that there are different patterns for different paradigms or scopes. To name a few you have patterns for object-oriented programming, functional programming, cloud, concurrency, domain driven design, etc.</p>

<h3 id="whatsthedifferencebetweendevelopmentprinciples"><strong>What's the difference between development principles?</strong></h3>

<p>I'll explain it with an example. If you want to design a car that has adhesion, you have to do it with front-wheel drive. This is an example of a recurring problem and linked solution, namely a pattern. Following the example, the principles would be the basic rules for an engine to work.</p>

<p>Development principles are a guide that helps you have an easy-to-maintain and an easy-to-change code, and not being fragile in the face of change - something you touch on one side and stops working on the other side. To me, development principles are before patterns, and patterns often apply these principles.</p>

<h3 id="dotheyalwayshavetobeused"><strong>Do they always have to be used?</strong></h3>

<p>No, forcing the use of a pattern is often a mistake. Let's go back to the previous question for a minute. There is a principle called YAGNI, which comes to say to not do something you do not need. And believe me, there are two things you will never need, a poorly built architecture and an over-architecture, which in the end is nothing more than a poorly built architecture.</p>

<h3 id="conclusion"><strong>Conclusion</strong></h3>

<p>I have used patterns for over 15 years and I will continue to use them for the advantages they offer. I urge you to learn about them and also use them. The benefit cost is amazing.</p>]]></content:encoded></item><item><title><![CDATA[[SPA] Scaffolding de una solución con dotnet CLI]]></title><description><![CDATA[Uso de dotnet cli para generar un scaffolding de un backend para proyectos  en capas. ]]></description><link>https://ghost-azure3fff.azurewebsites.net/scaffolding-solucion-dotnet-cli/</link><guid isPermaLink="false">6799d45a-3bd6-41fa-8f90-535886d06328</guid><dc:creator><![CDATA[Daniel Mazzini Vidal]]></dc:creator><pubDate>Tue, 28 Mar 2017 22:28:24 GMT</pubDate><media:content url="http://blog.codecrafterslab.com/content/images/2017/03/scaffolding.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://blog.codecrafterslab.com/content/images/2017/03/scaffolding.jpg" alt="[SPA] Scaffolding de una solución con dotnet CLI"><p>Cuando vas trabajando en diferentes proyectos y además algunas veces te toca hacer arquitectura, llega un momento en que te das cuenta que estaría muy bien crear un template de una solución con sus proyectos y dependencias.</p>

<p>Más de una vez quise crear un template en visual studio que tuviera lo típico que necesitas para hacer una solución en tres capas. Las veces que lo quise hacer me encontré con un problema, la relación coste/beneficio. Es muy costoso crear un template de una solución - ya lo es el template de un proyecto - el tiempo de utilidad podría ser relativamente poco (piensa las veces que ha cambiado desde Visual Studio 2012 al Visual Studio 2017 la creación de un proyecto web). Además Visual Studio cambia el soporte a los templates arbitrariamente entre versión y versión. Después apareció <a href="http://yeoman.io/" target="_blank">yeoman</a> con sus <a href="http://yeoman.io/generators" target="_blank">generadores</a> y me olvidé un poco de esto.</p>

<h2 id="dotnetclitotherescue">Dotnet CLI... to the rescue</h2>

<p>Pero al ver lo que se puede hacer desde la línea de comandos de dotnet cli, lo retome con nuevas esperanzas. Y quiero compartir mis resultados.</p>

<p>Lo primero, mi problema sobre el coste beneficio se resolvió de pleno. Tarde 30 minutos en ver que era viable y 3 horas hasta tener el script que te muestro. Y a diferencia de un template de Visual Studio, esto también me funciona en Mac y Linux.</p>

<p>La idea es crear el esqueleto de una backend típico en .net como puede ser una arquitectura de 3 capas. <br>
Los requerimientos son:</p>

<ol>
<li>La solución tiene que tener los siguientes proyectos: <br>
<ul><li>web api,</li>
<li>Mensajes usados en la firma del web api</li>
<li>application layer,</li>
<li>business layer,</li>
<li>data layer,</li>
<li>entidades,</li>
<li>proyectos de pruebas.</li></ul></li>
<li>Todos los proyectos deberán estar asociados a la solución.  </li>
<li>Cada proyecto tendrá las referencias a los otros proyectos que usa. Además, cuando sea necesario tendrán referencias que estén en nuget.  </li>
<li>Además, quiero que cuente con una estructura de directorios que separe el código de pruebas del código de aplicación.  </li>
<li>Otra de las cosas que me toca agregar a los proyectos es el gitignore, así que me lo descargaré del repositorio que está en GitHub donde hay diferentes gitignore dependientes de la herramienta de desarrollo que uses.  </li>
<li>Restaurar las referencias de todos los proyectos  </li>
<li>Compilare la solución. No solo un proyecto.  </li>
<li>Abrir la solución con Visual Studio Code.</li>
</ol>

<p>La idea final es abrir un bash y escribir "Bash crearBackend3Capas.sh NombreSolucion".</p>

<h2 id="quenecesitastenerinstalado">¿Que necesitas tener instalado?</h2>

<ul>
<li>.Net Core</li>
<li>El último SDK de .net core.</li>
<li>Si tienes algún problema, bájate el último build de dotnet cli desde las release del repositorio en GitHub.</li>
</ul>

<h2 id="vamosaporello">¡¡Vamos a por ello!!</h2>

<p>Si quieres seguir el artículo con el código descargado, <a href="https://github.com/CodeCraftersLab/blog/blob/master/scaffoldingSolution/crearBackend3Capas.sh" target="_blank"> lo tienes en este GitHub.</a></p>

<h4 id="declaracindevariables">Declaración de variables</h4>

<p>Tomamos el nombre de la solución que se puso como parámetro y creamos el archivo de la solución dentro de una carpeta con el mismo nombre. Si la solución se llama "CodeCrafters", quedará "CodeCrafters/CodeCrafters.sln". Igual que si lo hicieras con Visual Studio. <br>
Por cada proyecto uso tres variables para </p>

<ul>
<li>el nombre del proyecto</li>
<li>la carpeta donde se pondrá el proyecto</li>
<li>el path donde estará el archivo del proyecto</li>
</ul>

<p>Recordar que en este punto ya estoy cumpliendo el requisito de colocar el código en un directorio y los test en otro. El código irá a src y las pruebas a test  </p>

<pre><code class="language-bash">SolutionName=$1;  
SolutionFile="$SolutionName/$SolutionName.sln";  
gitIgnorePath="$SolutionName/.gitignore";  
projExt=".csproj";

WebApiName="$SolutionName.WebApi";  
WebApiPath=${SolutionName%%/}/src/$WebApiName;  
WebApiProj=${WebApiPath%%/}/$WebApiName$projExt;  
</code></pre>

<h4 id="crearlasolucin">Crear la solución</h4>

<p>Le decimos a dotnet cli que nos cree una solución en un directorio llamado igual que la solución. <br>
Un detalle, para poder diferenciar los pasos que se van ejecutan del script del resto de valores que se escribirán en la consola pongo los primeros de color verde claro.  </p>

<pre><code class="language-bash">echo -e "\033[1;92m Create solution \033[0m"  
dotnet new sln -n $SolutionName -o "$SolutionName"  
</code></pre>

<h4 id="crearlosproyectos">Crear los proyectos</h4>

<p>En el script en GitHub tenes todos los proyectos, pero aquí pongo un ejemplo de los tres tipos de proyectos que se crean. <br>
En cuanto a directorios, la idea es que el Proyecto de Web Api este en "CodeCrafters/src/CodeCrafters.WebApi/CodeCrafters.WebApi.csproj" <br>
En todos estoy poniendo el mismo framework. En tu version 2.0 puedes hacer que el framework venga como un parámetro opcional. 😁 <br>
Los proyectos de tipo librería de clases pueden ser proyectos que referencien net Standart, puedes especificarle como framework el netstandard1.0 al 1.6  </p>

<pre><code class="language-bash">dotnet new webapi -n $WebApiName -o "$WebApiPath" -f netcoreapp1.1  
dotnet new classlib -n $AppLayerName -o "$AppLayerPath" -f netcoreapp1.1  
dotnet new xunit -n $AppLayerTestName -o "$AppLayerTestPath" -f netcoreapp1.1  
</code></pre>

<h4 id="ponerungitignore">Poner un gitignore</h4>

<p>Hay <a href="https://github.com/github/gitignore" target="_blank">un repositorio en GitHub que tiene los diferentes gitignore</a> según la herramientas que uses. Con la siguiente línea de comandos lo bajas de Github y lo grabas en la carpeta raíz de la solución.  </p>

<pre><code class="language-bash">curl -o $gitIgnorePath 'https://raw.githubusercontent.com/github/gitignore/master/VisualStudio.gitignore'  
</code></pre>

<p>Este mismo mecanismo te puede servir para otros archivos de uso común, como puede ser un archivo de settings de StyleCop.  </p>

<h4 id="asociarlosproyectosalasolucin">Asociar los proyectos a la solución.</h4>

<p>No puedes dejar los proyectos como islas, pertenecen a una solución y tienes que asociarlos. En esta línea de abajo buscas todos los proyectos y le ejecutas el comando que los asocia a la solución.  </p>

<pre><code class="language-bash">for refProj in `find $SolutionName -name '*.csproj'` ;  
  do dotnet sln $SolutionFile add $refProj ;  
done  
</code></pre>

<p><strong>Nota:</strong> Este comando te puede servir para ejecutar todos los proyectos de test. Te invito a que te hagas un script que en tu ordenador compile y ejecute los test. Ya tienes el 50%, no te puedes quejar  😁 </p>

<pre><code class="language-bash">for unitTestProj in `find $SolutionName -name '*UnitTest.csproj'` ;  
  do dotnet test $unitTestProj ;  
done  
</code></pre>

<h4 id="referenciasentreproyectos">Referencias entre proyectos</h4>

<p>Para indicar que el proyecto de WebApi necesita del proyecto de Business Layer tienes que ejecutar el siguiente comando  </p>

<pre><code class="language-bash">dotnet add $WebApiProj reference $BLayerProj  
</code></pre>

<h4 id="referenciasexternas">Referencias externas</h4>

<p>Puedes bajarte de un servidor de nuget los paquetes externos, pero primero mira que referencias trae en forma predeterminada cada proyecto. Por ejemplo, el proyecto de Web Api ya trae el paquete de MVC.  </p>

<pre><code class="language-bash">dotnet add $DALayerProj package Microsoft.EntityFrameworkCore --package-directory $SolutionName/packages  
</code></pre>

<p>Si buscas paquetes que no están en nuget debes especificar la url con el parámetro -s  </p>

<pre><code class="language-bash">dotnet add $DALayerProj package Microsoft.EntityFrameworkCore -s https://dotnet.myget.org/F/dotnet-core/api/v3/index.json  
</code></pre>

<p>Con lo que llevas hasta el momento ya tendrías suficiente, pero seguimos para matricula de honor. 👍 </p>

<h4 id="restaurarpaquetes">Restaurar paquetes</h4>

<p>Los paquetes de nuget que tu necesitas ya se descargaron en el paso anterior, pero los que estan predeterminados en los proyectos, como Microsoft.AspNetCore no. Ahora toca descargarlos.  </p>

<pre><code class="language-bash">for proj in `find $SolutionName -name '*.csproj'` ;  
  do dotnet restore $proj ;  
done  
</code></pre>

<h4 id="compilarlasolucin">Compilar la solución</h4>

<p>Acá hacemos un build de la solución, no solo de un proyecto. Al compilar ya detecta la dependencia entre proyectos.</p>

<pre><code class="language-bash">dotnet msbuild $SolutionFile  
</code></pre>

<h4 id="opcionalabrirlasolucinenvisualstudiocode">(opcional) Abrir la solución en Visual Studio Code</h4>

<p>Si tienes VSCode en el path cargar la solución es facilísimo  </p>

<pre><code class="language-bash">code $SolutionName  
</code></pre>

<h4 id="recomendablesubirunaprimeraversionaungitlocal">(recomendable) Subir una primera version a un git local</h4>

<p>En Mac y Linux el git viene integrado en el bash, en windows tienes que instalarlo. La idea es que puedas iniciar un repositorio local de git y hacer un primer commit con la solución como quedo después de ejecutar todo el script.</p>

<pre><code class="language-bash">pushd $SolutionName  
git init  
git add --all &amp;&amp; git commit -m "Code generate by @CodeCraftersEs"  
popd  
</code></pre>

<p>"Pero Daniel... esto último no estaba entre los requerimientos..." Es que siempre me gusta sorprender a mis clientes dando algo mas de los que esperan.   😁 </p>

<h3 id="conclusin">Conclusión</h3>

<p>Hace tres años atrás hice una demo de angular y use yeoman desde la línea de comandos para crear una solución web mvc. Algunos lo vieron como "un paso atrás", que tenía que ser todo visual e integrado en Visual Studio.</p>

<p>Creo que con dotnet CLI se ha abierto un melón diferente, uno al que los programadores .net no estamos tan acostumbrados como los programadores node con npm, y es el uso de la línea de comandos. Esta ya no es cosa de devOps que hacen un script en powershell para hacer algo en Azure. Ahora podemos crear soluciones, agregar proyectos, descargar referencias, y aquellos comandos que ya conocíamos - como <a href="https://github.com/CodeCraftersLab/blog/blob/master/scaffoldingSolution/AddMigration.sh" target="_blank"> Add-migration y UpdateDatabase de Entity Framework </a> - unirlos en un solo script.</p>]]></content:encoded></item><item><title><![CDATA[[SPA] FAQ sobre patrones]]></title><description><![CDATA[Preguntas frecuentes sobre el uso de patrones en el desarrollo de software]]></description><link>https://ghost-azure3fff.azurewebsites.net/faq-sobre-patrones/</link><guid isPermaLink="false">1d8a36d0-981e-4b50-a30c-d6e3def549ee</guid><category><![CDATA[patterns]]></category><dc:creator><![CDATA[Daniel Mazzini Vidal]]></dc:creator><pubDate>Tue, 07 Mar 2017 22:19:05 GMT</pubDate><media:content url="http://blog.codecrafterslab.com/content/images/2017/03/faq-2027970_640.png" medium="image"/><content:encoded><![CDATA[<img src="http://blog.codecrafterslab.com/content/images/2017/03/faq-2027970_640.png" alt="[SPA] FAQ sobre patrones"><p><em>Hoy quiero escribir sobre algunas preguntas que me hacen sobre el tema patrones.</em></p>

<h2 id="quson">¿Qué son?</h2>

<p>Los patrones son <strong>soluciones contrastadas a problemas recurrentes</strong> en el desarrollo y diseño de software. Para que una solución se considere un patrón debe tener algunas características como, por ejemplo, demostrar que se puede aplicar en diferentes tecnologías, es decir es un <strong>conocimiento agnóstico y reusable</strong>, que puede descomponerse en responsabilidades o roles bien definidos, y que ha demostrado su eficacia bajo ciertas circunstancias. A esas circunstancias se le da el nombre de fuerzas y son los motivos para usar el patrón y para identificarlo de otro diferente.</p>

<h2 id="porquetengoqueconocerlos">¿Porque tengo que conocerlos?</h2>

<p>Por suerte ¡no hay un solo porqué! sino que hay varios motivos para que los conozcas.</p>

<p><strong>Porque no necesitas reinventar la rueda.</strong> Los patrones pretenden evitar la reiteración de búsquedas de soluciones a problemas ya conocidos, que no re inventes la rueda. </p>

<p><strong>Porque iras en hombros de gigantes.</strong> Si, si... Estarás aplicando soluciones que cientos de arquitectos con muchísima experiencia han usado y refinado a lo largo de los años.</p>

<p><strong>Porque te ayudarán a estructurar tu código.</strong> Los patrones tienen roles o participantes bien definidos. Por ejemplo, en un patrón Observer, está el que observa y el sujeto observado. De esta manera evitaras programar todo junto en una sola clase.</p>

<p><strong>Porque serán parte de tu jerga de desarrollador.</strong> Esto es como la policía que dice <em>“es un 3218”</em> y lo entienden solo ellos. Pues con los patrones dirás <em>“Hay que hacer un Abstract Factory”</em> y todos los desarrolladores deberían saber de qué estás hablando. Es más, deberían pensar en los diferentes roles del patrón. </p>

<p><strong>Porque formalizaras el diseño.</strong> Sin llegar al caso extremo de “Para un martillo todos los problemas son clavos”, ni tampoco pretendiendo erradicar la creatividad, lo que buscan los patrones es que si tu solución se ha encontrado con un problema que tenga la solución testeada. Si en tu solución tienes unas estructuras de árbol deberías encontrarte con un patrón Composite.</p>

<p><strong>Porque se están dando a conocer más.</strong>  En los últimos años, he visto como diferentes lenguajes y framework iban agregando patrones. Algunos de ellos son:</p>

<ol>
<li>Los iteradores (foreach) en lenguajes OO.  </li>
<li>Abstract Factory en ADO.NET para crear conexiones y comandos.  </li>
<li>WPF y los commands para ejecutar acciones de UI.  </li>
<li>Aspnet y el cambio radical en el uso de MVC para gestionar las peticiones http.  </li>
<li>Framework js de tipo MV* y los observables (Knockout, Angular, Aurelia, Vue, por nombrar algunos) para mantener el html actualizado.  </li>
<li>Rx.Net y el uso de observables.  </li>
<li>NodeJs y su event loop. Si quieres saber porque Node es tan rápido debes conocer este patrón.  </li>
<li>Redux y su estado inmutable.</li>
</ol>

<p>Si alguien se te acerca y te dice que los patrones son una pérdida de tiempo y que lo usan 4 friquis, ya tienes argumentos para decir que no es así.</p>

<p><strong>Porque serán la mejor inversión profesional que puedes realizar.</strong> Esto no es un framework de Javascript que hoy sale uno y en 6 meses otro y tienes que estar saltando de un “Getting Started” o a otro. Esto es un conocimiento base que después vas aplicando en diferentes lenguajes de programación. Si todavía te quedan dudas te cuento mi experiencia. Aprendí sobre patrones antes del año 2000. En aquel entonces programaba en Visual Basic 6, aquel que no era 100% orientado a objetos porque tenia interfaces, pero no tenía herencia. Empecé a desarrollar patrones que se basan en interfaces como <em>adapter</em> o <em>strategy</em> con VB, y para los que usan herencia empecé a escribirlos en  Java, hasta que en el 2001 pude hacerlos en C#. Hace cosa de 2 años, me tocó trabajar en un proyecto donde aplique patrones en la interfaz de usuario con typescript. <strong>¿cuanto conocimiento tecnológico puedes usar despues de 15 años?</strong> </p>

<h2 id="perosiestoyoyalohago">Pero si esto yo ya lo hago!!</h2>

<p>Es muy posible que si estructuras bien tu código ya estés usando algún patrón, pero sin saberlo. Si estas en ese grupo, ¡eres un maquina! Ahora apréndete el nombre del patrón y podrás comunicarte mejor con otros programadores.</p>

<h2 id="hacefaltaconocerlostodos">¿Hace falta conocerlos todos?</h2>

<p>No, no hace falta. Mi consejo es que primero intentes asociar el problema - o como decia al principio, las fuerzas - y el nombre del patrón que lo resuelve. Cuando tengas el problema, recordando el nombre podrás buscarlo en internet para ver alguna implementación en algún blog o en GitHub. Después apréndete bien aquellos que consultes más.</p>

<p>Lo que si tienes que saber es que hay diferentes patrones para diferentes paradigmas o ámbitos. Por nombrar algunos tienes patrones de programación orientada a objetos, de programación funcional, de cloud, de concurrencia, de domain driven design, etc.</p>

<h2 id="qudiferenciahayconlosprincipiosdedesarrollo">¿Qué diferencia hay con los principios de desarrollo?</h2>

<p>Te lo explico con un ejemplo. Si quieres diseñar un coche que tenga adherencia, tienes que hacerlo con tracción delantera. Esto es un ejemplo de problema recurrente y solución asociada, es decir un patrón. Siguiendo con el ejemplo, los principios serían las normas básicas para que un motor funcione.</p>

<p>Los principios de desarrollo representan una guía que te ayuda a tener código fácil de mantener y fácil de cambiar, y que no sea frágil ante el cambio - aquello de que tocas en un lado y deja de fusionar otro. Para mis los principios están antes que los patrones, y los patrones suelen aplicar estos principios.</p>

<h2 id="hayqueusarlossiempre">¿Hay que usarlos siempre?</h2>

<p>No, forzar el uso de un patrón suele ser un error. Volvemos por un minuto a la pregunta anterior. Hay un principio que se llama YAGNI, que viene a decir que no hagas algo que no necesitas. Y créeme, hay dos cosas que nunca necesitaras, una arquitectura mal hecha y una sobre-arquitectura, que al final no es otra cosa que una arquitectura mal hecha.</p>

<h2 id="conclusin">Conclusión</h2>

<p>He usado patrones por más de 15 años y seguiré usándolos por las ventajas que ofrece. Te insto a que puedas aprender sobre ellos y usarlos. El coste beneficio es bestial.</p>]]></content:encoded></item><item><title><![CDATA[[SPA] Indice inverso con Redis]]></title><description><![CDATA[<blockquote>
  <p>Redis es una base de datos NoSQL de tipo clave valor. Cuando decimos esto, acude a nuestra cabeza el hecho de que al ser clave valor solo sirve para implementaciones de tipo Cache, pero por suerte no es así. Veremos <strong>cómo crear un índice inverso</strong> que sirve para las búsquedas</p></blockquote>]]></description><link>https://ghost-azure3fff.azurewebsites.net/indice-inverso-con-redis/</link><guid isPermaLink="false">208facce-1cb5-4fd5-8730-97f8976f04a9</guid><dc:creator><![CDATA[Daniel Mazzini Vidal]]></dc:creator><pubDate>Thu, 29 Dec 2016 21:55:11 GMT</pubDate><content:encoded><![CDATA[<blockquote>
  <p>Redis es una base de datos NoSQL de tipo clave valor. Cuando decimos esto, acude a nuestra cabeza el hecho de que al ser clave valor solo sirve para implementaciones de tipo Cache, pero por suerte no es así. Veremos <strong>cómo crear un índice inverso</strong> que sirve para las búsquedas de tipo full text search.</p>
</blockquote>

<p>Pero primero de todo <strong>¿qué es un índice inverso?</strong> Es un índice que se mantiene en un archivo aparte - por este motivo, al índice inverso también se lo conoce como archivo inverso - y que puede hacer referencia a más de una fuente.</p>

<p>Para dar un ejemplo práctico, en el libro Domain Driven Design, me encuentro con la palabra continuous en la página 15 cuando habla de continuous learning y en la página 341 cuando habla de continuous integration. Mientras que en el libro Continuous Delivery se encuentra en la página 36. Un índice inverso sería un documento donde solo se mantengan las referencias de la palabra continuous ordenadas por orden de importancia. Por ejemplo, puede creer que si alguien busca la palabra continuous seguramente estará buscando continuos integrations por lo tanto el libro de Continuous Delivery le servirá más, luego pondré la segunda referencia del libro Domain Driven Design y por último la referencia que habla de continuous learning.</p>

<style type="text/css">  
.tg  {border-collapse:collapse;border-spacing:0;border-color:#999;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:0px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#F7FDFA;border-top-width:1px;border-bottom-width:1px;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:0px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#26ADE4;border-top-width:1px;border-bottom-width:1px;}
.tg .tg-yw4l{vertical-align:top}
.tg .tg-6k2t{background-color:#D2E4FC;vertical-align:top}
</style>  

<table class="tg">  
  <tr>
    <th class="tg-yw4l">Documento</th>
    <th class="tg-yw4l">Orden</th>
    <th class="tg-yw4l">Capítulo</th>
    <th class="tg-yw4l">Página</th>
    <th class="tg-yw4l">Párrafo</th>
    <th class="tg-yw4l">Posición</th>
  </tr>
  <tr>
    <td class="tg-6k2t">Domain Driven Design</td>
    <td class="tg-6k2t">3</td>
    <td class="tg-6k2t">1</td>
    <td class="tg-6k2t">15</td>
    <td class="tg-6k2t">4</td>
    <td class="tg-6k2t">1</td>
  </tr>
  <tr>
    <td class="tg-yw4l">Domain Driven Design</td>
    <td class="tg-yw4l">2</td>
    <td class="tg-yw4l">14</td>
    <td class="tg-yw4l">341</td>
    <td class="tg-yw4l">1</td>
    <td class="tg-yw4l">1</td>
  </tr>
  <tr>
    <td class="tg-6k2t">Continuous Delivery</td>
    <td class="tg-6k2t">1</td>
    <td class="tg-6k2t">2</td>
    <td class="tg-6k2t">36</td>
    <td class="tg-6k2t">4</td>
    <td class="tg-6k2t">5</td>
  </tr>
</table>

<p>El propósito es tener búsquedas de tipo full text search mucho más rápidas, y en contra tiene que se tomará mucho más tiempo al agregar un documento porque se tienen que analizar todas las palabras, descartar aquellas palabras que semánticamente no agregan valor (a, al, el, si, etc.) y crear archivos nuevos para las palabras nuevas o actualizar los índices si ya existiera.</p>

<h4 id="cmolohacemosconredis">¿Cómo lo hacemos con redis?</h4>

<p>Por cada palabra creamos una lista ordenada siendo la palabra a buscar la clave de la lista. En la lista ordenada agregamos la posición del ranking que ocupará y una referencia o alias de la posición donde está.</p>

<pre><code>ZADD continuous 3 refDDD1
ZADD continuous 2 refDDD2
ZADD continuous 1 refCD1
</code></pre>

<blockquote>
  <p>Nota: estoy usando los comandos de Redis directamente para que puedas reproducirlo con el redis-cli.exe que está en el directorio de instalación del propio Redis. No quiero limitar el ejemplo a una plataforma y un solo driver.</p>
</blockquote>

<p>El resultado luego de procesar las entradas de continuous, integration y learning sería este</p>

<p><img src="https://ghost-azure3fff.azurewebsites.net/content/images/2016/12/Indice-inverso-1.PNG" alt=""></p>

<p>Para que se pueda hacer una búsqueda de tipo autocomplete, agregamos los <a href="https://es.wikipedia.org/wiki/N-grama">n-gram</a> necesarios. A modo de ejemplo, lo haré con la primer referencia</p>

<pre><code>ZADD c 1 refCD1
ZADD co 1 refCD1
ZADD con 1 refCD1
ZADD cont 1 refCD1
ZADD conti 1 refCD1
ZADD contin 1 refCD1
ZADD continu 1 refCD1
ZADD continuo 1 refCD1
ZADD continuou 1 refCD1
ZADD continuous 1 refCD1

ZADD c 2 refDD2
ZADD co 2 refDD2
ZADD con 2 refDD2
....
</code></pre>

<p>Luego cada alias se coloca como clave de una estructura hash con el resto de valores que me interesa que estén de la búsqueda, como documento, capítulo y página.</p>

<pre><code>HMSET refDDD1 documento “Domain Driven Design” capitulo 1 pagina 15 parrafo 4 posicion 1
HMSET refDDD2 documento “Domain Driven Design” capitulo 14 pagina 341 parrafo 1 posicion 1
HMSET refCD1 documento “Continuous Delivery” capitulo 2 pagina 36 parrafo 4 posicion 5
</code></pre>

<h4 id="yahoraabuscar">y ahora ¡¡a buscar!!</h4>

<p>Cuando ya tenemos todas las palabras con sus n-grams, tenemos que hacer el algoritmo de búsqueda. Pongamos el ejemplo que la persona escribe "con" como palabra clave.</p>

<pre><code>zrange con 0 4
</code></pre>

<p>Con este comando obtendremos las primeras cinco palabras (la posición de inicio y fin se incluyen) de la lista ordenada que tiene la clave "con". Como es una lista ordenado el resultado será:</p>

<pre><code>refCD1 
refDDD2
refDDD1
</code></pre>

<p>Tomamos estos valores y buscamos cada valor como un hash para obtener el nombre del documento</p>

<pre><code>HGET refCD1 documento
</code></pre>

<p>El resultado de este ultimo comando será</p>

<pre><code>Continuous Delivery
</code></pre>

<h3 id="performance">Performance</h3>

<p>Según la documentación de redis, el <a href="http://redis.io/commands/zrange">comando zrange</a> es una operación con un coste O(log(N)+M) donde N es la cantidad de registros que tiene la lista ordenada (es decir nuestro índice inverso) y M la cantidad de items que queremos que devuelva. </p>

<p>Mientras que el <a href="http://redis.io/commands/hget">comando HGET</a> tiene una complejidad O(1), es decir, tiene el mismo coste, sin importar cuan grande es el hash.</p>

<p>Si en el ejemplo tuviéramos que devolver no solo el nombre del documento, sino también el titulo, párrafo, etc.. tendríamos que usar el <a href="http://redis.io/commands/hgetall">comando HGETALL</a>, este comando tiene un coste de O(N), es decir, se incrementa cuanto mas propiedades del documento guardamos.</p>

<p>Si lo que te gustan son números de una aplicación en producción, te cuento... para un ranking de 150.000 posiciones, con un promedio de 16 palabras por posición que incluía el nombre del producto y palabras sinónimas, se hace un ZRANGE que trae 30 registros y luego 30 búsquedas de tipo HGET para obtener el título del producto, es decir  <strong>31 busquedas, y esta tardando 4 milisegundos</strong> en un i7 a 2.3 Ghz y no ocupo más de 400 Mb de RAM.</p>]]></content:encoded></item><item><title><![CDATA[[SPA] Introducción práctica a la programación funcional]]></title><description><![CDATA[<p><img src="https://ghost-azure3fff.azurewebsites.net/content/images/2016/12/senoCoseno.png" alt=""></p>

<p><span style="color:red">Actualizado el 03/Mayo/2017 - Se agrega el uso de <strong>colecciones immutables.</strong></span></p>

<h5 id="peroporquenecesitosaberprogramacinfuncional">pero ... ¿porque necesito saber programación funcional?</h5>

<p>Para tu vida profesional es muy bueno que manejes al menos tres tipos de lenguajes</p>

<ul>
<li>Orientado a Objetos (c#, java)</li>
<li>Dinámico (javascript, python)</li>
<li>Funcional (scala, f#, Haskeel)</li>
</ul>

<p>Porque detrás del lenguaje</p>]]></description><link>https://ghost-azure3fff.azurewebsites.net/introduccion-practica-a-la-programacion-funcional/</link><guid isPermaLink="false">f5348ab1-fc98-43b8-ad6a-63ec55bd09d0</guid><dc:creator><![CDATA[Daniel Mazzini Vidal]]></dc:creator><pubDate>Thu, 29 Dec 2016 21:36:17 GMT</pubDate><media:content url="http://blog.codecrafterslab.com/content/images/2016/12/senoCoseno.png" medium="image"/><content:encoded><![CDATA[<img src="http://blog.codecrafterslab.com/content/images/2016/12/senoCoseno.png" alt="[SPA] Introducción práctica a la programación funcional"><p><img src="https://ghost-azure3fff.azurewebsites.net/content/images/2016/12/senoCoseno.png" alt="[SPA] Introducción práctica a la programación funcional"></p>

<p><span style="color:red">Actualizado el 03/Mayo/2017 - Se agrega el uso de <strong>colecciones immutables.</strong></span></p>

<h5 id="peroporquenecesitosaberprogramacinfuncional">pero ... ¿porque necesito saber programación funcional?</h5>

<p>Para tu vida profesional es muy bueno que manejes al menos tres tipos de lenguajes</p>

<ul>
<li>Orientado a Objetos (c#, java)</li>
<li>Dinámico (javascript, python)</li>
<li>Funcional (scala, f#, Haskeel)</li>
</ul>

<p>Porque detrás del lenguaje en si, esta la forma en resolver el problema. Y eso es lo que más cuesta de la programación funcional. No hablo de que una es superior a la otra, sino que son dos paradigmas diferentes y que es bueno que las tengas en tu caja de herramientas mental.</p>

<h5 id="quenecesitassaberparaseguirleyendo">¿Que necesitas saber para seguir leyendo</h5>

<ul>
<li>Estar familiarizado con los conceptos (clase, objetos, polimorfismo y herencia) de programación orientada a objetos (POO en adelante) </li>
<li>Poder leer código c#</li>
</ul>

<h5 id="quenonecesitas">¿Que no necesitas?</h5>

<ul>
<li>Ser un experto en POO</li>
<li>Ser un maestro ninja de c#</li>
<li>Conocer algo de Haskeel, Scala, F# y otros lenguajes funcionales.</li>
</ul>

<h4 id="porquetengoqueconfiarenlasmates">¿porque tengo que confiar en las mates?</h4>

<p>En la wikipedia, si buscas programación funcional dice  </p>

<blockquote>
  <p>En ciencias de la computación, la programación funcional es un paradigma de programación declarativa basado en el uso de funciones matemáticas...</p>
</blockquote>

<p><em>¿que tienen las mates que me ayudaran a ser mejor programador? ¿porque tengo que confiar en ellas cuando casi arruinan mi adolescencia?</em> :)</p>

<p>Vamos a empezar con un ejemplo sencillo. Una función que me devuelve el iva de un importe dado. <br>
Primero definimos la función, en mates sera     <code>IVA(importe, porcentajeIva) = importe * (porcentajeIva/100)</code> mientras que en C# sera</p>

<pre><code class="language-cs">public decimal GetVat(double amount, double percentageVAT)  
{
   return (amount * (percentageVAT/100));
}
</code></pre>

<p>Ahora llamamos a la función definida con el valor 100 y 21</p>

<p>En mates <code>IVA(100, 21)</code> y en C# <code>var result = GetVat(100, 21);</code></p>

<p>De este ejemplo, vemos <strong>3 cosas en común que tienen las mates y esta función de c#</strong></p>

<ol>
<li>Solo se dedican a calcular el iva.  </li>
<li>La única dependencia que tienen es hacia las variables de entrada.  </li>
<li>Para un conjunto de valores de entrada solo le corresponde un valor de salida. No importa cuantas veces ponga 100 y 21, siempre me devolverá 21.</li>
</ol>

<h4 id="primerolasdesolid">Primero: La S de solid.</h4>

<p>En las mates, sumar solo suma. Puedes hacer que se combinen diferentes fórmulas, pero cada cual se dedica a lo suyo, tiene una sola responsabilidad, es decir son Single responsability, la S de <strong>S</strong>OLID</p>

<p>Ahora déjame poner una función típica de programación orientada a objetos, agregar un detalle de factura a una factura.</p>

<pre><code class="language-cs">void AddLine(InvoiceLine newInvoiceLine)  
{
    this.lines.Add(newInvoiceLine); // 1
    this.totalPrice += newInvoiceLine.Total; //2
}
</code></pre>

<p>Una de las propiedades de la programación orientada a objetos en la encapsulación, y esta función lo cumple muy bien porque oculta lo que sucede después de agregar. Pero como bien te haz dado cuenta, hace dos tareas, 1 - agrega un item y 2 - recalcula el total.</p>

<p>Lo primero que piensas es en separarlo en dos métodos</p>

<pre><code class="language-cs">void AddLine(InvoiceLine newInvoiceLine)  
{
  this.lines.add(newInvoiceLine);
}
void UpdateTotal(InvoiceLine newInvoiceLine)  
{
  this.totalPrice += newInvoiceLine.Total;
}
</code></pre>

<p>Pero el problema de esta solución es que generas una dependencia entre las funciones, teniendo que ser la segunda llamada luego de la primera para que el estado interno siga siendo coherente. Así que vamos a cambiar la clase para que el total sea una función en lugar de un resultado materializado.</p>

<pre><code class="language-cs">decimal GetTotal()  
{
   decimal total = 0;
   foreach(var line in this.lines)
   {
      total += line.Total;
   }
   return total;
}
</code></pre>

<p>Ahora podemos quitar variable <code>totalPrice</code> porque es reemplazada por la función <code>GetTotal</code>. </p>

<p>Podemos hacer la función GetTotal un poco diferente, que tengo un toque más funcional sin usar la variable interna total, para ello usaremos Linq.</p>

<pre><code class="language-cs">decimal GetTotal()  
{
   return this.details.Sum(item =&gt; item.Price);
}
</code></pre>

<p>O mejor aún, como una propiedad de solo lectura  </p>

<pre><code class="language-cs">public decimal Total  
{ 
       get { return Details.Sum(l =&gt; l.Total); } 
}
</code></pre>

<p>Ahora bien, apunta la primer lección de la programación funcional. <strong>Cuando refactorizas hacía programación funcional el estado interno de los objetos se reduce.</strong></p>

<p>Ahora tenemos el primer objetivo completo. Cada función tiene una única responsabilidad.</p>

<h4 id="segundosinefectoscolaterales">Segundo: Sin efectos colaterales.</h4>

<p>Cuando una función causa un cambio en algo fuera de su alcance, se llama side effect. Para ello la función tiene que recibir todo lo necesario para poder completar su responsabilidad por medio de parámetros. </p>

<p>Continuando con el ejemplo de la factura, imagina que tienes un método llamado cancelar.En el momento que cancelas la factura actualizas el saldo del cliente.</p>

<pre><code class="language-cs">private Customer customer;  
public void Cancel()  
{
    this.state = StateKind.canceled;
    this.customer.UpdateBalance(this.GetTotal());
}
</code></pre>

<p>Ahora pongamos un escenario donde el cliente tiene un saldo de 500 € y se cancela una factura de 100 €.</p>

<pre><code class="language-cs">customer.Balance; // 500€  
invoice.Cancel();  
customer.Balance // 600€  
</code></pre>

<p>Este es un ejemplo claro de side effect y de una función que no es matemática ya que no devuelve siempre el mismo resultado. ¿Como puedo hacer para que Cancelar sea no-side-effect?</p>

<p>Pues otra vez volvemos al tema de responsabilidad. No es la responsabilidad de cancelar la factura actualizar el saldo del cliente.</p>

<pre><code class="language-cs">public void Cancel()  
{
    this.state = StateKind.canceled;
}
</code></pre>

<p>La clase Cliente será la encargada de recibir una factura para cancelar y así actualizar su saldo. Después de verificar que la factura está cancelada, ajustará el saldo.</p>

<pre><code class="language-cs">public class Customer  
{
   void CancelInvoice(Invoice invoice)
   {
      if (invoice.State == StateKind.canceled;)
      {
         this.UpdateBalance(invoice.Total);
      }
   }
}
</code></pre>

<p>Con este diseño tenemos dos buenas noticias. <br>
1. El método Cancelar ya no necesita de la clase cliente. Puede que en otra parte de la clase factura si, pero este metodo ya no. Esto hace que el alcance (Bounded context) del objeto cliente para el sistema de facturación quede más limitado. <br>
2. En la clase cliente ahora el método ActualizarSaldo puede ser un método privado.</p>

<p>Volviendo al ejemplo anterior ahora tenemos que </p>

<pre><code class="language-cs">customer.Balance; // 500€  
invoice.Cancel();  
customer.Balance; // still is 500€  
customer.CancelInvoice(invoice);  
customer.Balance; //now is 600€  
</code></pre>

<p>Le hemos pasado la responsabilidad al cliente para que haga las dos llamadas en forma secuencial.</p>

<p>A pesar que este diseño es mejor, no es 100% funcional, porque el método Cancelar modifica una variable (estado) que no se recibe por parámetro.</p>

<h4 id="tecerofuncionespurasotransparenciareferencial">Tecero: funciones puras o transparencia referencial</h4>

<p>En mates, todas las funciones son referencialmente transparentes. El coseno de un ángulo de 90 grados sigue siendo 0, no importa cuantos años han pasado y cuantas veces lo repitas, siempre Cos(90) = 0. No importa como le pases la referencia Cos(89+1) o Cos(91-1), te dará lo mismo.</p>

<p>Volvamos a la función AddInvoice. Aunque es perfectamente valida en programación orientada a objetos, en términos de transparencia referencial no lo es porque cambia el estado interno al agregar un ítem a la lista.</p>

<pre><code class="language-cs">void AddLine(InvoiceLine newInvoiceLine)  
{
  this.lines.add(newInvoiceLine);
}
</code></pre>

<p>Para que esta función sea una función pura y no-side-effect necesitamos algunas cosas</p>

<p>1 - Poner un constructor donde le poner todas las propiedades del objeto. <br>
2 - La lista interna que esta como List, pasarla a ImmutableList. <br>
3 - Crear una funcion local que maneje los cambios en la coleccion, y si hay cambios que retorne una nueva instancia de la clase Invoice. <br>
4 - Agregar el item a la lista immutable. <br>
5 - Devolver una nueva instance de Invoice en lugar del void que hay ahora.</p>

<p>Pues manos a la obra. Primero paso. En los siguientes pasos necesitaremos crear una nueva instancia de Invoice con los nuevos valores. PAra ello necesitamos un constructor. En el constructor usaremos un IEnumerable para hacer la llamada al constructor mas facil, pero internamente lo convertimos a Immutable. </p>

<pre><code class="language-cs">public Invoice(IEnumerable&lt;InvoiceLine&gt; lines, StateKind state)  
{
    this.lines = lines.ToImmutableList();
    State = state;
}
</code></pre>

<p>Segundo paso.</p>

<pre><code class="language-cs">private ImmutableList&lt;InvoiceLine&gt; lines;  
public IEnumerable&lt;InvoiceLine&gt; Lines  
{
     get { return lines; } 
}
</code></pre>

<p>Tercer paso. Nuevo metodo local. Si la instancia de immutable list son diferentes, entonces hay que crear un nuevo objeto Invoice.</p>

<pre><code class="language-cs">private Invoice WithLines(IEnumerable&lt;InvoiceLine&gt; value)  
{
      return Object.ReferenceEquals(lines, value)
         ? this
         : new Invoice(value, State);
}
</code></pre>

<p>Cuarto y quinto paso. Devolver la nueva instancia.  </p>

<pre><code class="language-cs">public Invoice AddLine(InvoiceLine newOrderLine)  
{
    return WithLines(lines.Add(newOrderLine));
}
</code></pre>

<p>Que pasa con el metodo Cancel? Lo haremos immutable tambien.  </p>

<pre><code class="language-cs">public Invoice Cancel()  
{
    return (State == StateKind.canceled)
        ? this
        : new Invoice(Lines, StateKind.canceled);
}
</code></pre>

<p>Nota dos, <strong>cuando intentas hacer transparencia funcional cae por su propio peso la inmutabilidad de los datos</strong>. Es decir, la inmutabilidad es una consecuencia de la transparencia referencial que se usa en las mates.</p>

<p>Genial!! Ahora la clase invoice es immutable, todas sus propiedades son de solo lectura y los metodos devuelven una nueva instancia cuando realizan un cambio.</p>

<p>Ahora, hacemos lo mismo en la clase Customers.</p>

<pre><code class="language-cs">public class Customer  
{
    public Customer(decimal balance)
    {
        this.Balance = balance;
    }

    public decimal Balance { get; private set; }
    public Customer CancelInvoice(Invoice invoice)
    {
        return (invoice.State == StateKind.canceled)
            ? DiscountFromBalance(invoice.Total)
            : this;
    }

    private Customer DiscountFromBalance(decimal toTake)
    {
        return new Customer(Balance - toTake);
    }
}
</code></pre>

<p>Ahora veamos como se llama a estas funciones. Empezaremos suponiendo que la lista de detalles tiene 2 items, uno de <nobr>5 €</nobr> y otro de <nobr>15 €</nobr>, y el nuevo que queremos agregar tiene un precio de <nobr>20 €</nobr>.</p>

<pre><code class="language-cs">List&lt;InvoiceLine&gt; lines = new List&lt;InvoiceLine&gt;  
{
    new InvoiceLine(1, 5),
    new InvoiceLine(1, 15)
};
Invoice invoice = new Invoice(lines, StateKind.incomplete);  
var invoiceWithNewItem = invoice.AddLine(new InvoiceLine(1, 20));  
Console.WriteLine($"older total -&gt; {invoice.Total}");  
Console.WriteLine($"new total -&gt; {invoiceWithNewItem.Total}");  
</code></pre>

<p>Lo realmente importante aquí es que no importa cuantas veces ejecutes <code>invoice.Total;</code> siempre te devolverá 20 porque a) todos los metodos retornan una nueva instancia y b) porque el calculo del total no guarda ninguna información interna.</p>

<p>Ahora lo haremos con la clase customers. <br>
Entonces ahora lo vemos así</p>

<pre><code class="language-cs">Customer customer = new Customer(500);  
Console.WriteLine(customer.Balance);  
var invoiceCanceled = invoice.Cancel();  
var customerWithInvoiceCanceledProcessed = customer.CancelInvoice(invoiceCanceled); 

Console.WriteLine(customerWithInvoiceCanceledProcessed.Balance);  
</code></pre>

<h5 id="conclusionesyprximospasosdesafios">Conclusiones y próximos pasos / desafios</h5>

<p>Vimos una intro muy práctica de programación funcional -eso espero :) - y de cómo las mates nos pueden ayudar a programar por medio de funciones que:</p>

<ol>
<li>Solo tengan una responsabilidad.  </li>
<li>Sean no side effect.  </li>
<li>Usen transparencia referencial.</li>
</ol>

<p>Vimos como impacto esto en el diseño de nuestra aplicación. Y cómo nos ayuda a pensar diferente a la hora de resolver un problema.</p>

<p>Pero solo hemos rascado un poco, nos deja algunas preguntas que iremos viendo en otros artículos como: <br>
1 - No cabe duda que los datos inmutables son seguros, pero ¿qué pasa con el rendimiento? Si tengo que agregar 1000 item a la factura creará mil instancias diferentes de la lista para terminar usando sola la última. ¿Que pasa con la memoria? <br>
2 - Si en los métodos no se guarda estado que vaya mutando, ¿qué pasa con las variables de índice del comando for o con la variable de item en un foreach?</p>]]></content:encoded></item></channel></rss>