Ejemplo n.º 1
0
 private byte[] recCommFromServer()
 {
     byte[] res = new byte[commLength];
     try
     {
         serverStream.Read(res, 0, res.Length);
     }
     catch (Exception e) when(e is IOException || e is ObjectDisposedException)
     {
         //L'oggetto Socket sottostante è chiuso.
         //-oppure -
         //La classe NetworkStream è chiusa.
         //-oppure -
         //Si è verificato un errore durante la lettura dalla rete.
         MyLogger.print("Errore nella comunicazione con il server");
         MyLogger.debug(e.ToString());
         throw new SocketException();
         //mainWindow.
     }
     catch (Exception e)
     {
         MyLogger.debug(e.ToString());
         throw;
     }
     return(res);
 }
Ejemplo n.º 2
0
        /// <summary>
        /// delegato che inserisce il file in questione nell'appropriato hashSet
        /// </summary>
        /// <param name="fi"></param>
        private void checkFile(System.IO.FileInfo fi)
        {
            //MyLogger.add(fi.Name + "\n");
            RecordFile thisFile = new RecordFile(fi);

            if (fi.Length == 0)
            {
                return;
            }
            FileStatus status = dim.UpdateStatus(thisFile);

            switch (status)
            {
            case FileStatus.New:
                MyLogger.print("nuovo: ");
                newFiles.Add(thisFile);
                MyLogger.print(fi.Name + "\n");
                break;

            case FileStatus.Updated:
                MyLogger.print("aggiornato: ");
                updatedFiles.Add(thisFile);
                MyLogger.print(fi.Name + "\n");
                break;

            case FileStatus.Old:
                MyLogger.debug("vecchio: ");
                MyLogger.debug(fi.Name + "\n");
                //nothing to do
                break;
            }
            //MyLogger.add(thisFile);
        }
Ejemplo n.º 3
0
        public RecoverInfos askForRecoverInfo()
        {
            //todo: remove
            if (DEBUGGING_NO_SERVER)
            {
                RecoverInfos risdbg = new RecoverInfos();
                risdbg.addRawRecord("C:\\DATI\\poli\\Programmazione di Sistema\\progetto_client\\cartella_test\\1\r\n000000111111111100000000000000000000000000000000", 1);
                risdbg.addRawRecord("C:\\DATI\\poli\\Programmazione di Sistema\\progetto_client\\cartella_test\\2\r\n000000111111111100000000000000000000000000000000", 2);
                risdbg.addRawRecord("C:\\DATI\\poli\\Programmazione di Sistema\\progetto_client\\cartella_test\\3\r\n000000111111111100000000000000000000000000000000", 3);
                risdbg.addRawRecord("C:\\DATI\\poli\\Programmazione di Sistema\\progetto_client\\cartella_test\\4\r\n000000111111111100000000000000000000000000000000", 4);
                risdbg.addRawRecord("C:\\DATI\\poli\\Programmazione di Sistema\\progetto_client\\cartella_test\\5\r\n000000111111111100000000000000000000000000000000", 5);
                risdbg.addRawRecord("C:\\DATI\\poli\\Programmazione di Sistema\\progetto_client\\cartella_test\\6\r\n000000111111111100000000000000000000000000000000", 5);
                risdbg.addRawRecord("C:\\DATI\\poli\\Programmazione di Sistema\\progetto_client\\cartella_test\\7\r\n000000111111111100000000000000000000000000000000", 7);
                risdbg.addRawRecord("percorso\r\n000000111111111100000000000000000000000000000000", 1);
                return(risdbg);
            }
            //*/
            sendToServer(commRecoverInfo);
            waitForAck(commCmdAckFromServer);

            RecoverInfos ris = new RecoverInfos();

            try
            {
                //leggi numero di versioni
                int numVers = Convert.ToInt32(socketReadline());
                if (numVers == 0)
                {
                    MyLogger.debug("primo backup necessario");
                    return(null);
                }
                int nFile;
                int nVersCurr;
                //per ogni versione
                for (int bv = 1; bv <= numVers; bv++)
                {
                    nVersCurr = Convert.ToInt32(socketReadline());
                    if (nVersCurr != bv)
                    {
                        throw new Exception("nVersCurr != bv !!!!");
                    }
                    nFile = Convert.ToInt32(socketReadline());
                    //per ogni file
                    for (int f = 0; f < nFile; f++)
                    {
                        // [Percorso completo]\r\n[Ultima modifica -> 16byte][Hash -> 32char]\r\n
                        ris.addRawRecord(socketReadline() + "\r\n" + socketReadline(), bv);
                        sendToServer(commDataRec);
                    }
                }
            }
            catch (Exception e)
            {
                MyLogger.debug("errore in askForRecoverInfo\n");
                MyLogger.debug(e.ToString());
                throw;
            }
            return(ris);
        }
Ejemplo n.º 4
0
 private void deleteFile(string fileName)
 {
     try
     {
         File.Delete(fileName);
     }
     catch (Exception e)
     {
         MyLogger.print("impossibile eliminare il file errato: " + fileName);
         MyLogger.debug(e);
     }
 }
Ejemplo n.º 5
0
 private void setAutoSync(bool autoSync)
 {
     if (autoSync)
     {
         buttStartStopAutoSync.Content = AUTOSYNC_ON_TEXT;
         SyncTimer.Start();
         MyLogger.debug("AutoSync attivato\n");
     }
     else
     {
         buttStartStopAutoSync.Content = AUTOSYNC_OFF_TEXT;
         SyncTimer.Stop();
         MyLogger.debug("AutoSync disattivato\n");
     }
 }
Ejemplo n.º 6
0
 internal void syncNewFiles(RecordFile rf)
 {
     MyLogger.debug("newing file: " + rf.nameAndPath);
     sendToServer(commNewFile);
     waitForAck(commCmdAckFromServer);
     //aspettare eventuale MISS_BCK o BACKUPOK
     if (strRecCommFromServer() == commBackupOkFromServer)
     {
         SendWholeFileToServer(rf);
         MyLogger.debug("newed\n");
     }
     else
     {
         throw new AckErrorException();
     }
 }
Ejemplo n.º 7
0
 public bool setRootFolder(string rootFolder)
 {
     this.rootFolder = utf8.GetBytes(rootFolder);
     sendToServer(commSetFold_str);
     waitForAck(commCmdAckFromServer);
     sendToServer(this.rootFolder);
     if (strRecCommFromServer().Equals(commFolderOk)) //dovrebbe ricevere sempre FOLDEROK
     {
         MyLogger.debug("cartella selezionata correttamente.\n");
         return(true);
     }
     else
     {
         throw new UnknownServerResponseException();
     }
 }
Ejemplo n.º 8
0
        private void textBoxPorta_LostFocus(object sender, RoutedEventArgs e)
        {
            int res;

            try
            {
                res = Int32.Parse(textBoxPorta.Text);
            }
            catch (FormatException fe)
            {
                MyLogger.debug(fe.ToString());
                settings.setPorta(0); //valore non valido, con il get sarà restituito il default
                textBoxPorta.Text = settings.getPorta().ToString();
                return;
            }
            settings.setPorta(res);
        }
Ejemplo n.º 9
0
        private void textboxCycleTime_LostFocus(object sender, RoutedEventArgs e)
        {
            double num;
            string text = textboxCycleTime.Text;

            text = text.Replace(".", ",");
            if (!Double.TryParse(text, out num))
            {
                //errore
                settings.setCycleTime(0); //numero non valido, verrà restituito il DEFAULT al prossimo get
            }
            else
            {
                settings.setCycleTime(num);
            }
            applyScanInterval(settings.getCycleTime());
            MyLogger.debug("cycle time = " + settings.getCycleTime());
        }
Ejemplo n.º 10
0
 /// <summary>
 /// permette al logic thread di procedere
 /// </summary>
 public void MakeLogicThreadCycle()
 {
     System.Diagnostics.Debug.Assert(logicThread != null);
     if (!logicThread.IsAlive && !TerminateLogicThread)
     {
         try
         {
             logicThread.Start();
             return;
         }
         catch (System.Threading.ThreadStateException e)
         {
             MyLogger.debug(e.ToString());
         }
     }
     CycleNowEventSignaled = true;
     CycleNowEvent.Set(); //permette al logicThread di procedere.
 }
Ejemplo n.º 11
0
        internal void logout()
        {
            try
            {
                sendToServer(commLogout_str);
                MyLogger.print("disconnessione in corso...");

                //todo: da qui esce una socketexception da catchare
                waitForAck(commCmdAckFromServer);

                MyLogger.print("disconnessione effettuata\n");

                mainWindow.logged = false;
            }
            catch (Exception e)
            {
                MyLogger.debug(e);
            }
        }
Ejemplo n.º 12
0
        private void sendFileContent(RecordFile f)
        {
            try
            {
                const int bufsize      = 1024;
                var       buffer       = new byte[bufsize];
                int       actuallyRead = 0;

                long sizeFile       = 0;
                long totalBytesRead = 0;
                long nextStep       = 0;
                long stepSize;

                using (var s = File.OpenRead(f.nameAndPath))
                {
                    sizeFile = s.Length;
                    stepSize = (long)Math.Ceiling((double)sizeFile / 10);

                    while ((actuallyRead = s.Read(buffer, 0, bufsize)) > 0)
                    {
                        serverStream.Write(buffer, 0, actuallyRead);

                        //aggiorna progress bar
                        totalBytesRead += actuallyRead;
                        if (totalBytesRead > nextStep)
                        {
                            mainWindow.Dispatcher.BeginInvoke(mainWindow.DelSetProgressValues, sizeFile, 0, totalBytesRead);
                            nextStep += stepSize;
                        }
                    }
                }
                serverStream.Flush();
                mainWindow.Dispatcher.BeginInvoke(mainWindow.DelSetProgressValues, sizeFile, 0, sizeFile);
            }
            catch (Exception ex)
            {
                MyLogger.debug(ex.ToString());
                MyLogger.print("errore leggendo il file");
                throw;
            }
        }
Ejemplo n.º 13
0
        internal void syncDeletedFile(RecordFile rf)
        {
            MyLogger.debug("deleting file: " + rf.nameAndPath);
            sendToServer(commDeleteFile);
            waitForAck(commCmdAckFromServer);

            sendToServer(rf.nameAndPath);

            waitForAck(commInfoAckFromServer);
            MyLogger.debug("deleted\n");
            string res = strRecCommFromServer();

            if (res == commDELETED)
            {
                MyLogger.debug("deleted\n");
            }
            if (res == commNOTDEL)
            {
                MyLogger.debug("file inesistente.\n");
            }
        }
Ejemplo n.º 14
0
        public void sendInitialBackup(List <RecordFile> RecordFileList)
        {
            //TODO! nota: durante l'upload di un file grosso deve aspettare la fine dell'upload per chiudersi.
            //forse è meglio che il main process non faccia join ma si chiuda brutalmente?
            sendToServer(commInitialBackup);
            waitForAck(commCmdAckFromServer);

            MyLogger.print("Primo Backup in corso...");
            foreach (var rf in RecordFileList)
            {
                if (mainWindow.shouldIClose())
                {
                    throw new AbortLogicThreadException();
                }
                MyLogger.debug("invio del file " + rf.nameAndPath);
                sendToServer(commIBNextFile);
                SendWholeFileToServer(rf);
                MyLogger.debug("completato\n");
            }
            sendToServer(commIBSyncEnd);

            MyLogger.print("Primo Backup eseguito con successo\n");
        }
Ejemplo n.º 15
0
 private void newConnection()
 {
     MyLogger.print("Tentativo di connessione in corso...");
     try
     {
         //se già connesso abort del thread logico
         if (clientSocket.Connected)
         {
             throw new DoubleConnectionException();
         }
         //System.Net.IPAddress address = System.Net.IPAddress.Parse(serverIP);
         clientSocket.Connect(serverIP, serverPort);
         serverStream             = clientSocket.GetStream();
         serverStream.ReadTimeout = cnstReadTimeout;
     }
     catch (SocketException se)
     {
         MyLogger.print("Collegamento al server fallito\n");
         MyLogger.debug(se);
         throw;
     }
     MyLogger.print("Connesso\n");
 }
Ejemplo n.º 16
0
        public MainWindow()
        {
            //init UI
            InitializeComponent();

            //init delegates
            DelWriteLog               = writeInLog_RichTextBox;
            DelAskNewAccount          = askNewAccount;
            DelSetRecoverInfos        = setRecoverInfos;
            DelSetInterfaceLoggedMode = SetInterfaceLoggedMode;
            //DelYesNoQuestion = AskYesNoQuestion;
            DelShowOkMsg         = ShowOkMsg;
            DelSetProgressValues = SetProgressValues;

            //init accessory classes
            MyLogger.init(this);

            //load last settings from file
            LoadSettings();

            this.CycleNowEvent = new EventWaitHandle(false, EventResetMode.ManualReset);
            //this.CheckForAbortEvent = new EventWaitHandle(false, EventResetMode.ManualReset);

            SyncTimer           = new System.Windows.Threading.DispatcherTimer();
            SyncTimer.Tick     += new EventHandler(SyncTimerHandler);
            AbortTimer          = new System.Windows.Threading.DispatcherTimer();
            AbortTimer.Tick    += new EventHandler(AbortTimerHandler);
            AbortTimer.Interval = checkForAbortTimeSpan;

            ApplySettings();

            //imposta modalità interfaccia a not logged
            interfaceMode = interfaceMode_t.notLogged;

            //let's start
            MyLogger.debug("si comincia\n");
        }
Ejemplo n.º 17
0
 public static void debug(Object o)
 {
     MyLogger.debug(o.ToString());
 }
Ejemplo n.º 18
0
        /*-------------------------------------------------------------------------------------------------------------*/
        /*---logic Tread methods---------------------------------------------------------------------------------------*/
        /*-------------------------------------------------------------------------------------------------------------*/

        //siamo nel secondo thread, quello che non gestisce la interfaccia grafica.
        private void logicThreadStart()
        {
            MyLogger.debug("LogicThread starting");

            //setto interfaccia a busy
            this.Dispatcher.Invoke(DelSetInterfaceLoggedMode, interfaceMode_t.busy);

            try //catch errori non recuperabili per il thread
            {
                //reset richieste eventualmente vecchie per il logic thread
                resetLogicThreadNeeds();

                //avvio tmer per verifica abort signals periodicamente
                AbortTimer.Start();

                //inizializzo oggetto per connessione con server
                sm = new SessionManager(settings.getIP(), settings.getPorta(), this);
                //bool connected = false;

                //gestione del login
                sm.login(settings.getUser(), settings.getPassw());
                logged = true;

                //selezione cartella
                sm.setRootFolder(settings.getRootFolder());

                //attiva modalità logged nella UI
                this.Dispatcher.Invoke(DelSetInterfaceLoggedMode, interfaceMode_t.logged);

                //voglio iniziare con una sync
                needToSync = true;
                //needToSync = false;

                //è la prima sync per questa connessione
                firstConnSync = true;
                //firstConnSync = false;

                //ciclo finchè la connessione è attiva. si esce solo con eccezione o con chiusura thread logico (anch'essa un'eccezione).
                while (true)
                {
                    //verifica se deve sincronizzare
                    if (needToSync)
                    {
                        this.Dispatcher.Invoke(DelSetInterfaceLoggedMode, interfaceMode_t.busy);

                        MyLogger.print("AutoSync in corso\n");

                        // se è la prima sincronizzazione di questa connessione al server, crea DirMonitor
                        if (firstConnSync)
                        {
                            firstConnSync = false;
                            try
                            {
                                //init del dirMonitor
                                d = new DirMonitor(settings.getRootFolder(), sm);
                            }
                            catch (EmptyDirException)
                            {
                                //se arrivo qui è perchè c'è stata la prima connessione, l'initial backup di una cartella vuota e il download delle recoverInfo sempre vuote.
                                firstConnSync = true;
                            }
                        }
                        else //non è la prima connessione
                        {
                            //scandisco root folder
                            d.scanDir();

                            //sincronizzo tutte le modifiche
                            SyncAll();
                        }
                        needToSync = false;
                        this.Dispatcher.Invoke(DelSetInterfaceLoggedMode, interfaceMode_t.logged);
                        MyLogger.print("Completata\n");
                    }

                    //verifica se deve richiedere l'intero ultimo backup
                    if (needToRecoverWholeBackup)
                    {
                        this.Dispatcher.Invoke(DelSetInterfaceLoggedMode, interfaceMode_t.busy);

                        sm.AskForSelectedBackupVersion(RecoveringQuery);
                        needToRecoverWholeBackup = false;

                        this.Dispatcher.Invoke(DelSetInterfaceLoggedMode, interfaceMode_t.logged);
                    }

                    //verifica se deve richiedere dati per ripristino di file vecchi
                    if (needToAskRecoverInfo)
                    {
                        this.Dispatcher.Invoke(DelSetInterfaceLoggedMode, interfaceMode_t.busy);

                        var recInfos = sm.askForRecoverInfo();
                        needToAskRecoverInfo = false;

                        System.Diagnostics.Debug.Assert(recoverW != null);

                        recoverW.Dispatcher.Invoke(DelSetRecoverInfos, recInfos);

                        //qui l'interfaccia sarà resettata dalla recoverwindow che si chiude
                        //this.Dispatcher.Invoke(DelSetInterfaceLoggedMode, interfaceMode_t.logged);
                    }

                    //recupera recoverRecord
                    if (needToAskForFileToRecover)
                    {
                        this.Dispatcher.Invoke(DelSetInterfaceLoggedMode, interfaceMode_t.busy);

                        //recupera file
                        sm.askForSingleFile(fileToRecover);

                        needToAskForFileToRecover = false;

                        this.Dispatcher.Invoke(DelSetInterfaceLoggedMode, interfaceMode_t.logged);
                    }

                    WaitForSyncTime();
                }
            } //fine try esterno
            catch (SocketException)
            {
                MyLogger.print("impossibile connettersi. Server non ragiungibile");
            }
            catch (LoginFailedException)
            {
                MyLogger.print("errore nel login. Correggere dati di accesso o creare nuovo utente.");
            }
            catch (RootSetErrorException)
            {
                MyLogger.print("errore nella selezione della cartella. Correggere il path");
            }
            catch (AbortLogicThreadException)
            {
                MyLogger.print("Connessione Interrotta\n");
                MyLogger.debug("LogicThread closing per abort logic thread exception");
            }
            catch (DirectoryNotFoundException)
            {
                MyLogger.print("impossibile trovare directory specificata. Selezionarne un'altra");
            }
            catch (Exception e) //eccezione sconosciuta.
            {
                MyLogger.line();
                MyLogger.debug(e.Message);
                MyLogger.line();
                MyLogger.debug(e.ToString());
                MyLogger.debug("LogicThread closing");
                MyLogger.print("Errore sconosciuto. Chiusura connessione.\n");
            }


            this.Dispatcher.BeginInvoke(DelSetInterfaceLoggedMode, interfaceMode_t.notLogged);
            //if (!TerminateLogicThread)
            //{
            //    //setta la UI in modalità unlocked a meno che non sia TerminateLogicThread settata,
            //    //se no mainThread va in join e va in deadlock (non esegue invoke())
            //    this.Dispatcher.BeginInvoke(DelSetInterfaceLoggedMode, interfaceMode_t.notLogged);
            //}

            sm.closeConnection();
            //disattivo il timer che sblocca periodicamente il logicThread affinchè controlli se deve abortire
            AbortTimer.Stop();
            //this.Dispatcher.Invoke(DelSetInterfaceLoggedMode, interfaceMode_t.notLogged);
            logged = false;
            //TODO: ma quando chiudo recoverW diventa null?
            if (recoverW != null)
            {
                recoverW.Dispatcher.BeginInvoke(recoverW.DelCloseWindow);
            }
            return; //logic thread termina qui
        }
Ejemplo n.º 19
0
 public static void line()
 {
     MyLogger.debug("-----------------------------------------------\n");
 }
Ejemplo n.º 20
0
        internal void AskForSelectedBackupVersion(MainWindow.RecoveringQuery_st recQuery)
        {
            int version = recQuery.versionToRecover;

            MyLogger.print("Ripristino della versione " + recQuery.versionToRecover + "... ");
            sendToServer(commRecoverBackup);
            waitForAck(commCmdAckFromServer);
            //seleziono versione
            sendToServer(version.ToString());

            int fileCount = recQuery.recInfos.getVersionSpecificCount(version);

            try
            {
                for (int i = 0; i < fileCount; i++)
                {
                    //legge nome del file
                    string fileName = socketReadline();
                    string newPathAndName;
                    //definisce percorso dove salvare il file
                    if (recQuery.recoveringFolderPath != "")
                    {
                        //path da usare: quello specificato da utente
                        System.Diagnostics.Debug.Assert(fileName.Contains(mainWindow.settings.getRootFolder()));
                        //elimina la rootFolder. lascia // iniziale
                        string localPath = fileName.Substring(mainWindow.settings.getRootFolder().Length);
                        newPathAndName = recQuery.recoveringFolderPath.TrimEnd(Path.AltDirectorySeparatorChar) + localPath;
                    }
                    else
                    {
                        //path da usare: quello originale del file
                        newPathAndName = fileName;
                    }

                    //apro il file
                    FileStream fout;
                    Directory.CreateDirectory(System.IO.Path.GetDirectoryName(newPathAndName));
                    try
                    {
                        fout = new FileStream(newPathAndName, FileMode.Create);
                    }
                    catch (Exception e) when(e is IOException || e is UnauthorizedAccessException)
                    {
                        //se file è protetto ne crea una copia a fianco
                        newPathAndName += "-restoredCopy";
                        fout            = new FileStream(newPathAndName, FileMode.Create);
                        MyLogger.print("Impossibile ripristinare il file " + newPathAndName + ", salvo con suffisso \"restoredCopy\"\n");
                    }

                    System.DateTime LastModifyDate;
                    try
                    {
                        LastModifyDate = RecFileContent(newPathAndName, fout);
                        fout.Close();
                        FileInfo fi = new FileInfo(newPathAndName);
                        fi.LastWriteTime = LastModifyDate;
                    }
                    catch (CancelFileRequestException)
                    {
                        MyLogger.print("Operazione Annullata\n");
                        fout.Close();
                        deleteFile(newPathAndName);
                        return;
                    }
                    catch (IOException)
                    {
                        MyLogger.popup("Impossibile accedere al file " + newPathAndName + " Operazione interrotta.", MessageBoxImage.Error);
                        fout.Close();
                        deleteFile(newPathAndName);
                        return;
                    }
                }

                //mainWindow.Dispatcher.Invoke(mainWindow.DelShowOkMsg, "Ripristino versione completato!", MessageBoxImage.Information);
                //MyLogger.print("Ripristino versione " + recQuery.versionToRecover.ToString() + " riuscito");
                MyLogger.popup("Ripristino versione " + recQuery.versionToRecover.ToString() + " riuscito", MessageBoxImage.Information);
            }
            catch (Exception e)
            {
                MyLogger.print("ripristino fallito");
                mainWindow.Dispatcher.Invoke(mainWindow.DelShowOkMsg, "Ripristino versione fallita", MessageBoxImage.Error);
                MyLogger.debug(e.ToString());
                return;
            }
        }