sabato 10 gennaio 2015

Summernote - un editor WYSIWYG per Bootstrap

Oggi presento Summernote, un editor WYSIWYG per Bootstrap molto ben fatto. Tra le caratteristiche che lo rendono un ottimo prodotto (a mio parere) sono la facilità di installazione, la gestione del menù personalizzata e la possibilità di mostrare il sorgente del testo immesso.

Installazione

Si può installare direttamente dai sorgenti oppure tramite bower:
bower install summernote

Dipendenze

Utilizza ovviamente Bootstrap (e jQuery), assieme a font-awesome. Questo significa che è necessario includere i seguenti file (se non sono già inclusi nella pagina html):
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"></link>

<!-- include summernote css/js-->
<link href="summernote.css" rel="stylesheet"></link>
<script src="summernote.min.js"></script>

Inserimento del codice html e javascript

Un semplice <div> verrà trasformato in un editor Summernote con poche righe di codice javascript:
<div id="summernote">Hello Summernote</div>
<script>
$(document).ready(function() {
  $('#summernote').summernote();
});
</script>

Risultato


:-)

venerdì 9 gennaio 2015

Il meteo con Php e le API di Yahoo Weather

A tempo perso sto preparando una sveglia con Raspberry PI, che al momento di suonare si colleghi ad un sistema meteo, scarichi le informazioni e le pronunci tramite un sintetizzatore vocale.


Il primo passo è quindi quello di sviluppare un sistema che possa comprendere le condizioni meteo esterne. Ho trovato il servizio di API Yahoo Weather e me ne sono innamorato!
Di seguito è mostrato il codice dello script php che ho sviluppato: utilizza le funzioni curl per interfacciarsi con le API che rispondono in JSON, ho mappato i codici delle condizioni meteo in italiano (come da documentazione ufficiale) e ho scovato su stackoverflow una funzione per tradurre la direzione del vento da gradi alle classiche direzioni da rosa dei venti.
<?php

//Tradotto in php dall'originale 
//http://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
function degToCompass($num) {
    $val=floor(($num/22.5)+.5);
    $arr=["N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];
    return $arr[($val % 16)];
}


$condizioni = array(
"0"=>  "tornado",
"1"=>  "tempesta tropicale",
"2"=>  "uragano",
"3"=>  "forti temporali",
"4"=>  "temporali",
"5"=>  "pioggia mista a neve",
"6"=>  "pioggia mista a nevischio",
"7"=>  "neve mista a nevischio",
"8"=>  "pioviggine gelata",
"9"=>  "pioggerella",
"10"=>  "pioggia gelata",
"11"=>  "rovesci",
"12"=>  "rovesci",
"13"=>  "raffiche di neve",
"14"=>  "rovesci di neve leggeri",
"15"=>  "soffia neve",
"16"=>  "neve",
"17"=>  "grandinare",
"18"=>  "nevischio",
"19"=>  "polvere",
"20"=>  "nebbioso",
"21"=>  "foschia",
"22"=>  "foschia",
"23"=>  "ventoso",
"24"=>  "ventoso",
"25"=>  "freddo",
"26"=>    "nuvoloso",
"27"=>  "Sereno",
"28"=>  "Sereno",
"29"=>  "parzialmente nuvoloso",
"30"=>  "parzialmente nuvoloso",
"31"=>  "Sereno",
"32"=>  "soleggiato",
"33"=>  "Sereno",
"34"=>  "Sereno",
"35"=>  "pioggia mista e grandine",
"36"=>  "caldo",
"37"=>  "isolati temporali",
"38"=>  "temporali sparsi",
"39"=>  "temporali sparsi",
"40"=>  "Rovesci sparsi",
"41"=>  "tormenta di neve",
"42"=>  "rovesci di neve sparsi",
"43"=>  "tormenta di neve",
"44"=>  "parzialmente nuvoloso",
"45"=>  "rovesci temporaleschi",
"46"=>  "rovesci di neve",
"47"=>  "Temporali isolati",
"3200"=>  "non disponibile"
);

$BASE_URL = "http://query.yahooapis.com/v1/public/yql";

$yql_query = 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="Rimini, Italy") and u="c"';
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";

$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
$phpObj =  json_decode($json);
echo "\nMeteo per Rimini\n";
echo "----------------\n";
echo "Temperatura:      ";
echo $phpObj->query->results->channel->item->condition->temp."° C\n";
echo "Condizioni meteo: ";
echo $condizioni[$phpObj->query->results->channel->item->condition->code]."\n";
echo "Alba:             ";
echo $phpObj->query->results->channel->astronomy->sunrise."\n";
echo "Tramonto:         ";
echo $phpObj->query->results->channel->astronomy->sunset."\n";
echo "Umidità:          ";
echo $phpObj->query->results->channel->atmosphere->humidity."%\n";
echo "Pressione:        ";
echo $phpObj->query->results->channel->atmosphere->pressure." millibar\n";
echo "Previsioni:       ";
echo $condizioni[$phpObj->query->results->channel->item->forecast[0]->code];
echo ", t. max ".$phpObj->query->results->channel->item->forecast[0]->high;
echo "° C, t. min ".$phpObj->query->results->channel->item->forecast[0]->low." °C \n";

echo "Vento:            ";
echo $phpObj->query->results->channel->wind->speed." km/h ";
echo degToCompass($phpObj->query->results->channel->wind->direction)."\n";

giovedì 23 ottobre 2014

Estendere un disco LVM in Ubuntu Server 14.04 su Aruba Cloud

Una delle comodità dei server in cloud è la possibilità di aggiungere risorse man mano che servono. Mentre per CPU e Ram è sufficiente operare sul pannello di controllo dell'infrastruttura cloud, per l'aumento dello spazio disco bisogna eseguire qualche operazione in più. Per quale motivo? Perché lo spazio aggiuntivo, impostato dal configuratore, estende il disco fisicamente, ma non la partizione del sistema operativo. E senza queste operazioni ci si ritroverà un disco più grande, ma la partizione (attiva) del sistema operativo delle dimensioni precedenti!

Avendo alcuni server su Aruba Cloud, ho avuto la necessità di estendere il disco di una macchina virtuale con sistema operativo Ubuntu Server 14.04. Le istruzioni che mostrerò sono però valide anche per altri sistemi operativi linux, in particolare tutti quelli che supportano LVM.

Il primo passo sarà quello di spegnere la macchina virtuale ed agire sul pannello di controllo del cloud, aggiungendo spazio al disco principale. Nel mio caso sono voluto passare da 10 GB a 30 GB.
Si può ora riattivare la macchina virtuale. I passi sono semplici:

1. controllare mediante il comando parted l'effettivo spazio libero non allocato, digitandovi il comando print free ed analizzando il risultato. Ciò che ci interessa, è la riga "Free Space" di 21.5 GB (nel mio caso).
Per uscire, basta digitare "q".
root@CloudServer:~# parted
GNU Parted 2.3
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) print free                                                       
Model: VMware Virtual disk (scsi)
Disk /dev/sda: 32.2GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type      File system  Flags
        32.3kB  1049kB  1016kB            Free Space
 1      1049kB  256MB   255MB   primary   ext2         boot
        256MB   257MB   1048kB            Free Space
 2      257MB   10.7GB  10.5GB  extended
 5      257MB   10.7GB  10.5GB  logical                lvm
        10.7GB  32.2GB  21.5GB            Free Space
2. creare una nuova partizione con il comando
root@CloudServer:~# cfdisk
selezionare la riga dello spazio libero interessato, selezionare New, poi scegliere partizione Logica [Edit: un utente mi ha giustamente fatto notare che a questo punto, è necessario specificarne il formato, ossia 8E]. Infine selezionare Write per salvare le modifiche e infine Quit per uscire. Nel mio caso è stato necessario riavviare la macchina virtuale, quindi consiglio di farlo.

3. controllare l'avvenuta creazione della partizione, nel mio caso /dev/sda6
root@CloudServer:~# fdisk -l /dev/sda

Disk /dev/sda: 32.2 GB, 32212254720 bytes
255 heads, 63 sectors/track, 3916 cylinders, total 62914560 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000bc621

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048      499711      248832   83  Linux
/dev/sda2          501758    62914559    31206401    5  Extended
/dev/sda5          501760    20969471    10233856   8e  Linux LVM
/dev/sda6        20969535    62914559    20972512+  83  Linux

4. creare il volume fisico per sda6
root@CloudServer:~# pvcreate /dev/sda6
  Physical volume "/dev/sda6" successfully created

5. controllare i volumi fisici
root@CloudServer:~# pvdisplay
  --- Physical volume ---
  PV Name               /dev/sda5
  VG Name               vg
  PV Size               9.76 GiB / not usable 2.00 MiB
  Allocatable           yes (but full)
  PE Size               4.00 MiB
  Total PE              2498
  Free PE               0
  Allocated PE          2498
  PV UUID               5fDfUK-6RjG-nFMX-iNgM-44rF-7zz0-4JIr9Y
   
  "/dev/sda6" is a new physical volume of "20.00 GiB"
  --- NEW Physical volume ---
  PV Name               /dev/sda6
  VG Name               
  PV Size               20.00 GiB
  Allocatable           NO
  PE Size               0   
  Total PE              0
  Free PE               0
  Allocated PE          0
  PV UUID               hu4B6U-WDfx-zocW-13uX-BiwJ-2CoM-LHKhT9

6.  estendere il nuovo volume creato (sda6) dandogli lo stesso VG name del volume principale (sda5), nel mio caso vg
root@CloudServer:~# vgextend vg /dev/sda6
  Volume group "vg" successfully extended

7. controllare il nome del volume logico da estendere (nel mio caso /dev/vg/lv_root)
root@CloudServer:~# lvdisplay
  --- Logical volume ---
  LV Path                /dev/vg/lv_swap
  LV Name                lv_swap
  VG Name                vg
  LV UUID                CohmrO-3wcX-zLMV-exxT-gUDu-dAxo-vJhfD4
  LV Write Access        read/write
  LV Creation host, time ubuntu, 2014-07-18 10:33:32 +0200
  LV Status              available
  # open                 2
  LV Size                952.00 MiB
  Current LE             238
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           252:0
   
  --- Logical volume ---
  LV Path                /dev/vg/lv_root
  LV Name                lv_root
  VG Name                vg
  LV UUID                VxYaWt-nPDZ-zTos-Bhbk-0dyz-vlX4-5P06Qc
  LV Write Access        read/write
  LV Creation host, time ubuntu, 2014-07-18 10:33:44 +0200
  LV Status              available
  # open                 1
  LV Size                8.83 GiB
  Current LE             2260
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           252:1

8. estendere il volume logico
root@CloudServer:~# lvextend -l+100%FREE /dev/vg/lv_root
  Extending logical volume lv_root to 28.82 GiB
  Logical volume lv_root successfully resized

9. estendere il file system
root@CloudServer:~# resize2fs /dev/mapper/vg-lv_root 
resize2fs 1.42.9 (4-Feb-2014)
Filesystem at /dev/mapper/vg-lv_root is mounted on /; on-line resizing required
old_desc_blocks = 1, new_desc_blocks = 2
The filesystem on /dev/mapper/vg-lv_root is now 7556096 blocks long.

10. controllare lo spazio libero per assicurarsi che tutto sia andato a buon fine
root@CloudServer:~# df -h
Filesystem              Size  Used Avail Use% Mounted on
/dev/mapper/vg-lv_root   29G  1.7G   26G   6% /
none                    4.0K     0  4.0K   0% /sys/fs/cgroup
udev                    991M  4.0K  991M   1% /dev
tmpfs                   201M  532K  200M   1% /run
none                    5.0M     0  5.0M   0% /run/lock
none                   1002M     0 1002M   0% /run/shm
none                    100M     0  100M   0% /run/user
/dev/sda1               236M   39M  185M  18% /boot

Ho liberamente adattato le istruzioni che si possono trovare a questo indirizzo per farli funzionare correttamente con il template Ubuntu 14.04 di Aruba Cloud.

lunedì 7 aprile 2014

Includere un file html esterno con jQuery

Un semplice snippet per includere dinamicamente il contenuto html di un file esterno con jQuery:

 $('body').append($('<div></div>').load('file_esterno.html', function() {
   //Qui operazioni opzionali sull'html appena caricato
 });
:-)

giovedì 3 aprile 2014

jVectorMap - Mappe geografiche vettoriali in Javascript

jVectoMap è una utile libreria che permette di mostrare ed interagire con mappe geografiche vettoriali in Javascript. Il vantaggio di questo progetto, oltre a quello di essere open source, è che utilizza tecnologie native dei browser, quindi html, javascript, svg o vml, css, senza bisogno di plugin aggiuntivi. La sezione tutorial è molto ben fatta, ne consiglio una attenta lettura.
Qualche tempo fa ho avuto bisogno di sfruttare questa libreria per mostrare una mappa geografica della provenienza dei preventivi richiesti dagli utenti su un determinato sito web. Per ottimizzare tutto però ho voluto caricare i dati relativi al numero dei preventivi dei singoli stati in ajax con il formato JSON, vediamo come.
<div id="mappamondo-richieste" style="height:350px;width:100%;"></div>

$.ajax({
   type: "GET",
   url: 'http://api.example.com/stats/world/',
   dataType: "json",
   }).done(function( json_response ) { 
                            
     $('#mappamondo-richieste').vectorMap({
      map: 'world_mill_en',
      series: {
        regions: [{
          values: json_response.worldData,
          scale: ['#C8EEFF', '#0071A4'],
          normalizeFunction: 'polynomial'
        }]
      },
      onRegionLabelShow: function(e, el, code){
        if(!json_response.worldData[code]) json_response.worldData[code] = 0;
          el.html(el.html()+' ('+json_response.worldData[code]+')');
        }
      });
                            
    }).fail(function(jqXHR, textStatus) {
       console.log( "Request failed: " + textStatus + " " + jqXHR.status );
    });

La mappa utilizzata è la world_mill_en, ossia rappresenta l'intero globo terrestre. Le sigle delle nazioni seguono il formato a due lettere (ad esempio IT per Italia, FR per Francia, DE per Germania, ecc.).
L'url richiamata è una API (nel mio progetto scritta in Php) che risponde in formato JSON con una particolare struttura, ad esempio:
{
  "worldData":
  {
    "IT":"97",
    "US":"357"
  }
}
Il risultato finale non delude le mie aspettative :-)

sabato 29 marzo 2014

C# - Stampante direttamente con comandi nativi

Poco tempo fa ho avuto la necessità di stampare, con comandi nativi, su una stampante termica Zebra.
In passato mi era capitato di dover stampare con comandi nativi, ma su stampantine con porta seriale, quindi i comandi altro non erano che stringhe inviate in seriale.
In questo caso, invece, la stampante era collegata via usb e accessibile solo tramite drivers. Come fare? Incredibilmente la Microsoft ci viene in aiuto, e ha pubblicato una classe fantastica chiamata RawPrinterHelper che permette proprio di interagire direttamente con la stampante, a qualsiasi porta essa sia collegata (parallela, usb, seriale).
E' una classe statica, e per usarla è sufficiente eseguire il metodo SendStringToPrinter; il primo parametro sarà il nome della stampante, così come è definita nell'elenco stampanti di Windows, mentre il secondo parametro sarà la stringa di comandi da inviare direttamente alla stampante.
Ad esempio, in caso di una stampante Zebra:
RawPrinterHelper.SendStringToPrinter("Zebra GX420T", "^XA^FDESEMPIO^FS^XZ");
Di seguito posto anche il codice originale della classe, che si può trovare comunque a questo indirizzo: http://support.microsoft.com/kb/322091/it
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;

namespace TintoLavaApp
{
    public class RawPrinterHelper
    {
        // Structure and API declarions:
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        public class DOCINFOA
        {
            [MarshalAs(UnmanagedType.LPStr)]
            public string pDocName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pOutputFile;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pDataType;
        }
        [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

        [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool ClosePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

        [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool EndDocPrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool StartPagePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool EndPagePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

        // SendBytesToPrinter()
        // When the function is given a printer name and an unmanaged array
        // of bytes, the function sends those bytes to the print queue.
        // Returns true on success, false on failure.
        public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
        {
            Int32 dwError = 0, dwWritten = 0;
            IntPtr hPrinter = new IntPtr(0);
            DOCINFOA di = new DOCINFOA();
            bool bSuccess = false; // Assume failure unless you specifically succeed.

            di.pDocName = "My C#.NET RAW Document";
            di.pDataType = "RAW";

            // Open the printer.
            if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
            {
                // Start a document.
                if (StartDocPrinter(hPrinter, 1, di))
                {
                    // Start a page.
                    if (StartPagePrinter(hPrinter))
                    {
                        // Write your bytes.
                        bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                        EndPagePrinter(hPrinter);
                    }
                    EndDocPrinter(hPrinter);
                }
                ClosePrinter(hPrinter);
            }
            // If you did not succeed, GetLastError may give more information
            // about why not.
            if (bSuccess == false)
            {
                dwError = Marshal.GetLastWin32Error();
            }
            return bSuccess;
        }

        public static bool SendFileToPrinter(string szPrinterName, string szFileName)
        {
            // Open the file.
            FileStream fs = new FileStream(szFileName, FileMode.Open);
            // Create a BinaryReader on the file.
            BinaryReader br = new BinaryReader(fs);
            // Dim an array of bytes big enough to hold the file's contents.
            Byte[] bytes = new Byte[fs.Length];
            bool bSuccess = false;
            // Your unmanaged pointer.
            IntPtr pUnmanagedBytes = new IntPtr(0);
            int nLength;

            nLength = Convert.ToInt32(fs.Length);
            // Read the contents of the file into the array.
            bytes = br.ReadBytes(nLength);
            // Allocate some unmanaged memory for those bytes.
            pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
            // Copy the managed byte array into the unmanaged array.
            Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
            // Send the unmanaged bytes to the printer.
            bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
            // Free the unmanaged memory that you allocated earlier.
            Marshal.FreeCoTaskMem(pUnmanagedBytes);
            return bSuccess;
        }
        public static bool SendStringToPrinter(string szPrinterName, string szString)
        {
            IntPtr pBytes;
            Int32 dwCount;
            // How many characters are in the string?
            dwCount = szString.Length;
            // Assume that the printer is expecting ANSI text, and then convert
            // the string to ANSI text.
            pBytes = Marshal.StringToCoTaskMemAnsi(szString);
            // Send the converted ANSI string to the printer.
            SendBytesToPrinter(szPrinterName, pBytes, dwCount);
            Marshal.FreeCoTaskMem(pBytes);
            return true;
        }
    }
}

venerdì 28 marzo 2014

Chiamate cross thread su controlli winform - C#

Se si utilizzano thread durante lo sviluppo di applicazioni c#, si può avere la necessità di agire direttamente su controlli winform, ad esempio impostare il contenuto di una casella di testo in una finestra.
Se però si tenta di agire direttamente sul controllo, ad esempio da un oggetto backgroundWorker (che altro non è che un thread), a runtime viene generata una eccezione e il debugger si lamenta per una chiamata cross-thread non correttamente gestita.
Per fortuna la soluzione è alquanto semplice, racchiusa in poche righe di codice. Ad esempio, nel codice eseguito dal backgroundWorker, basterà inserire una chiamata invoke sul controllo con il quale intendiamo interagire.
Dato una textbox chiamata txt_esempio, il codice quindi sarà:

try
{
    txt_esempio.Invoke((MethodInvoker)delegate() { 
        txt_esempio.Text = "Testo modificato da backgroundWorker"; 
    });
}
catch (InvalidOperationException ioe) { }