martedì 31 ottobre 2017

Javascript prototype function collection ------

Mustache ----- mai più stringhe concatenate in Javascript!!!!!

Per utilizzare la libreria Mustache.js sono necessari i seguenti passi:

1) installazione
     https://github.com/janl/mustache.js   in base al vostro ambiente, scegliete il sistema a voi consono.
2) creazione del template da posizionare magari, in una pagina html esistente:

Il template, che vi propongo è rappresentato da un blocco  <script> il cui type è "x-tmpl-mustache", ad esempio:

<script id="idDelTemplate" type="x-tmpl-mustache">
    <div class=' col-md-12 col-sm-12  col-xs-12  input-group' id='{{matricola}}'>
        <span class='form-control'>{{matricola}}</span>
        <span class='input-group-addon' onclick='removeBarcode("{{matricola}}")'> <i class='glyphicon glyphicon-trash'></i> </span>
    </div>
</script>

Successivamente, per utilizzarlo bastera:
 3) Wrappare il template con jquery :

                   var newItem = $('#idDelTemplate').html();

4) Testare se il template sia corretto :

                   Mustache.parse(newItem); // sembra sia optionale e utile in futuro... il progetto 

5) "Stampare" il template collegato al modello nel nostro contenitore:

              var printedModelTemplate= Mustache.render(template, objModel);
              $('body').html(printedModelTemplate);

dove il modello objModel = { matricola:1234123123};

Questa libreria è definita come logicLess, pertanto non si avranno disponibili le funzionalità "di alto livello" presenti in altri framework, vedi React (  che a prima vista pare estenda  Mustache ) o AngularJs/2

ad ogni modo, un minimo di rendering condizionato, il nostro Mustache lo offre, ad esempio supponendo di dover renderizzare un blocco html in base al verificarsi di una condizione,  Mustache offre la seguente sintassi:

{{#VAR}} Do Some Stuff{{/VAR}}
{{^VAR}} Not Do Some Stuff{{/VAR}}

Supponendo che nel modello sia contenuta una property VAR di tipo booleano, se VAR è true verrà stampato 
Do Some Stuff

altrimenti

Not Do Some Stuff

in termini pratici, i blocchi condizionali andranno posizionati dove si ritiene necessario :



objModel = { matricola:1234123123, VAR :true};

<script id="idDelTemplate" type="x-tmpl-mustache">
    <div class=' col-md-12 col-sm-12  col-xs-12  input-group' id='{{matricola}}'>
        <span class='form-control'>{{matricola}}</span>
        <span class='input-group-addon' onclick='removeBarcode("{{matricola}}")'> <i class='glyphicon glyphicon-trash'></i> </span>
    </div>
{{#VAR}}<span>Do Some Stuff</span>{{/VAR}}
{{^VAR}} <p>Not Do Some Stuff</p>{{/VAR}}
</script>





Libreria onesta, semplice e con poche pretese, sebbene l'efficacia sia indiscutibile.

ciao ciao
















martedì 17 ottobre 2017

Media Query!!! how it works ...for me :)

REMINDER :)

hi to all, .... that's a fast post

/* Higher Than  767px WORK*/
@media screen and (min-width: 767px) { body{ background-color: red;    }}
/* Higher Than  968px WORK*/
@media screen and (min-width: 968px) { body{ background-color: yellow; }}




/*Lower Than 768px Work*/
@media screen and (max-width: 768px) { body{ background-color: blue;    } }
/*Lower Than 567px Work*/
@media screen and (max-width: 567px) { body{ background-color: white;    } }


bye

sabato 8 luglio 2017

Java - Scarica file da domini con protocollo https - Download files from domains with https protocol











Italiano
Ciao a tutti,
il download di file, reperiti da domini o siti internet che utilizzano il protocollo https da Java, prevede l'importazione del certificato ssl all'interno di un keystore noto all'utente, in altre parole al keystore utilizzato di solito oppure in un nuovo keystore, e di un semplice programmino che scarica un elemento dopo l'altro, niente di trascendentale, ma per chi non ha familirità con certificati ssl, potrebbe un attimo rallentare l'attività.

procedendo per passi, cercando di snelline al massimo i processi vedremo come:
1) scaricare il certificato in base 64, per questo utilizzeremo google chrome, tab security --> view certificate --> download base 64
2) import del certificato attraverso l'utility keytool

3) applicazione java ( un semplice main va benissimo) e setting del keystore da utilizzare...

Passo 1

sul sito che contiene i file da scaricare, premere F12,

navigare fino al tab security e premere il pulsante "View Certificate"... seguire le indicazioni nelle immagini imm1, 2.. 3




image 1




imm2

imm3



successivamente, salvare il certificato, esempio downcert.cer



Passo 2

l'import del certificato nel keystore è una operazione molto semplice, accertatevi di avere nel path configurata una jdk o jre.... quindi una una shell eseguire :


 keytool -importcert -file downcert.cer -keystore keystore.jks -alias "AliasName"


(si suppone di essere posizionati nella cartella che contiene il certificato quindi il keystore, sebbene non sia corretto ma per comodità....)

Lanciato il comando verrà chiesto se:

il certificato sia attendibile, scrivere si e
la password del keystore, che verrà utilizzata nel codice al passo 3




English 

Hello to all,
Downloading files from domains or websites that use https from Java suggests importing the ssl certificate within a known keystore, in other words to the keystore usually used or in a new keystore , And a simple program that downloads an item after another, nothing transcendental, but for those who do not have familiarity with ssl certificates, it may be a moment to slow down the activity.

By proceeding in steps, trying to streamline the processes at maximum we will see how:
1) download certificate based 64, for this we will use google chrome, security tab -> view certificate -> 64 download base
2) Import the certificate through the keytool utility

3) java application (a simple main goes fine) and keystore setting to use ...

Step 1

On the site that contains the files to download, press F12,

Navigate to the security tab and press the "View Certificate" button ... follow the directions in the images imm1, 2 .. 3
(see previous images)
Then save the certificate.

Step 2

Importing the certificate in the keystore is a very simple operation, make sure you have a jdk or jre configured path ... so a shell execute:

  keytool -importcert -file downcert.cer -keystore keystore.jks -alias "AliasName"

(It is supposed to be placed in the folder that contains the certificate then the keystore, although it is not correct but for convenience ....)

Launched the command will ask if:
The certificate is trusted, write yes and
The keystore password, which will be used in the code at step 3





PASSO 3 / STEP 3



import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

public class main {
public static String[] links=new String[]{
"https://www.domainexample.com/resource1.jpg",
"https://www.domainexample.com/resource2.jpg",
"",
"",
"https://www.domainexample.com/resourceN.jpg" };

public static void main(String[] args) throws MalformedURLException, IOException{
String  ks= System.getProperty("user.home") + "/Desktop/keystore.jks";
String  folder= System.getProperty("user.home") + "/Desktop/downloadfoldercontainer";

new File(folder).mkdirs();
System.setProperty("javax.net.ssl.trustStore", ks);
System.setProperty("javax.net.ssl.trustStorePassword", "passwordStep2Passo2");

System.out.println("start:"+System.currentTimeMillis());
for(int i=0;i<links.length;i++){
try(InputStream in = new URL(links[i]).openStream()){
   Files.copy(in, Paths.get(folder+"/photo"+i+"image.jpg"));
}
}
System.out.println("stop:"+System.currentTimeMillis());
}
}



ciaoooo ragazzi :)

giovedì 24 novembre 2016

Parsing XML with C# And LINQ Microsoft Framework 4.0

Ciao a tutti,

come ci suggerisce il titolo del post, oggi illustrerò un modo comodo per leggere un file ( oppure una stringa ) contenente un messaggio XML per utilizzarlo all'interno del nostro programma......

Innanzitutto, prendiamo un file XML

<XML_NUMORDINE>
    <INFORMAZIONI>
        <CODICE_PREVENTIVO>2016O000000470</CODICE_PREVENTIVO>
        <DATA_AUTORIZZAZIONE>2016-12-01</DATA_AUTORIZZAZIONE>
        <NUMERO_ORDINE>1</NUMERO_ORDINE>
        <DATA_ORDINE>2016-12-01</DATA_ORDINE>
    </INFORMAZIONI>
    <INFORMAZIONI>
       ...
   </INFORMAZIONI>
    <INFORMAZIONI>
     ...
    </INFORMAZIONI>
    <INFORMAZIONI>
     ...
    </INFORMAZIONI>
</XML_NUMORDINE>


La necessità è, come si può immaginare, quella di ricreare un vettore o lista contenente tutti i campi racchiusi nel tag <INFORMAZIONI/>.

Per far ciò utilizzeremo Linq, innanzitutto una classe di comodo che rappresenta i dati :

      public class ItemsXmlTibcoPull {
            public ItemsXmlTibcoPull() {
                CODICE_PREVENTIVO = "";
                DATA_AUTORIZZAZIONE="";
                NUMERO_ORDINE = "";
                DATA_ORDINE = "";
            }

            public string DATA_ORDINE { get; set; }

            public string NUMERO_ORDINE { get; set; }

            public string DATA_AUTORIZZAZIONE { get; set; }

            public string CODICE_PREVENTIVO { get; set; }
        }

In seconda battuta un parser:

//" NOTA:questo parser prevede in ingresso il path del file xml o il suo contenuto"
public List<ItemsXmlTibcoPull> parser(String path, bool isPath = true){
            List<ItemsXmlTibcoPull> list = new List<ItemsXmlTibcoPull>();
            XElement e =null;
            if (isPath) e = XElement.Load(path);
            else e = XElement.Load(new System.IO.StringReader(path));
//wrappiamo il tag <INFORMAZIONI/>
           foreach (XElement level1Element in e.Elements("INFORMAZIONI"))
            {
                ItemsXmlTibcoPull item = new ItemsXmlTibcoPull();
//e per ogni elemento ne prendiamo il valore      
            foreach (XElement level2Element in level1Element.Elements("CODICE_PREVENTIVO"))
                {
                    item.CODICE_PREVENTIVO = level2Element.Value;
                 
                }
             
                foreach (XElement level2Element in level1Element.Elements("DATA_AUTORIZZAZIONE"))
                {
                    item.DATA_AUTORIZZAZIONE = level2Element.Value;
                 
                }
             
                foreach (XElement level2Element in level1Element.Elements("NUMERO_ORDINE"))
                {
                    item.NUMERO_ORDINE = level2Element.Value;
                  //qualora avessimo dovuto recuperare un attributo sulla property... name ad esempio
                  //result.AppendLine(level1Element.Attribute("name").Value);
                }
                //result.AppendLine(level1Element.Attribute("name").Value);
                foreach (XElement level2Element in level1Element.Elements("DATA_ORDINE"))
                {
                    item.DATA_ORDINE = level2Element.Value;
                   
                }
                list.Add(item);
            }
            return list;
}



ed il gioco è fatto!!!

Non commento ulteriormente perchè si commenta da solo .....

buon lavoro!

ciao


martedì 4 ottobre 2016

Trasformare un foglio Excel in query SQL

Buonasera, è da tanto che non scrivo........

stasera mi sono imbattuto in un foglio excel con soli 70000 record ma molto "sporco", al punto da invalidare il tool Excel To Mysql ( credo si chiami così)


in soldoni ho scritto uno script vba, configurabile, per creare, partendo dal "benedetto" foglio o sheet excel , tutte le query di insert necessare per caricarlo sul "beneamato" DBMS, in questo caso Mysql.





Buon Lavoro :)



PS1: in alto le variabili da configurare,.... i nomi spero siano intuitivi.
PS2: per utilizzarlo, abilitare il tab sviluppo e inserire un pulsante activex,... in posizione 1,1... alla fine dello script capirete perchè
PS3: anche gli interi vengono wrappati dagli apicetti..... miglioratelo :)

ciao


Private Sub CommandButton1_Click()
 
    Dim NOME_TABELLA As String
    NOME_TABELLA = "codifica"
    Dim COLONNAFINALE As Integer
    COLONNAFINALE = 10
    Dim PRIMARIGACONDATI As Long
    PRIMARIGACONDATI = 4
    Dim RIGA_INTESTAZIONI As Integer
    RIGA_INTESTAZIONI = 3
 
    Dim c As Long
    Dim intestazione As String
 
    intestazione = "insert into " & NOME_TABELLA & " ("
    c = 1
 
 
 
 
    While (Cells(RIGA_INTESTAZIONI, c) <> "")
     
        If (intestazione <> "insert into codifica (") And (c < (COLONNAFINALE + 1)) Then
            intestazione = intestazione & ","
        End If
        intestazione = intestazione & CStr(Cells(RIGA_INTESTAZIONI, c))
        c = c + 1
    Wend
    intestazione = intestazione & ") values ("
 
    Dim storei As String
    storei = intestazione
    Dim a As String
    a = "'"
    Dim b As String
    b = ","
 
 
 
    c = PRIMARIGACONDATI
 
    While (Cells(c, 1) <> "")
     
        Dim k As Integer
        k = 1
        Dim query As String
        query = storei
        While (k < (COLONNAFINALE + 1))
         
            If (query <> storei) Then
                query = query & b
            End If
         
            If (Cells(1, k) = "date") Then
                If (Cells(c, k) <> "") Then
                    query = query & a
                    query = query & Mid(Cells(c, k), 7, 4) & "-" & Mid(Cells(c, k), 4, 2) & "-" & Mid(Cells(c, k), 1, 2)
                    query = query & a
                   
                Else
                    query = query & "null"
                End If
           
            Else
                If (Cells(c, k) <> "") Then
                    query = query & a
                    query = query & Replace(CStr(Cells(c, k)), "'", "''")
                    query = query & a
                   
                Else
                    query = query & a & a
                End If
           
           
            End If
         
         
         
         
           
         
             
           
                 
               
            k = k + 1
        Wend
        query = query & ");"
     
        Cells(c, (COLONNAFINALE + 1)) = query
        DoEvents
     
        c = c + 1
     
        'posizione contatore
        Cells(1, 2) = c
    Wend
 
    MsgBox "fine"
 
 
 
End Sub


sabato 19 aprile 2014

TSQL SPLIT STRING INTO TABLE OF

TSQL SPLIT STRING INTO TABLE OF


Come splittare una stringa e trasformarla in una tabella in SQLSERVER


/*** Object: Function [dbo].[SplitString]  by:ALLDONE  Script Date: 19/04/2014 15:30:10 ***/
USE [prjYOURDB];
GO
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
CREATE FUNCTION [dbo].[SplitString]
(@input varchar(4000))
RETURNS @Result table
(
[valore] varchar(50) COLLATE Latin1_General_CI_AS NULL
)
WITH EXEC AS CALLER
AS
BEGIN
DECLARE @str VARCHAR(50)
      DECLARE @ind Int
      IF(@input is not null)
      BEGIN
            SET @ind = CharIndex(',',@input)
            WHILE @ind > 0
            BEGIN
                  SET @str = SUBSTRING(@input,1,@ind-1)
                  SET @input = SUBSTRING(@input,@ind+1,LEN(@input)-@ind)
                  INSERT INTO @Result values (@str)
                  SET @ind = CharIndex(',',@input)
            END
            SET @str = @input
            INSERT INTO @Result values (@str)
      END
      RETURN
END

GO




ciao ciao