n° 185
Maggio/Giugno 2013
Maggio 23, 2013, 11:53:47 pm *
Benvenuto! Accedi o registrati.
Hai dimenticato l'e-mail di attivazione?

Accesso con nome utente, password e durata della sessione
Notizia:
 
   Indice   Linux Windows Techassistance Gameassistance videogame hardware Aiuto Ricerca Agenda Downloads Accedi Registrati  

* Messaggi recenti
Messaggi recenti
Pagine: [1]   Vai giù
  Stampa  
Autore Discussione: Download Archivio da Web  (Letto 3053 volte)
0 utenti e 1 Utente non registrato stanno visualizzando questa discussione.
kello6372
Newbie
*

Karma: +0/-0
Scollegato Scollegato

Messaggi: 1


Mostra profilo E-mail
« inserita:: Febbraio 22, 2008, 04:53:54 pm »

Salve, sono nuovo del forum.
Sto realizzando un'applicazione che fornisce previsioni di ambi e terni per il gioco del lotto. Mi occorreva sapere come fare una sezione per aggiornare l'archivio delle estrazioni (locale all'applicazione) da web.
Registrato
jachetto
Administrator
Full Member
*****

Karma: +9/-0
Scollegato Scollegato

Messaggi: 494


Mostra profilo
« Risposta #1 inserita:: Febbraio 22, 2008, 05:01:39 pm »

gli fai fare un parsing di questa pagina http://www.lottomatica.it/lotto/estrazioni/estrazioni_ultime.html e salvi tutto in un db. Meglio ancora se trovi un servizio di rss bello e pronto.
Registrato
alex.75
invioattach
Full Member
***

Karma: +14/-3
Scollegato Scollegato

Messaggi: 341



Mostra profilo WWW
« Risposta #2 inserita:: Marzo 19, 2008, 10:28:53 pm »

Visto che io lo faccio in una applicazione stand-alone, ti posto il codice che uso (funzionante)
1) Download del file zip contenente .txt  storico estrazioni dal 1939 (completo)
2) Estrazione del file

Nota: la classe FileManager usa #ZipLib per unzippare il file:
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;

Devi pulire TANTO codice perchè uso una form separata (con thread separato ed eventi) per il download  ed una classe separata che si occupa di unzippare il file.
Però c'è tutto per ottenere il file di testo con tutte le estrazioni.

Codice:
        private String appPath = Application.StartupPath;
        public String ApplicationPath { get { return appPath; } }
        public const string DOWNLOAD_DIRECTORY = "Download";
        public const string ARCHIVE_FILE = "storico.txt";
        public const string WEB_ARCHIVE_URL = "http://www.lottomatica.it/lotto/sel/db/storico.zip";

/// questo è il click sul menu ///
private void menuExtractionsUpdateFromWeb_Click(object sender, EventArgs e)
        {
            string downloadDir = appPath + "\\Download";

            System.IO.Directory.CreateDirectory(downloadDir);

            string fileName = "storico_" + DateTime.Now.ToString(" yyyy-MM-dd HH-mm-ss") + ".zip";

            DreamSoft.Downloader.FormDownload formDownload = new DreamSoft.Downloader.FormDownload();
            formDownload.SetDownloadSource(WEB_ARCHIVE_URL);
            formDownload.SetDownloadDestination(downloadDir + "\\" + fileName);
            DialogResult result = formDownload.ShowDialog();


            string messageText = null;

            switch (result)
            {
                case DialogResult.OK:
                     break; 
                case DialogResult.Abort:
                    /// L10N
                    messageText = "Download interrotto";
                    break;
                case DialogResult.No:
                    /// L10N
                    messageText = "Error: " + formDownload.Error;
                    break;
                default:
                    /// L10N
                    messageText = "Risultato inaspettato";
                    break;
            }

           
            if(!String.IsNullOrEmpty(messageText))
            {
                MessageBox.Show(messageText);
                return;
            }

            FileManager fileManager = new FileManager();

            /// create db from data
            /// string filePathe = fileName
            if (!fileManager.UnzipFile(downloadDir + "\\" + fileName, downloadDir))
            {
                /// L10N
                MessageBox.Show("Errore nell'estrazione dell'archivio scaricato: " + fileManager.LastError);
                return;
            }

            /// TODO
            if(!fileManager.UpdateDatabase(dbManager ,downloadDir + "\\" + ARCHIVE_FILE))
            {
                /// L10N
                MessageBox.Show("Errore durante l'aggioranemnto del database: " + fileManager.LastError);
                return;
            }

        }

/// metodo chiamato in form download se in modalità "modale" (.showDialog()) ///
private void DownloadThread()
        {
            this.DialogResult = DialogResult.None;

            string from = txtDownloadFrom.Text;
            string to = txtDownloadTo.Text;
            string targetDirectory;

            bytesReaded = 0;
            totalBytesReaded = 0;

            HttpWebRequest request;
            HttpWebResponse response;
            Stream stream =  null;
            FileStream fs = null;

            /// L10N
            //InvokeShowInfo("Inizio download", Color.Black);

            ///InvokeSetProgress(0);

            try
            {
                request = (HttpWebRequest)WebRequest.Create(from);
                InvokeShowInfo(String.Format(General.DownloadOfFile_0, GetShortSourceString(from, 60)), Color.Blue);
                response = (HttpWebResponse)request.GetResponse();

                stream = response.GetResponseStream();

                downloadSize = response.ContentLength;
                if (downloadSize <= 0)
                {
                    error = General.NoDataRetrievedException;
                    throw new NoDataRetrievedException(error);   /// LCZ
                }
                downloadSizeString = FormatFileSizeString(downloadSize);
                InvokeSetProgress(0);

                /// TODO control destination directory
                //FileInfo fi = new FileInfo(to);

                targetDirectory = Path.GetDirectoryName(to);
                if (!Directory.Exists(targetDirectory))
                {
                    try
                    {
                        Directory.CreateDirectory(targetDirectory);
                    }
                    catch (Exception)
                    {
                        throw new Exception(Errors.TargetDirectoryCreationFail);
                    }
                }


                try
                {
                    fs = new FileStream(to, FileMode.Create); /// overwrite if exist

                }
                catch (Exception exc)
                {
                    throw new DestinationDirectoryNotExists(error);
                }

                //fs = new FileStream(to, FileMode.Create); /// overwrite if exist

                byte[] buffer = new byte[bufferSize];

                readings = 0;
                int readengSteps = 15;
                int speedForReadings = bufferSize * readengSteps;
                double elapsedSeconds;

                DateTime start = DateTime.Now;
                Stopwatch stopWatch = new Stopwatch();
                TimeSpan elapsedTime;
                stopWatch.Start();
                do
                {
                    if (threadDownload.ThreadState == System.Threading.ThreadState.AbortRequested)
                    {
                        break;
                    }
                    bytesReaded = stream.Read(buffer, 0, bufferSize);
                    //DateTime stop = DateTime.No
                    fs.Write(buffer, 0, bytesReaded);
                    readings++;
                    totalBytesReaded += bytesReaded;

                    if (readings == readengSteps)
                    {
                        //stopWatch.

                        //int ms = (DateTime.Now.Subtract(start)).Milliseconds;
                        elapsedTime = DateTime.Now.Subtract(start);
                        elapsedSeconds = elapsedTime.Seconds + elapsedTime.Milliseconds / 1000D;

                        speed = speedForReadings / elapsedSeconds;

                        //logManager.Write("Speed: " + speed, LogLevel.Info);

                        InvokeSetProgress(totalBytesReaded);

                        readings = 0;
                        start = DateTime.Now;
                    }

                }
                while (bytesReaded > 0);

                InvokeShowInfo(General.DownloadCompleted, Color.Green); /// LCZ

                this.DialogResult = DialogResult.OK;

            }
            catch (WebException exc)
            {
                error = General.Error + ": " + exc.Message;
                InvokeShowInfo(error, Color.Red);

                this.DialogResult = DialogResult.No;

            }
            catch (ApplicationException)
            {
                InvokeShowInfo(error, Color.Red);
                this.DialogResult = DialogResult.No;
            }
            //catch (NoDataRetrievedException exc)
            //{
            //    InvokeShowInfo(error, Color.Red);
            //    this.DialogResult = DialogResult.No;
            //}
            catch (ThreadAbortException exc)
            {
                //if (threadDownload.ThreadState == System.Threading.ThreadState.AbortRequested)
                //{
                //    break;
                //}
                this.DialogResult = DialogResult.Abort;
            }
            catch (Exception exc)
            {
                /// L10N
                error = General.Error + ": " + exc.Message;
                InvokeShowInfo(error, Color.Red);

                this.DialogResult = DialogResult.No;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }

            downloadRun = false;

            DownloadEnd();

        }


/// metodo della classe FileManager ///

        public bool UnzipFile(string fileName, string targetDirectory)
        {
            bool fileFound = false;

            using (ZipFile zipFile = new ZipFile(fileName))
            {

                for (int i = 0; i < zipFile.Count; ++i)
                {
                    ZipEntry e = zipFile[i];
                    if (e.IsFile)
                    {
                        /// extract the file
                        //FastZip fastZip = new FastZip(events);
                        FastZip fastZip = new FastZip();

                        //fastZip. CreateEmptyDirectories  = createEmptyDirs;
                        //fastZip.RestoreAttributesOnExtract = restoreAttributes;
                        //fastZip.RestoreDateTimeOnExtract = restoreDates;
                        //FastZip.Overwrite.Always
                        fastZip.ExtractZip(fileName, targetDirectory, "");

                        //FastZip.ConfirmOverwriteDelegate confirmOverwriteDelegate = new FastZip.ConfirmOverwriteDelegate(ConfirmOverwrite);                           
                        //fastZip.ExtractZip(fileName, targetDirectory,FastZip.Overwrite.Always, confirmOverwriteDelegate ,"" ,"" ,false);                           
                        fileFound = true;
                    }

                }

                if (!fileFound)
                {
                    /// L10N
                    error = "il file zip non contiene file";
                    return false;
                }

            }

            return true;
        }


NON chiedermi di pulire il codice perchè non ho voglia.

N.B. Attento alla "scansione" delle estrazioni dal file txt: le prime estrazioni avevano 6/7 ruote, poi 10 ed ora 11 con la ruota "Nazionale".

ciao
Alessandro
Registrato
Pagine: [1]   Vai su
  Stampa  
 
Vai a:  

Copyright © 2011 Edizioni Master SpA. p.iva : 02105820787

Tutti i diritti di proprietà letteraria e artistica riservati. - Privacy



Links to Page