jueves, 27 de noviembre de 2014

Algunas ideas del mundo del desarrollo de software

1._Pasa el tiempo muy rápido, tan rápido que en 2015 cumplo ocho años inmerso en la profesión de programador. Tras este tiempo he acumulado una serie de experiencias, algunas buenas y otras no tanto, junto a una serie de reflexiones que quiero poner en orden en este artículo. [más]

2._El programador es una especie más que intenta sobrevivir en este mundo. El medio en el que un programador nace, crece y muere cambia constantemente y a distintas velocidades. La selección natural se ha convertido en un proceso que en el caso de los programadores se agudiza y muchos individuos optan por la evolución como medio de supervivencia en un sector que sufre cataclismos de forma cíclica. [más]

miércoles, 26 de noviembre de 2014

Remove numbers in an array using gulp, mocha and expect

This last weekend, Iwas at codemotion 2014. In one  of the sessions, the speaker spoke about gulp. He said that it will be the standard tool for web developer. So I´ve done a little kata (remove a number in an array) with expect.js, mocha and gulp in javascript. The code lives here

The gulpfile.js

var gulp = require('gulp'),
   jshint = require('gulp-jshint'),
   mocha = require('gulp-mocha');

gulp.task('jshint', function(){
 gulp.src('source/*.js')
    jshint.reporter('default');
});

gulp.task('mocha', function () {
    gulp.src('test/*.js')
        .pipe(mocha({
            reporter: 'list'
        }))
        .on('error', function(err){
         console.log(err.message);
      this.emit('end'); 
        });
});

gulp.task('watch', function () {
 gulp.watch('source/*.js', function(){
  gulp.start('mocha');
 });
 gulp.watch('test/*.js', function(){
  gulp.start('mocha');
 });
});

gulp.task('default', function() {
    gulp.start('jshint', 'watch');
});


The System Under Test:

function removeElementInArray(number, vector){
 if(vector == []){
  return vector;
 }

 var result = [];
 var head;

 for(var position = 0; position < vector.length; position++){
  head = vector[position];
  if(head != number){
   result.push(head);
  }
 }
 return result;
}

exports.remove = removeElementInArray;

And the tests:

var sut = require("../source/sut.js"),
 expect = require("expect.js");

describe("Remove a number in an array thought functional way using TDD", function(){
  it("Given empty array then return empty array", function(){
    expect(sut.remove(2, [])).to.eql([]);
  });
  
  it("Given array with one element and 0 positions then return the same array", function(){
    expect(sut.remove(2, [2])).to.eql([]);
  });
  it("Given array with two numbers and number then return array without the number in the array", function(){
    expect(sut.remove(1, [1,2])).to.eql([2]);
  });
  it("Given array and positions then return rotated array without the number", function(){
    expect(sut.remove(3, [3,2,3,4])).to.eql([2,4]);
  });
});

domingo, 17 de agosto de 2014

Code Kata: Rotate An Array In javascript, with grunt and expect

the description
the code

My first Grunt file

I've investigating about automating (increase my productivity) writing tests and code in javascript, so I've found grunt

This little examples watch all .js files and validate with jshint

module.exports = function(grunt){
 grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),
  jshint:{
   all:['Gruntfile.js', './src/*.js', './spec/*.js']
  },
  watch:{
   files:'**/*.js',
   tasks:['jshint']
  }
 });

 grunt.loadNpmTasks('grunt-contrib-jshint');
 grunt.loadNpmTasks('grunt-contrib-watch');

 grunt.registerTask('test', ['jshint']);
};

my package.json
{
  "name": "grunt-test",
  "version": "0.0.1",
  "description": "simple grunt test",
  "keywords": [
    "grunt",
    "javascript",
    "jshint"
  ],
  "author": "Seymour Poler",
  "license": "GPL v2 or later",
  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-jshint": "~0.10.0",
    "grunt-contrib-watch": "~0.6.1"
  }
}

martes, 3 de junio de 2014

MSTest Assert.AreEqual with List

I was doing sms code kata with tdd. I´ve found the problem with the Assert.AreEqual with list<T>.
CollectionAssert.AreEquivalent(listOne, listTwo) is the solution source

jueves, 29 de mayo de 2014

Decorator Pattern in C#

I'm reading C# 3.0 Design Patterns by Judith Bisop
I've understood the decorator pattern.
Here is my little example for extending StreamReder class by password, when it reads.
using System;
using System.IO;

namespace Decorator
{
 public class LoginStream
 {
  private StreamReader  _streamReader;
  private string _password;

  public LoginStream (StreamReader streamReader, string password){
   _streamReader = streamReader;
   _password = password;
  }

  public string Read (string password){
   if (_password == password) {
    return _streamReader.ReadToEnd ();
   }
   throw new Exception ("Ivalid Password");
  }

 }
}
And the tests:
using System;
using System.IO;
using Decorator;
using NUnit.Framework;

namespace DecoratorTests
{
 [TestFixture()]
 public class Test
 {
  [Test()]
  public void LoginStream_Read_return_string_when_has_a_valid_password ()
  {
   var stream = new StreamReader("/home/luis/tmp/Prueba/Prueba.sln");
   var password = "password";
   var loginStream = new LoginStream(stream, password);

   var result = loginStream.Read(password);

   Assert.IsNotEmpty (result);
  }

  [Test()]
  [ExpectedException(typeof(Exception))]
  public void LoginStraeam_Read_return_exception_when_has_an_invalid_password ()
  {
   var stream = new StreamReader("path");
   var password = "password";
   var loginStream = new LoginStream(stream, password);

   loginStream.Read("invalidPassword");

   Assert.Fail ("Exception expected");
  }
 }
}


lunes, 31 de marzo de 2014

Export html Table to csv

Some time ago a collegue in Adesis, he needed to export html table to csv file.
I´ve dicovered some new music
So this the solution. It works
    



    
    
    
 
     
    
 Export To Excel



Titulo tabla
Nombre Provincia Telefono/Fax URL Marcas
Aistribuidor Nombre Tadrid 200 000 000 www.paginaweb.com marcas
Bistribuidor Nombre Sadrid 500 000 000 www.paginaweb.com marcas
Cistribuidor Nombre Sadrid 300 000 000 www.paginaweb.com marcas
Distribuidor Nombre Madrid 900 000 000 www.paginaweb.com marcas

viernes, 21 de marzo de 2014

martes, 28 de enero de 2014

Enable CORS in ASP.NET WebAPI

In Global.asax.cs file

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        HttpContext.Current.Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        HttpContext.Current.Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
        HttpContext.Current.Response.AppendHeader("Expires", "0"); // Proxies.

        HttpContext.Current.Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        HttpContext.Current.Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
        HttpContext.Current.Response.AppendHeader("Expires", "0"); // Proxies.

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Content-Range, Content-Disposition, Content-Description");
            HttpContext.Current.Response.End();
        }
    }
}

martes, 7 de enero de 2014

Start with nodejs server

var http = require('http');
var mime = require('mime');
var url = require('url');
var fs = require('fs');
var _base = './';

http.createServer(function(req, res){
 pathname = _base + req.url;
 console.log('path name: ' + pathname);
 fs.stat(pathname, function(err, stats){
  if(err){
   res.writeHead(404);
   res.write('Bad request 404 \n');
   res.end();
  }else if(stats.isFile()){
   var type = mime.lookup(pathname);
   console.log('mime-type: ' + type);
   res.setHeader('Content-Type', type);
   res.statusCode = 200;
   var file = fs.createReadStream(pathname);
   file.on('open', function(data){
    file.pipe(res);
   });
   file.on('error', function(err){
    console.log('error open the file: ' + err);
   })
  }else{
   res.writeHead(403);
   res.write('Directory access is forbidden');
   res.end();
  }
 });
}).listen(1024);
console.log('server running on 1024');

Playing with MongoDB & nodejs

I´m reading learning nodejs book and this is a little example. It´s not the best solution, but it´s a piece of code.
var mongodb = require('mongodb');

var bugRepository = module.exports = {};

var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true});
bugRepository.database = new mongodb.Db('bugdb', server);

var self = bugRepository;

bugRepository.insert  = function(bug){
 console.log('insert ' + bug);
 self.database.collection('bugs', function(err, collection){
  collection.insert([bug], {safe:true}, function(err, result){
   if(err){
    console.log('err saving new bug: ' + err);
    return;
   }
   if(result){
    console.log('result of saving bug: ' + result); 
   }
  });
 });
}

bugRepository.delete  = function(bug){
 console.log('delete id ' + bug.idBug);
 self.database.collection('bugs', function(err, collection){
  collection.remove({id: bug.idBug}, function(err, result){
   if(err){
    console.log('error removing one bug: ' + err);
    return;
   }
   if(result){
    console.log('deleting result: ' + result);
   }
   return result;
  });
 });
}

bugRepository.get  = function(bug){
 console.log('get id: ' + bug.idBug);
 self.database.collection('bugs', function(err, collection){
  collection.remove({id: bug.idBug}, function(err, doc){
   if(err){
    console.log('error removing one bug: ' + err);
    return;
   }
   if(doc){
    console.log('getting a bug' + doc);
    return doc;
   }
  });
 });
}

With the test:
var repository = require('./bugRepository');
var testCase  = require('nodeunit').testCase;

module.exports = testCase({
 //setup: function(){},
 //teardown: function(){},
 'Save simple bug': function(test){
  var bug = {};
  bug.idBug = 1;
  bug.name = 'bug name';
  bug.description = 'bug description';
  repository.insert(bug);
  var expected = repository.get(bug);
  test.equal(bug, expected);
  repository.delete(bug);
  test.done();
 }
});
for running the test:
nodejs /usr/local/bin/node_modules/nodeunit/bin/nodeunit bugRepository.test.js