Posts Tagged ‘c#’
12
lug

Hello,

a simple trick for you to get pixel color on a particular position of your screen with Windows GDI32.dll API libs.




First of all, you need to import Win32 API:

1
2
3
4
5
6
7
8
    [DllImport( "user32.dll" )]
    static extern IntPtr GetDC( IntPtr hwnd );

    [DllImport( "user32.dll" )]
    static extern Int32 ReleaseDC( IntPtr hwnd, IntPtr hdc );

    [DllImport( "gdi32.dll" )]
    static extern uint GetPixel( IntPtr hdc, int nXPos, int nYPos );

after that, create a function like this that return color in ARGB:

1
2
3
4
5
6
7
8
9
10
    static public System.Drawing.Color GetPixelColor( int x, int y )
    {
      IntPtr hdc = GetDC( IntPtr.Zero );
      uint pixel = GetPixel( hdc, x, y );
      ReleaseDC( IntPtr.Zero, hdc );
      Color color = Color.FromArgb( ( int )( pixel & 0x000000FF ),
                   ( int )( pixel & 0x0000FF00 ) >> 8,
                   ( int )( pixel & 0x00FF0000 ) >> 16 );
      return color;
    }

you can call it simply GetPixelColor( 0, 100 );

That’s all.

Rif: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , ,

07
giu

Un .sh come promemoria per macchine a 64bit, non si sa mai…

Versione OPTIMIZED:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Clean everything
if test -d optimized; then \
  cd optimized; \
  make distclean; \
  cd ..; \
fi;

# Do autoconf & friends
make -f Makefile.cvs
mkdir optimized
cd optimized

# Configure for debug build
export CXXFLAGS="-O2 -Wno-deprecated -Wall -g0"
../configure

# Build
make


Versione DEBUG:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Clean everything
if test -d debug; then \
  cd debug; \
  make distclean; \
  cd ..; \
fi;

# Do autoconf & friends
make -f Makefile.cvs
mkdir debug
cd debug

# Configure for debug build
export CXXFLAGS="-O0 -Wno-deprecated -g3"
../configure

# Build
make

yep.

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , ,

20
mag

Da una vecchia mail è venuto fuori questo codice…
…lo pubblico giusto per fare due risate.

Magic.cpp:

1
2
3
4
5
6
7
#include"Magic.h"

Dear Computer
Please print "Hello World!" string
Then wait until user pressed a key
Best Regards
Programmer

Magic.h:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<stdio .h>
#include<conio .h>

#define a )
#define Best ;
#define Computer (void){
#define Dear void main
#define key ;
#define pressed (
#define Please printf
#define Programmer
#define print (
#define Regards }
#define string );
#define Then int
#define until =
#define user getch
#define wait x

have fun!

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , ,

07
apr

Vediamo come creare con c# un file xml con nodi, attributi e testo in questo formato, con XmlDocument e XmlTextWriter:

1
2
3
4
5
6
7
8
 <city name="milano" thumbs="5">
   <thumb id="1" nid="11" t="0">
   <coord lat="45.464074" lon="9.190669"/>
   <pos b="90.115905" t="-0.5"/>
   <img />c:\test\img.png
   <desc>bla bla bla</desc>
 </thumb>
</city>

bene… facile facile con l’XMLTextWriter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  XmlTextWriter xw = new XmlTextWriter(fileName, Encoding.UTF8);

  xw.WriteStartDocument();

  /* nodo principale */
  xw.WriteStartElement("city");
  xw.WriteAttributeString("name", "milano");
  xw.WriteAttributeString("thumbs", "1");

  /* sotto nodi */
  xw.WriteStartElement("thumb");
  /* attributi */
  xw.WriteAttributeString("id", "1");
  xw.WriteAttributeString("nid", "111");
  xw.WriteAttributeString("t", "0");
  xw.WriteStartElement("coord");
  xw.WriteAttributeString("lat", "45");
  xw.WriteAttributeString("lon", "12");
  xw.WriteEndElement();
  xw.WriteStartElement("pos");
  xw.WriteAttributeString("b", "1.5");
  xw.WriteAttributeString("t", "-0.5");
  xw.WriteEndElement();

  xw.WriteStartElement("img");
  xw.WriteString("c:\test\img.png");
  xw.WriteEndElement();

  xw.WriteStartElement("desc");
  xw.WriteString("bla bla bla");
  xw.WriteEndElement();
  xw.WriteEndElement();
 
  /* chiusura tag */
  xw.WriteEndElement();
  xw.WriteEndDocument();
  xw.Close();

Ok! Il nostro file XML è pronto!!! Ricordati di aggiungere le librerie per l’xml tipo System.Xml.


Invece, per fare l’append di un sottonodo al file xml principale bisogna utilizzare XmlDocument.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
  XmlDocument xd = new XmlDocument();
  xd.Load(fName);

  /* con xpath punto al nodo interessato */
  XmlAttribute tmpN = xd.SelectSingleNode("city//@thumbs") as XmlAttribute;

  //XmlNode lastId = (xd.LastChild).LastChild.SelectSingleNode("@id");

  /* prendo i sottonodi e aggiungo valori */
  XmlElement thumbNode = xd.CreateElement("thumb");
  XmlAttribute thumbId = xd.CreateAttribute("id");
  thumbId.Value = "000";

  XmlAttribute thumbNId = xd.CreateAttribute("nid");
  thumbNId.Value = Request["nid"];

  XmlAttribute thumbT = xd.CreateAttribute("t");
  thumbT.Value = Request["type"];

  thumbNode.SetAttributeNode(thumbId);
  thumbNode.SetAttributeNode(thumbNId);
  thumbNode.SetAttributeNode(thumbT);

  XmlElement coordElem = xd.CreateElement("coord");
  XmlAttribute coordLat = xd.CreateAttribute("lat");
  coordLat.Value = Request["lat"];

  XmlAttribute coordLon = xd.CreateAttribute("lon");
  coordLon.Value = Request["lon"];

  coordElem.SetAttributeNode(coordLat);
  coordElem.SetAttributeNode(coordLon);

  XmlElement posElem = xd.CreateElement("pos");
  XmlAttribute posB = xd.CreateAttribute("b");
  posB.Value = "-4.3";

  XmlAttribute posT = xd.CreateAttribute("t");
  posT.Value = "123";

  posElem.SetAttributeNode(posB);
  posElem.SetAttributeNode(posT);

  XmlElement imgElem = xd.CreateElement("img");
  imgElem.InnerText = Request["img"];

  XmlElement descElem = xd.CreateElement("desc");
  descElem.InnerText = Request["et"];

  thumbNode.AppendChild(coordElem);
  thumbNode.AppendChild(posElem);
  thumbNode.AppendChild(imgElem);
  thumbNode.AppendChild(descElem);

  xd.DocumentElement.InsertAfter(thumbNode, xd.DocumentElement.LastChild);

  XmlNodeList xmlNL = xd.GetElementsByTagName("thumb");
  tmpN.Value = xmlNL.Count.ToString();

  FileStream fsxml = new FileStream(fName, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
  xd.Save(fsxml);
  fsxml.Close();

Meglio… adesso abbiamo aggiunto i sottonodi che ci interessano…
…ma ora? Ho sbagliato ad inserire un nodo, come si cancella???

Easy…
utilizziamo sempre XPATH perchè ci piace tanto!

1
2
3
4
5
6
7
8
9
10
  /* apro, cerco e cancello */
  XmlDocument d = new XmlDocument();
  d.Load("xmlfile.xml");
  XmlNode t = d.SelectSingleNode("city//thumb[@id='" + idValue + "']");
  t.ParentNode.RemoveChild(t);

  /* salvo */
  FileStream fsxml = new FileStream(local, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
  d.Save(fsxml);
  fsxml.Close();

oppure un delete / update del conteggio nodi ad esempio:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  XmlDocument d = new XmlDocument();
  d.Load("xmlfile.xml");
  XmlNode t = d.SelectSingleNode("city//thumb[@id='" + idValue + "']");
  t.ParentNode.RemoveChild(t);

  /* update valore del conteggio (esempio) */
  XmlNodeList xmlNL = d.GetElementsByTagName("thumb");
  int c = xmlNL.Count;
  XmlAttribute tmpN = d.SelectSingleNode("city//@thumbs") as XmlAttribute;
  tmpN.Value = c.ToString();

  FileStream fsxml = new FileStream(local, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
  d.Save(fsxml);
  fsxml.Close();

Un omaggio: MSDN

yep!

[ref -> albertopasca.it]

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , , , ,

16
mar

Last.fm?

Beh, direi che lo conoscono tutti ormai… ma come ben sapete da un pò di tempo è diventato a pagamento in “Italia”, si, in Italia, perchè in America, Germania e UK no!

E adesso???

Era il mio programma preferito di musica online…

…ma provate ad andare su “Strumenti -> Opzioni -> Connessione”.
C’è la voce proxy…

IT: Wikipedia
EN: Wikipedia

…possiamo quindi deviare la nostra connessione su un proxy server americano/inglese/tedesco ad esempio, no?

La cosa difficile qual’è?
Beh, trovare un proxy stabile o utilizzare dei programmini a tema tipo Hotspot Shield ad esempio!

Bene! Una volta installato ed eseguito provate ad aprire il vostro last.fm di fiducia… :D

Ah, vi danno fastidio i banner che escono sul browser quanto avete attivo Hotspot shield? Su Firefox c’è un plugin chiamato ADBLOCK Plus, installatelo e attivatelo e niente più banner fastidiosi!




E se volessi registrare le tracce audio?

E’ già spiegato qui (registrare con c#). Bisogna solo divertirsi un pò….

Per i pigri invece, c’è una bozza triste, piena di bug, funzionante malissimo.
Beh, funzionante con delle accortezze per il momento:

  • last.fm deve essere aperto, non ridotto a icona nella tray bar
  • la vostra periferica di registrazione attiva dovrebbe essere “Mix Wave” su XP almeno… su W7 non so quale sia… altrimenti con il microfono ovviamente si sente male.
  • se va giù la connessione… ahimè continua a registrare…
  • last.fm Recorder





    Tutto qui, è abbastanza stupido e facile.
    Nella lista appaiono le canzoni in scroll… al click su registra, viene registrata la prossima canzone!

    I file verranno registrati in formato .mp3 con il nome corretto sul vostro disco.
    Ah, beh… ovviamente si scarica da qui… eseguitelo nella cartella con gli altri file che trovate nello zip…

    Non lamentatevi!

    enjoy.

    [ref -> albertopasca.it]




    FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

    , , , , , , , , , ,

    15
    mar

    Metodo comodo comodo per ritornare da iso-8859-1 a utf-8 una stringa corretta:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    /* return utf8 chars from iso-8859-1 */
    string replaceSpecials(string special)
    {
      if (special.Contains("Ã"))
      {
        Encoding utf_8 = Encoding.UTF8;
        byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(special);
        special = utf_8.GetString(bytes);
      }

      return special;
    }

    I diversi caratteri interpretati da à verranno convertiti nel valore corretto in formato UTF-8.

    done.

    [ref -> albertopasca.it]

    FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

    , , , , , , , ,

    25
    feb

    Bene,

    abbiamo un file di log da 600Mb con 8.791.937 milioni di righe… in formato access.log.gz fatto in questo modo:

    1
    2
    3
    [...]
    IP.IP.IPP.IPP - - [14/Sep/2009:00:01:22 +0200] "GET /xml.php/getall?cmd=tile&format=jpeg&x=3777&y=5143&z=16&extra=2&ts=256&q=60&rdr=0&sito=test HTTP/1.1" 200 1713 "http://www.ilmiosito.it/call?v=373" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; GTB6)"
    [...]

    Cosa ci serve? L’url e i suoi parametri? Ok…

    Da shell possiamo usare un ZCAT per leggere il file zippato senza aprirlo e magari fare un redirect con meno righe, giusto per fare dei test:

    1
    $ zcat /tmp/access.log.gz | grep "&x=" | head -2500 > /tmp/small.log

    ora abbiamo un file più piccolo…

    1
    cut -d\" -f2 /tmp/small.log | cut -d\? -f2 | cut -d\  -f1 > CLEAR.log

    ora abbiamo un file contenente solo l’url da parsare! Già meglio vero?


    Adesso, con C# mettiamo su un parser senza perderci troppo tempo in shell e carichiamo il file!

    Può essere comodo usare le liste, in modo da salvare la coppia:

    (valore_che_serve),(quante_volte_si_ripete)

    1
          var CityList = new Dictionary<string , int>();

    e ovviamente salvare o incrementare i valori trovati:

    1
    2
    3
    4
           if ( ! CityList.ContainsKey( VALORE ))
                  CityList.Add(VALORE, 1);
            else
                  CityList[VALORE] = CityList[VALORE] + 1;

    così abbiamo per ogni chiave il suo numero di ripetizioni!

    Ma poi? Tutto disordinato?
    No, no, mettiamo un pò di ordine, magari salvando un file CSV separato da “;” con i valori ordinati dal più ripetuto al memo ripetuto…

    1
    2
    3
    4
    5
    6
    7
    8
    StreamWriter sw = new StreamWriter(@"Z:\alb\ordine.dat");

    foreach (KeyValuePair</string><string , int> item in CityList.OrderByDescending(key => key.Value))
    {
            sw.WriteLine(item.Key + ";" + item.Value);
            sw.Flush();
    }
    sw.close();

    Ah, per usare le Dictionary e il metodo OrderBy, sono necessarie queste due librerie:

    using System.Collections.Generic;
    using System.Linq;


    Bene, tutto qui!

    Adesso abbiamo un file CSV ordinato, con il nostro valore preferito (IP, la città, un url…) e quante volte viene ripetuto!
    Per ogni utilizzo!

    enjoy.

    [ref -> albertopasca.it]

    FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

    , , , , , , , , , , ,

    17
    feb

    Semplice semplice…

    Perchè mai usare lo StreamReader per contare le linee in un file di testo???

    1
    2
    3
    4
    5
    6
    7
    8
    StreamReader sr = new StreamReader(inputPath);
    int lines = 0;
    while (!sr.EndOfStream)
    {
      sr.ReadLine();
      lines++;
    }
    sr.close();


    …quanto si può facilmente fare un ReadAllLines?

    1
         int lines = File.ReadAllLines(@"iltuofile.log").Length;

    :)

    [ref -> albertopasca.it]

    FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

    , , , , , , , , , ,

    02
    feb

    Rieccoci…
    fresco fresco di mattinata!

    E’ uno dei metodi che permette di rimuovere un elemento da un array semplice.
    Esempio

    1
    string[] bigArray = new string[1234567];

    Per array molto grandi può risolvere mooooolti problemi:

    1
    2
    3
    4
    5
    6
        private string[] removeAt(int idx)
        {
          var tmp = new List<string>(fileEntries);
          tmp.RemoveAt(idx);
          return tmp.ToArray();
        }


    yep!

    RIF: stackoverflow.com

    [ref -> albertopasca.it]

    FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

    , , , , , , , ,

    21
    gen

    Magari può essere utile questo metodo facile facile che permette di dividere un qualsiasi file (binario o testo) in un numero di parti definite.

    SplitFileByByte
    In questo caso, non vengono considerate le righe ma i byte del file e viene splittato in base al numero richiesto.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    public void SplitFileByByte(string FileInputPath, string FolderOutputPath, int OutputFiles)
    {
      Byte[] byteSource = System.IO.File.ReadAllBytes(FileInputPath);
      FileInfo fiSource = new FileInfo(FileInputPath);
      int partSize = (int)Math.Ceiling((double)(fiSource.Length / OutputFiles));
      int fileOffset = 0;
      string currPartPath;
      FileStream fsPart;
      int sizeRemaining = (int)fiSource.Length;

      for (int i = 0; i < OutputFiles; i++)
      {
        currPartPath = FolderOutputPath + "\\" + fiSource.Name + "." + String.Format(@"{0:D4}", i) + ".part";
        if (!File.Exists(currPartPath))
        {
          fsPart = new FileStream(currPartPath, FileMode.CreateNew);
          sizeRemaining = (int)fiSource.Length - (partSize * i);
          if (sizeRemaining < partSize) partSize = sizeRemaining;

          while (true)
          {
            if (!(byteSource[partSize * 2] == 110 && byteSource[partSize * 2 + 1] == 62)) partSize++;
            else
            {
              partSize += 2;
              break;
            }
          }

          fsPart.Write(byteSource, fileOffset, partSize);
          fsPart.Close();
          fileOffset += partSize;
        }
      }
    }


    SplitFileByLine
    In questo caso essendo il file da splittare un xml con i blocchi da 3 righe ognuno, si considera questa caratteristica, pertanto il file viene diviso in blocchi di 3 righe ognuno aggiungendo poi header e footer.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    public void SplitFileByLine(int part, string outputFolder)
    {
      ArrayList lines = new ArrayList();
      StreamReader sr = null;
      try
      {
        sr = new StreamReader(outputFolder + "file.xml");
        while (!sr.EndOfStream) lines.Add(sr.ReadLine());

        /* rimuovo le intestazioni e il footer */
        lines.RemoveAt(0);
        lines.RemoveAt(0);
        lines.RemoveAt(lines.Count - 1);

        if (lines.Count >= 50)
        {
          StreamWriter sw = null;

          int div = lines.Count / part;
          /* preparo lo split in modo tale che le sezioni
           * non vengano mai divise. Sono 3 righe a blocco!
           */

          while (div % 3 != 0) div++;
          int cont = 0;

          for (int i = 0; i < part; i++)
          {
            int tot = 0;
            try
            {
              sw = new StreamWriter(outputFolder + "part_" + i + ".xml");

              /* intestazioni */
              sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
              sw.WriteLine("<locations>");

              tot = div * (i + 1);
              for (int k = cont; k < tot; k++) sw.WriteLine(lines[k]);
            } //try
            catch { }
            finally
            {
              cont = tot;
              /* scrivo footer */
              sw.WriteLine("</locations>");
              sw.Flush();
              sw.Close();
            } //finally
          } //for
        } //if
      } //try
      catch { }
    }

    enjoy!


    [ref -> albertopasca.it]

    FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

    , , , ,

    Switch to our mobile site