示例#1
0
        private void lDeletedFileVersions_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DependencyObject obj = (DependencyObject)e.OriginalSource;

            while (obj != null && obj != lDeletedFiles)
            {
                if (obj.GetType() == typeof(System.Windows.Controls.ListViewItem))
                {
                    DateTime deletedVersion = ((FileVersionListViewItem)lDeletedFileVersions.SelectedItem).sTimestamp;

                    foreach (DateTime fv in deletedFileUtente.Items)
                    {
                        if (deletedVersion == fv)
                        {
                            deletedFileVersion = fv;
                        }
                    }

                    MessageBoxResult res = System.Windows.MessageBox.Show("Do you want to restore file \"" + deletedFileUtente.Nome + "\" with version " + deletedVersion + " ?", "Restore system", System.Windows.MessageBoxButton.YesNo);

                    if (res == MessageBoxResult.Yes)
                    {
                        try
                        {
                            if (Command.Logged == true)
                            {
                                ControlloModifiche.StopTimer();
                                Command getVersComm = new ComandoScaricaFile(deletedFileUtente.Nome, deletedFileUtente.Path, deletedFileVersion);
                                getVersComm.esegui();
                                this.GetDelFiles();
                                ControlloModifiche.Inizializza();
                            }
                            else
                            {
                                Command loginComm = new ComandoLogin(connectionSettings.readSetting("account", "username"), connectionSettings.readSetting("account", "password"));
                                loginComm.esegui();
                            }
                        }
                        catch (ServerException ex)
                        {
                            System.Windows.MessageBox.Show("Restore failed\n" + ex.Message, "Restoring system", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    break;
                }
                obj = VisualTreeHelper.GetParent(obj);
            }
        }
        private void openLogin()
        {
            if (!loggedin)
            {
                Login lw = new Login();
                bool loginAuthorized = false;
                bLogInOut.IsEnabled = false;
                lw.Username = connectionSettings.readSetting("account", "username");
                lw.Password = connectionSettings.readSetting("account", "password");
                while (!loginAuthorized)
                {
                    lw.showLogin();
                    try
                    {
                        switch (lw.waitResponse())
                        {
                            case Login.LoginResponse.CANCEL:

                                lw.Close();
                                bLogInOut.IsEnabled = true;
                                return;
                            case Login.LoginResponse.LOGIN:
                                Command loginComm = new ComandoLogin(lw.Username, lw.Password);
                                loginAuthorized = loginComm.esegui();

                                if (!loginAuthorized)
                                {
                                    lw.ErrorMessage = "Login failed";
                                }
                                break;
                            case Login.LoginResponse.REGISTER:
                                Command regComm = new ComandoRegistra(lw.Username, lw.Password);
                                loginAuthorized = regComm.esegui();

                                if (!loginAuthorized)
                                {
                                    lw.ErrorMessage = "Registration failed";
                                }
                                break;
                            default:
                                throw new Exception("Not implemented");
                        }
                        if (loginAuthorized)
                        {
                            lUsername.Content = lw.Username;
                            bLogInOut.Content = "Logout";
                            lw.Close();
                            connectionSettings.writeSetting("account", "username", lw.Username);
                            connectionSettings.writeSetting("account", "password", lw.Password);
                            bStart.IsEnabled = true;
                            loggedin = true;
                            updateStatus("Logged in");
                        }
                    }
                    catch (Exception ex) when (ex is ServerException || ex is ClientException)
                    {
                        lw.ErrorMessage = ex.Message;
                        loginAuthorized = false;
                    }
                }
                bLogInOut.IsEnabled = true;
            }
        }
        private void lFileVersions_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DependencyObject obj = (DependencyObject)e.OriginalSource;
            while (obj != null && obj != lDetails)
            {
                if (obj.GetType() == typeof(System.Windows.Controls.ListViewItem))
                {
                    DateTime selectedVersion = ((FileVersionListViewItem)lFileVersions.SelectedItem).sTimestamp;

                    foreach (DateTime fv in selectedFileUtente.Items)
                    {
                        if (selectedVersion == fv)
                            selectedFileVersion = fv;
                    }

                    MessageBoxResult res = System.Windows.MessageBox.Show("Do you want to restore file \"" + selectedFileUtente.Nome + "\" with version of " + selectedVersion + " ?", "Restore system", System.Windows.MessageBoxButton.YesNo);

                    if (res == MessageBoxResult.Yes)
                    {
                        try
                        {
                            if (Command.Logged == true)
                            {
                                ControlloModifiche.StopTimer();
                                Command getVersComm = new ComandoScaricaFile(selectedFileUtente.Nome, selectedFileUtente.Path, selectedFileVersion);
                                getVersComm.esegui();
                                this.GetFiles();
                                ControlloModifiche.Inizializza();
                            }
                            else
                            {
                                Command loginComm = new ComandoLogin(connectionSettings.readSetting("account", "username"), connectionSettings.readSetting("account", "password"));
                                loginComm.esegui();
                            }
                        }
                        catch (ServerException ex)
                        {
                            System.Windows.MessageBox.Show("Restore failed\n" + ex.Message, "Restoring system", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    break;
                }
                obj = VisualTreeHelper.GetParent(obj);
            }
        }
        /// <summary>
        /// Inizializza il controllo periodico del contenuto della cartella.
        /// Controlla anche le credenziali con il server testando il login.
        /// </summary>
        /// <exception cref="ServerException"></exception>
        /// <exception cref="ClientException"></exception>
        static public void Inizializza()
        {
            connectionSetting = new ConnectionSettings();
            user      = connectionSetting.readSetting("account", "username");
            pwd       = connectionSetting.readSetting("account", "password");
            base_path = connectionSetting.readSetting("account", "directory");
            interval  = Int32.Parse(connectionSetting.readSetting("connection", "syncTime"));

            if (!base_path.EndsWith("\\"))
            {
                base_path += "\\";
            }

            Properties.Settings.Default.user       = user;
            Properties.Settings.Default.pwd        = pwd;
            Properties.Settings.Default.base_path  = base_path;
            Properties.Settings.Default.intervallo = interval;
            Properties.Settings.Default.Save();

            if (!init)
            {
                if (user == null || pwd == null)
                {
                    throw new ClientException("Mancano le credenziali dell'utente. Fare il login.", ClientErrorCode.CredenzialiUtenteMancanti);
                }
                if (base_path == null)
                {
                    throw new ClientException("Il percorso di controllo non è specificato", ClientErrorCode.PercorsoNonSpecificato);
                }
                //Controllo se nome utente e password sono giusti
                if (!Command.Logged)
                {
                    try
                    {
                        ComandoLogin login = new ComandoLogin(user, pwd);
                        login.esegui();
                        ComandoEsci esci = new ComandoEsci();
                        esci.esegui();
                    }
                    catch (ServerException e) //Se il server non è disponibile l'eccezione non viene catturata...
                    {
                        switch (e.ErrorCode)
                        {
                        case ServerErrorCode.DatiErrati:
                            throw new ClientException("Le credenziali dell'utente sono errate. Rifare il login o registrarsi.", ClientErrorCode.CredenzialiUtenteErrate);

                        default:
                            throw;
                        }
                    }
                }
                //Controlla se il DB è ok

                //if (!DB_Table.DBEsiste)
                //throw new ClientException("Il database non esiste", ClientErrorCode.DatabaseNonPresente);

                /*
                 * string sha_db = DB_Table.HashDB;
                 * ComandoScaricaHashDB c = new ComandoScaricaHashDB();
                 * c.esegui();
                 * if(sha_db != c.hash)
                 * {
                 *  throw new ClientException("Il database è corrotto o non esiste");
                 * }
                 */
                //Imposta il timer per il controllo periodico
                checker           = new System.Timers.Timer(interval * 1000);
                checker.AutoReset = true;
                checker.Elapsed  += Checker_Elapsed;
                init = true;
                if (!Directory.Exists(base_path))
                {
                    throw new ClientException(Properties.Messaggi.CartellaNonEsistente, ClientErrorCode.CartellaNonEsistente);
                }
            }
            checker.Enabled = true;
        }
        public static void Check()
        {
            TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time");

            if (!Directory.Exists(base_path))
            {
                return;
            }
            if (Monitor.TryEnter(syncLock))
            {
                try {
                    List <string[]>   files       = FileUtenteList.exploreFileSystem(base_path);
                    List <FileUtente> toBeDeleted = new List <FileUtente>();
                    FileUtenteList    list        = FileUtenteList.getInstance();
                    string[]          entry       = new string[2];
                    string            path_completo;
                    Command           c;

                    CultureInfo it = new CultureInfo("it-IT");
                    Thread.CurrentThread.CurrentCulture = it;

                    if (!init)
                    {
                        throw new ClientException("La classe per il controllo delle modifiche non è inizializzata correttamente.", ClientErrorCode.ControlloNonInizializzato);
                    }
                    if (!Command.Logged)
                    {
                        ComandoLogin login = new ComandoLogin(user, pwd);
                        login.esegui();
                    }
                    FileInfo finfo;
                    foreach (FileUtente fu in list)
                    {
                        //Check if still exists, and if its modified
                        entry[0] = fu.Nome;
                        entry[1] = fu.Path;
                        int index;
                        if ((index = files.FindIndex(fTest => (fTest[0] == entry[0] && fTest[1] == entry[1]))) >= 0)
                        {
                            files.RemoveAt(index);
                            //Il file selezionato esiste ancora...
                            path_completo = base_path + entry[1] + Path.DirectorySeparatorChar + entry[0];
                            finfo         = new FileInfo(path_completo);

                            DateTime dt   = TimeZoneInfo.ConvertTime(finfo.LastWriteTime, TimeZoneInfo.Local, tz);
                            DateTime tMod = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
                            tMod = tMod.AddTicks(-(tMod.Ticks % TimeSpan.TicksPerSecond));

                            if (DateTime.Compare(tMod, fu.TempoModifica) != 0)
                            {
                                FileStream fs      = File.Open(path_completo, FileMode.Open);
                                string     new_sha = FileUtente.CalcolaSHA256(fs);
                                if (new_sha != fu.SHA256Contenuto)
                                {
                                    fu.aggiornaDati((int)finfo.Length, finfo.LastWriteTime);
                                    c = new ComandoAggiornaContenutoFile(entry[0], entry[1], (int)finfo.Length,
                                                                         finfo.LastWriteTime, fu.SHA256Contenuto);
                                    c.esegui();
                                }
                            }
                        }
                        else
                        {
                            toBeDeleted.Add(fu);
                        }
                    }
                    //Cancelliamo
                    foreach (FileUtente _fu in toBeDeleted)
                    {
                        list.Delete(_fu.Id);
                        c = new ComandoEliminaFile(_fu.Nome, _fu.Path);
                        c.esegui();
                    }

                    //file nuovi
                    FileUtente fu2;
                    foreach (string[] n_file in files)
                    {
                        string file_path_completo = base_path + n_file[1] + Path.DirectorySeparatorChar + n_file[0];
                        finfo = new FileInfo(file_path_completo);
                        DateTime dt   = TimeZoneInfo.ConvertTime(finfo.LastWriteTime, TimeZoneInfo.Local, tz);
                        DateTime tMod = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
                        tMod = tMod.AddTicks(-(tMod.Ticks % TimeSpan.TicksPerSecond));
                        dt   = TimeZoneInfo.ConvertTime(finfo.CreationTime, TimeZoneInfo.Local, tz);
                        DateTime tCre = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
                        tCre = tCre.AddTicks(-(tCre.Ticks % TimeSpan.TicksPerSecond));

                        FileStream fs      = File.Open(file_path_completo, FileMode.Open);
                        string     new_sha = FileUtente.CalcolaSHA256(fs);
                        fu2 = list.CreaNuovo(n_file[0], n_file[1], tCre, tMod, (int)finfo.Length, new_sha);
                        c   = new ComandoNuovoFile(n_file[0], n_file[1], (int)finfo.Length, tCre, tMod, new_sha);
                        c.esegui();
                    }
                }
                finally
                {
                    if (Monitor.IsEntered(syncLock))
                    {
                        Monitor.Exit(syncLock);
                    }
                }
            }
        }
示例#6
0
        private void openLogin()
        {
            if (!loggedin)
            {
                Login lw = new Login();
                bool  loginAuthorized = false;
                bLogInOut.IsEnabled = false;
                lw.Username         = connectionSettings.readSetting("account", "username");
                lw.Password         = connectionSettings.readSetting("account", "password");
                while (!loginAuthorized)
                {
                    lw.showLogin();
                    try
                    {
                        switch (lw.waitResponse())
                        {
                        case Login.LoginResponse.CANCEL:

                            lw.Close();
                            bLogInOut.IsEnabled = true;
                            return;

                        case Login.LoginResponse.LOGIN:
                            Command loginComm = new ComandoLogin(lw.Username, lw.Password);
                            loginAuthorized = loginComm.esegui();

                            if (!loginAuthorized)
                            {
                                lw.ErrorMessage = "Login failed";
                            }
                            break;

                        case Login.LoginResponse.REGISTER:
                            Command regComm = new ComandoRegistra(lw.Username, lw.Password);
                            loginAuthorized = regComm.esegui();

                            if (!loginAuthorized)
                            {
                                lw.ErrorMessage = "Registration failed";
                            }
                            break;

                        default:
                            throw new Exception("Not implemented");
                        }
                        if (loginAuthorized)
                        {
                            lUsername.Content = lw.Username;
                            bLogInOut.Content = "Logout";
                            lw.Close();
                            connectionSettings.writeSetting("account", "username", lw.Username);
                            connectionSettings.writeSetting("account", "password", lw.Password);
                            bStart.IsEnabled = true;
                            loggedin         = true;
                            updateStatus("Logged in");
                        }
                    }
                    catch (Exception ex) when(ex is ServerException || ex is ClientException)
                    {
                        lw.ErrorMessage = ex.Message;
                        loginAuthorized = false;
                    }
                }
                bLogInOut.IsEnabled = true;
            }
        }
        public static void Check()
        {
            TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time");

            if (!Directory.Exists(base_path))
                return;
            if(Monitor.TryEnter(syncLock))
            {
                try {
                    List<string[]> files = FileUtenteList.exploreFileSystem(base_path);
                    List<FileUtente> toBeDeleted = new List<FileUtente>();
                    FileUtenteList list = FileUtenteList.getInstance();
                    string[] entry = new string[2];
                    string path_completo;
                    Command c;

                    CultureInfo it = new CultureInfo("it-IT");
                    Thread.CurrentThread.CurrentCulture = it;

                    if (!init)
                    {
                        throw new ClientException("La classe per il controllo delle modifiche non è inizializzata correttamente.", ClientErrorCode.ControlloNonInizializzato);
                    }
                    if (!Command.Logged)
                    {
                        ComandoLogin login = new ComandoLogin(user, pwd);
                        login.esegui();
                    }
                    FileInfo finfo;
                    foreach (FileUtente fu in list)
                    {
                        //Check if still exists, and if its modified
                        entry[0] = fu.Nome;
                        entry[1] = fu.Path;
                        int index;
                        if ((index = files.FindIndex(fTest => (fTest[0] == entry[0] && fTest[1] == entry[1]))) >= 0)
                        {
                            files.RemoveAt(index);
                            //Il file selezionato esiste ancora...
                            path_completo = base_path + entry[1] + Path.DirectorySeparatorChar + entry[0];
                            finfo = new FileInfo(path_completo);

                            DateTime dt = TimeZoneInfo.ConvertTime(finfo.LastWriteTime, TimeZoneInfo.Local, tz);
                            DateTime tMod = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
                            tMod = tMod.AddTicks(-(tMod.Ticks % TimeSpan.TicksPerSecond));

                            if (DateTime.Compare(tMod, fu.TempoModifica) != 0)
                            {
                                FileStream fs = File.Open(path_completo, FileMode.Open);
                                string new_sha = FileUtente.CalcolaSHA256(fs);
                                if (new_sha != fu.SHA256Contenuto)
                                {
                                    fu.aggiornaDati((int)finfo.Length, finfo.LastWriteTime);
                                    c = new ComandoAggiornaContenutoFile(entry[0], entry[1], (int)finfo.Length,
                                        finfo.LastWriteTime, fu.SHA256Contenuto);
                                    c.esegui();
                                }
                            }
                        }
                        else
                        {
                            toBeDeleted.Add(fu);
                        }
                    }
                    //Cancelliamo
                    foreach (FileUtente _fu in toBeDeleted)
                    {
                        list.Delete(_fu.Id);
                        c = new ComandoEliminaFile(_fu.Nome, _fu.Path);
                        c.esegui();
                    }

                    //file nuovi
                    FileUtente fu2;
                    foreach (string[] n_file in files)
                    {
                        string file_path_completo = base_path + n_file[1] + Path.DirectorySeparatorChar + n_file[0];
                        finfo = new FileInfo(file_path_completo);
                        DateTime dt = TimeZoneInfo.ConvertTime(finfo.LastWriteTime, TimeZoneInfo.Local, tz);
                        DateTime tMod = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
                        tMod = tMod.AddTicks(-(tMod.Ticks % TimeSpan.TicksPerSecond));
                        dt = TimeZoneInfo.ConvertTime(finfo.CreationTime, TimeZoneInfo.Local, tz);
                        DateTime tCre = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
                        tCre = tCre.AddTicks(-(tCre.Ticks % TimeSpan.TicksPerSecond));

                        FileStream fs = File.Open(file_path_completo, FileMode.Open);
                        string new_sha = FileUtente.CalcolaSHA256(fs);
                        fu2 = list.CreaNuovo(n_file[0], n_file[1], tCre, tMod, (int)finfo.Length, new_sha);
                        c = new ComandoNuovoFile(n_file[0], n_file[1], (int)finfo.Length, tCre, tMod, new_sha);
                        c.esegui();
                    }
                }
                finally
                {
                    if (Monitor.IsEntered(syncLock))
                        Monitor.Exit(syncLock);
                }
            }
        }
        /// <summary>
        /// Inizializza il controllo periodico del contenuto della cartella.
        /// Controlla anche le credenziali con il server testando il login.
        /// </summary>
        /// <exception cref="ServerException"></exception>
        /// <exception cref="ClientException"></exception>
        public static void Inizializza()
        {
            connectionSetting = new ConnectionSettings();
            user = connectionSetting.readSetting("account", "username");
            pwd = connectionSetting.readSetting("account", "password");
            base_path = connectionSetting.readSetting("account", "directory");
            interval = Int32.Parse(connectionSetting.readSetting("connection", "syncTime"));

            if (!base_path.EndsWith("\\"))
            {
                base_path += "\\";
            }

            Properties.Settings.Default.user = user;
            Properties.Settings.Default.pwd = pwd;
            Properties.Settings.Default.base_path = base_path;
            Properties.Settings.Default.intervallo = interval;
            Properties.Settings.Default.Save();

            if (!init)
            {
                if (user == null || pwd == null)
                    throw new ClientException("Mancano le credenziali dell'utente. Fare il login.", ClientErrorCode.CredenzialiUtenteMancanti);
                if (base_path == null)
                    throw new ClientException("Il percorso di controllo non è specificato", ClientErrorCode.PercorsoNonSpecificato);
                //Controllo se nome utente e password sono giusti
                if (!Command.Logged)
                {
                    try
                    {
                        ComandoLogin login = new ComandoLogin(user, pwd);
                        login.esegui();
                        ComandoEsci esci = new ComandoEsci();
                        esci.esegui();
                    }
                    catch (ServerException e) //Se il server non è disponibile l'eccezione non viene catturata...
                    {
                        switch (e.ErrorCode)
                        {
                            case ServerErrorCode.DatiErrati:
                                throw new ClientException("Le credenziali dell'utente sono errate. Rifare il login o registrarsi.", ClientErrorCode.CredenzialiUtenteErrate);
                            default:
                                throw;
                        }
                    }
                }
                //Controlla se il DB è ok

                //if (!DB_Table.DBEsiste)
                    //throw new ClientException("Il database non esiste", ClientErrorCode.DatabaseNonPresente);
                /*
                string sha_db = DB_Table.HashDB;
                ComandoScaricaHashDB c = new ComandoScaricaHashDB();
                c.esegui();
                if(sha_db != c.hash)
                {
                    throw new ClientException("Il database è corrotto o non esiste");
                }
                */
                //Imposta il timer per il controllo periodico
                checker = new System.Timers.Timer(interval * 1000);
                checker.AutoReset = true;
                checker.Elapsed += Checker_Elapsed;
                init = true;
                if (!Directory.Exists(base_path))
                    throw new ClientException(Properties.Messaggi.CartellaNonEsistente, ClientErrorCode.CartellaNonEsistente);
            }
            checker.Enabled = true;
        }