public DirectoryStatus(DirectoryStatus other) { this.files = new Dictionary<String, DirectoryFile>(other.files); this.folderPath = String.Copy(other.folderPath); this.username = String.Copy(other.username); this.creationTime = DateTime.Now; }
/// <summary> /// Produce the set difference of this and src. Produce this - src /// </summary> /// <param name="src">the set from which extract items</param> /// <returns>the difference set</returns> public Dictionary<String, DirectoryFile> getDifference(DirectoryStatus src) { Dictionary<String, DirectoryFile> d1 = this.files; Dictionary<String, DirectoryFile> d2 = src.files; Dictionary<String, DirectoryFile> d3; //d1 - d2 d3 = d1.Where(x => !d2.ContainsKey(x.Key)).ToDictionary(x => x.Key, x => x.Value); return d3; }
private void dir_grid_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (!client.resumeSession()) { connected = false; if (watcher != null) watcher.Stop(); client.TcpClient.Close(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "Your session is expired, please login again"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); return; } if (this.dir_grid.SelectedItem == null) return; var item = this.dir_grid.SelectedItem as SnapshotItem; DirectoryStatus dir = new DirectoryStatus(); CurrentDirectory = item.Path; RootDirectory = item.Path; CurrentSnapshotTime = Convert.ToDateTime(item.LastModificationTime); if (client.getSnapshotInfo(dir, CurrentDirectory, CurrentSnapshotTime) < 0) { connected = false; client.TcpClient.Close(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "A Network Error occurred, please try later"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } else this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new FillGrid(fill_snap_grid), dir); }
public static DirectoryStatus getLastSnapshot(String directory, String username) { DirectoryStatus ds = new DirectoryStatus(); ds.FolderPath = directory; ds.Username = username; directory += "\\"; String date = null; try { using (var con = new SQLiteConnection(connectionString)) { con.Open(); if (!cleanDBsnapshots(con, username, directory)) return ds; using (var cmd = con.CreateCommand()) { int len = directory.Length; cmd.CommandText = @"select max(creation_time) from snapshots where" + " user_id = @id and substr(path,1," + len + ") = @dir;"; cmd.Parameters.AddWithValue("@id", username); cmd.Parameters.AddWithValue("@dir", directory); object val = cmd.ExecuteScalar(); date = (val == System.DBNull.Value) ? null : (String)val; } if (date != null) { ds.CreationTime = DateTime.ParseExact(date, date_format, null); using (var cmd = con.CreateCommand()) { int len = directory.Length; cmd.CommandText = @"select * from snapshots where user_id = @id" + " and substr(path,1," + len + ") = @dir" + " and creation_time = @date;"; cmd.Parameters.AddWithValue("@id", username); cmd.Parameters.AddWithValue("@dir", directory); cmd.Parameters.AddWithValue("@date", date); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { DirectoryFile file = new DirectoryFile(); file.UserId = username; file.Directory = (Boolean)reader["directory"]; file.Path = (String)reader["path"]; file.Path = file.Path.Substring(0,file.Path.LastIndexOf('\\')); file.Filename = (String)reader["filename"]; file.Deleted = (Boolean)reader["deleted"]; file.LastModificationTime = (DateTime)reader["last_mod_time"]; if (!file.Directory) { file.Id = (Int64)reader["file_id"]; file.Checksum = (String)reader["checksum"]; } file.Fullname = Path.Combine(file.Path, file.Filename); ds.Files.Add(file.Fullname, file); } } } } } return ds; } catch (SQLiteException) { return null; } }
public static bool insertUnchanged(SQLiteConnection conn, DirectoryStatus oldStatus, DirectoryStatus newStatus) { try { if (oldStatus.Equals(newStatus)) return true; Dictionary<String, DirectoryFile> diff; diff = oldStatus.Files.Where(x => !newStatus.Files.ContainsKey(x.Key)).ToDictionary(x => x.Key, x => x.Value); foreach (var item in diff) { using (SQLiteCommand cmd = conn.CreateCommand()) { DirectoryFile file = item.Value; if (file.Directory) { cmd.CommandText = @"insert into snapshots (user_id,creation_time,path,filename,last_mod_time,directory,deleted) values" + " (@user, @creationTime, @path, @filename, @lastModTime, @directory, @deleted);"; cmd.Parameters.AddWithValue("@user", newStatus.Username); cmd.Parameters.AddWithValue("@creationTime", newStatus.CreationTime.ToString(date_format)); cmd.Parameters.AddWithValue("@path", file.Path + "\\"); cmd.Parameters.AddWithValue("@filename", file.Filename); cmd.Parameters.AddWithValue("@lastModTime", file.LastModificationTime.ToString(date_format)); cmd.Parameters.AddWithValue("@directory", file.Directory); cmd.Parameters.AddWithValue("@deleted", file.Deleted); cmd.ExecuteNonQuery(); DirectoryFile newFile = file.clone(); newStatus.Files.Add(newFile.Fullname, newFile); } else { cmd.CommandText = @"insert into snapshots (user_id,file_id,creation_time,checksum,path,filename,last_mod_time,deleted) values" + " (@user, @fileId, @creationTime, @checksum, @path, @filename, @lastModTime, @deleted);"; cmd.Parameters.AddWithValue("@user", file.UserId); cmd.Parameters.AddWithValue("@fileId", file.Id); cmd.Parameters.AddWithValue("@creationTime", newStatus.CreationTime.ToString(date_format)); cmd.Parameters.AddWithValue("@checksum", file.Checksum); cmd.Parameters.AddWithValue("@path", file.Path + "\\"); cmd.Parameters.AddWithValue("@filename", file.Filename); cmd.Parameters.AddWithValue("@lastModTime", file.LastModificationTime.ToString(date_format)); cmd.Parameters.AddWithValue("@deleted", file.Deleted); cmd.ExecuteNonQuery(); DirectoryFile newFile = file.clone(); newStatus.Files.Add(newFile.Fullname, newFile); } } } return true; } catch (SQLiteException) { return false;} }
public static bool deleteDirectory(SQLiteConnection conn, DirectoryStatus newStatus, DirectoryStatus oldStatus, String path, DateTime lastModTime) { try { path += "\\"; Dictionary<String, DirectoryFile> del = new Dictionary<String,DirectoryFile>(); foreach (var item in oldStatus.Files) { String s = item.Key + "\\"; if (s.Length >= path.Length) { if (s.Substring(0, path.Length).Equals(path)) { // file or directory contained in the directory to delete del.Add(item.Key, item.Value); } } } foreach (var item in del) { using (SQLiteCommand cmd = conn.CreateCommand()) { DirectoryFile file = item.Value; if (file.Directory) { cmd.CommandText = @"insert into snapshots (user_id,creation_time,path,filename," + " last_mod_time,directory,deleted) values (@user, @creationTime, @path," + " @filename, @lastModTime, @directory, @deleted);"; cmd.Parameters.AddWithValue("@user", newStatus.Username); cmd.Parameters.AddWithValue("@creationTime", newStatus.CreationTime.ToString(date_format)); cmd.Parameters.AddWithValue("@path", file.Path + "\\"); cmd.Parameters.AddWithValue("@filename", file.Filename); cmd.Parameters.AddWithValue("@lastModTime", file.LastModificationTime.ToString(date_format)); cmd.Parameters.AddWithValue("@directory", file.Directory); cmd.Parameters.AddWithValue("@deleted", true); cmd.ExecuteNonQuery(); file.Deleted = true; DirectoryFile newFile = file.clone(); newStatus.Files.Add(newFile.Fullname, newFile); } else { cmd.CommandText = @"insert into snapshots (user_id,file_id,creation_time,checksum,path,filename," + " last_mod_time,deleted) values (@user, @fileId, @creationTime, @checksum, @path," + " @filename, @lastModTime, @deleted);"; cmd.Parameters.AddWithValue("@user", file.UserId); cmd.Parameters.AddWithValue("@fileId", file.Id); cmd.Parameters.AddWithValue("@creationTime", newStatus.CreationTime.ToString(date_format)); cmd.Parameters.AddWithValue("@checksum", file.Checksum); cmd.Parameters.AddWithValue("@path", file.Path + "\\"); cmd.Parameters.AddWithValue("@filename", file.Filename); cmd.Parameters.AddWithValue("@lastModTime", file.LastModificationTime.ToString(date_format)); cmd.Parameters.AddWithValue("@deleted", true); cmd.ExecuteNonQuery(); file.Deleted = true; DirectoryFile newFile = file.clone(); newStatus.Files.Add(newFile.Fullname, newFile); } } } return true; } catch (SQLiteException) { return false;} }
public static bool cleanDBfiles(SQLiteConnection conn, DirectoryStatus newStatus, String filename, String path) { return cleanDBfiles(conn, newStatus.Username, filename, path); }
public static bool insertDirectory(SQLiteConnection conn, DirectoryStatus newStatus, String filename, String path, DateTime lastModTime) { try { using (SQLiteCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"insert into snapshots (user_id,creation_time,path,filename,last_mod_time,directory) values" + " (@user, @creationTime, @path, @filename, @lastModTime, @directory);"; cmd.Parameters.AddWithValue("@user", newStatus.Username); cmd.Parameters.AddWithValue("@creationTime", newStatus.CreationTime.ToString(date_format)); cmd.Parameters.AddWithValue("@path", path + "\\"); cmd.Parameters.AddWithValue("@filename", filename); cmd.Parameters.AddWithValue("@lastModTime", lastModTime.ToString(date_format)); cmd.Parameters.AddWithValue("@directory", true); cmd.ExecuteNonQuery(); } //add directory DirectoryFile dirFile = new DirectoryFile(path, filename, newStatus.Username, lastModTime, true); newStatus.Files.Add(dirFile.Fullname, dirFile); return true; } catch (SQLiteException) { return false;} }
private void rw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { try { if (e.Error != null || e.Cancelled) { //something went wrong during restore connected = false; client.TcpClient.Close(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "An error on the server occurred, please try later"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); return; } else { bool result = (bool)e.Result; if (result) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.progressBar_file.Visibility = Visibility.Visible; this.progressBar_file.IsIndeterminate = true; this.Label_log.Content = "Resyncing with the server . . ."; this.Label_log.Visibility = Visibility.Visible; })); DirectoryStatus local = new DirectoryStatus(); local.FolderPath = RootDirectory; local.Username = client.UserId; CurrentDirectory = String.Copy(RootDirectory); client.fillDirectoryStatus(local, RootDirectory); DirectoryStatus remote = new DirectoryStatus(); remote.Username = client.UserId; remote.FolderPath = RootDirectory; // for updating the progress bar PbUpdater up = new PbUpdater(); up.rootDir = RootDirectory; up.remote = remote; up.local = local; sync_worker.RunWorkerAsync(up); this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.progressBar_file.IsIndeterminate = true; this.progressBar_file.Visibility = Visibility.Visible; this.file_grid.Visibility = Visibility.Hidden; this.Back_button.Visibility = Visibility.Hidden; this.Home_button.Visibility = Visibility.Hidden; this.Refresh_button.Visibility = Visibility.Hidden; this.Label_log.Content = "Restoring directory " + up.rootDir + "..."; this.Label_log.Visibility = Visibility.Visible; })); // try to free some memory ... local = null; remote = null; //GC.Collect(); } else { //something went wrong during restore connected = false; client.TcpClient.Close(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "An error on the server occurred, please try later"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } } } catch (UnauthorizedAccessException) { } catch (IOException) { } }
private void Restore_Button_Click(object sender, RoutedEventArgs e) { if (!client.resumeSession()) { connected = false; client.TcpClient.Close(); if (watcher != null) watcher.Stop(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "Your session is expired, please login again"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); return; } ListItem item = ((FrameworkElement)sender).DataContext as ListItem; String path = System.IO.Path.Combine(item.Path, item.Filename); if (item.Directory) { //restore directory watcher.Stop(); if (!Directory.Exists(path)) Directory.CreateDirectory(path); PbUpdater up = new PbUpdater(); up.path = path; restore_worker.RunWorkerAsync(up); } else { if (item.Deleted) { //restore file watcher.Stop(); if (!Directory.Exists(item.Path)) Directory.CreateDirectory(item.Path); PbUpdater up = new PbUpdater(); up.path = path; up.id = item.Id; restore_worker.RunWorkerAsync(up); } else { //for turn back on the directory CurrentDirectory = path; //see older versions of a file DirectoryStatus dir = new DirectoryStatus(); this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.Back_button.IsEnabled = false; this.Refresh_button.IsEnabled = false; })); int n = client.getPreviousVersions(dir, CurrentDirectory); if (n < 0) { connected = false; client.TcpClient.Close(); if (watcher != null) watcher.Stop(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "A Network Error occurred, please try later"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } if (n == 0) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { FileList.Clear(); this.file_grid.ItemsSource = FileList; this.Back_button.IsEnabled = true; this.Label_log.Content = "No previous version for the file selected"; this.Label_log.Visibility = Visibility.Visible; })); } else this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new FillGrid(fill_prev_grid), dir); } } }
private void Refresh_button_Click(object sender, RoutedEventArgs e) { if (!client.resumeSession()) { connected = false; client.TcpClient.Close(); if (watcher != null) watcher.Stop(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "Your session is expired, please login again"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); return; } if (CurrentDirectory != null) { DirectoryStatus dir = new DirectoryStatus(); if (client.getDirectoryInfo(dir, CurrentDirectory) < 0) { connected = false; client.TcpClient.Close(); if (watcher != null) watcher.Stop(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "A Network Error occurred, please try later"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } else this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new FillGrid(fill_grid), dir); } }
private void Back_button_Click(object sender, RoutedEventArgs e) { if (!client.resumeSession()) { connected = false; client.TcpClient.Close(); if (watcher != null) watcher.Stop(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "Your session is expired, please login again"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); return; } if (CurrentDirectory != null) { CurrentDirectory = System.IO.Path.GetDirectoryName(CurrentDirectory); DirectoryStatus dir = new DirectoryStatus(); this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.Back_button.IsEnabled = true; this.Refresh_button.IsEnabled = true; this.Label_filename.Visibility = Visibility.Hidden; })); if (client.getDirectoryInfo(dir, CurrentDirectory) < 0) { connected = false; client.TcpClient.Close(); if (watcher != null) watcher.Stop(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "A Network Error occurred, please try later"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } else this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new FillGrid(fill_grid), dir); } }
private void file_grid_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (!client.resumeSession()) { connected = false; client.TcpClient.Close(); if (watcher != null) watcher.Stop(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "Your session is expired, please login again"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); return; } if (this.file_grid.SelectedItem == null) return; var item = this.file_grid.SelectedItem as FileListItem; if (item.Directory) { //entry is a directory DirectoryStatus dir = new DirectoryStatus(); CurrentDirectory = System.IO.Path.Combine(item.Path, item.Filename); if (client.getDirectoryInfo(dir, CurrentDirectory) < 0) { connected = false; client.TcpClient.Close(); if (watcher != null) watcher.Stop(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "A Network Error occurred, please try later"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new FillGrid(fill_grid), dir); } }
private void Back_button_2_Click(object sender, RoutedEventArgs e) { if (!client.resumeSession()) { connected = false; if (watcher != null) watcher.Stop(); client.TcpClient.Close(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "Your session is expired, please login again"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); return; } if (CurrentDirectory != null) { if (CurrentDirectory.Equals(RootDirectory)) { DirectoryStatus ds = new DirectoryStatus(); int directories = client.getAllSnapshots(ds); if (directories >= 0) { if (directories == 0) { // no previous sync this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.progressBar_file.Visibility = Visibility.Hidden; this.Label_log.Content = "No previous synchronization found.\nGo back and start synchronize one folder"; })); } else { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new FillGrid(fill_dir_grid), ds); } } else { //error connected = false; client.TcpClient.Close(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "A Network Error occurred, please try later"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } } else { CurrentDirectory = System.IO.Path.GetDirectoryName(CurrentDirectory); DirectoryStatus dir = new DirectoryStatus(); this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.Back_button_2.IsEnabled = true; })); if (client.getSnapshotInfo(dir, CurrentDirectory, CurrentSnapshotTime) < 0) { connected = false; client.TcpClient.Close(); if (watcher != null) watcher.Stop(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "A Network Error occurred, please try later"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } else this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new FillGrid(fill_snap_grid), dir); } } }
private void fill_snap_grid(DirectoryStatus status) { FileList.Clear(); foreach (var item in status.Files) { SnapshotItem file = new SnapshotItem(item.Value); FileList.Add(file); } this.Back_button_2.Visibility = Visibility.Visible; this.Home_button.Visibility = Visibility.Visible; this.progressBar_file.Visibility = Visibility.Hidden; this.Label_log.Visibility = Visibility.Hidden; this.Label_log.Visibility = Visibility.Hidden; this.file_grid.Visibility = Visibility.Hidden; this.filePrev_grid.Visibility = Visibility.Hidden; this.dir_grid.Visibility = Visibility.Hidden; this.fileSnap_grid.Visibility = Visibility.Visible; this.fileSnap_grid.ItemsSource = FileList; }
public static DirectoryStatus getAllSnapshots(String username) { DirectoryStatus ds = new DirectoryStatus(); try { using (var con = new SQLiteConnection(DBmanager.connectionString)) { con.Open(); using (var cmd = con.CreateCommand()) { cmd.CommandText = @"select distinct path,creation_time from snapshots where user_id=@id"; cmd.Parameters.AddWithValue("@id", username); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { DirectoryFile file = new DirectoryFile(); file.UserId = username; file.Directory = true; file.Path = (String)reader["path"]; file.Path = file.Path.Substring(0, file.Path.LastIndexOf('\\')); DateTime prefix = (DateTime)reader["creation_time"]; file.Fullname = (String)prefix.ToString("dd/MM/yyyyTHH:ss") + "_" + (String)reader["path"]; file.LastModificationTime = (DateTime)reader["creation_time"]; ds.Files.Add(file.Fullname, file); } } } } return ds; } catch (SQLiteException) { return null; } }
public static DirectoryStatus getSnapshotFilesOfDirectory(String directory, String username, DateTime creationTime) { DirectoryStatus ds = new DirectoryStatus(); ds.FolderPath = directory; ds.Username = username; try { using (var con = new SQLiteConnection(connectionString)) { con.Open(); using (var cmd = con.CreateCommand()) { int len = directory.Length; cmd.CommandText = @"select * from snapshots where user_id = @id" + " and path = @dir and creation_time = @date;"; cmd.Parameters.AddWithValue("@id", username); cmd.Parameters.AddWithValue("@dir", directory + "\\"); cmd.Parameters.AddWithValue("@date", creationTime.ToString(date_format)); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { DirectoryFile file = new DirectoryFile(); file.UserId = username; file.Directory = (Boolean)reader["directory"]; file.Path = (String)reader["path"]; file.Path = file.Path.Substring(0, file.Path.LastIndexOf('\\')); file.Filename = (String)reader["filename"]; file.Deleted = (Boolean)reader["deleted"]; file.LastModificationTime = (DateTime)reader["last_mod_time"]; if (!file.Directory) { file.Id = (Int64)reader["file_id"]; file.Checksum = (String)reader["checksum"]; } file.Fullname = Path.Combine(file.Path, file.Filename); ds.Files.Add(file.Fullname, file); } } } } return ds; } catch (SQLiteException) { return ds; } }
private void sw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (!connected) return; bool result = (bool)e.Result; if ( !client.resumeSession() ) { connected = false; client.TcpClient.Close(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "Your session is expired, please login again"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } else { if (result) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.progressBar_file.Visibility = Visibility.Hidden; this.file_grid.Visibility = Visibility.Visible; this.dir_grid.Visibility = Visibility.Hidden; this.fileSnap_grid.Visibility = Visibility.Hidden; this.Back_button.Visibility = Visibility.Visible; this.Home_button.Visibility = Visibility.Visible; this.Refresh_button.Visibility = Visibility.Visible; this.Label_log.Visibility = Visibility.Hidden; })); DirectoryStatus remote = new DirectoryStatus(); remote.Username = client.UserId; remote.FolderPath = RootDirectory; if (client.getDirectoryInfo(remote, RootDirectory) < 0) { connected = false; client.TcpClient.Close(); String msg = "Log in to the remote server"; String title = "You were disconncted"; String bannerMsg = "A Network Error occurred, please try later"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } else { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new FillGrid(fill_grid), remote); watcher = new Watcher(RootDirectory, client); } } else { String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "An error occurred during synchronization, pleasy try later"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } } }
/***** Clean DB functions ******/ public static bool cleanDBsnapshots(SQLiteConnection conn, DirectoryStatus newStatus, String directory) { return cleanDBsnapshots(conn, newStatus.Username, directory); }
private void fill_prev_grid(DirectoryStatus status) { FileList.Clear(); if (CurrentDirectory.Equals(RootDirectory)) { //see turn back botton this.Back_button.IsEnabled = false; } else { //don't see botton this.Back_button.IsEnabled = true; } foreach (var item in status.Files) { FileVersionItem file = new FileVersionItem(item.Value); FileList.Add(file); } this.Label_log.Visibility = Visibility.Hidden; this.file_grid.Visibility = Visibility.Hidden; this.dir_grid.Visibility = Visibility.Hidden; this.fileSnap_grid.Visibility = Visibility.Hidden; this.filePrev_grid.Visibility = Visibility.Visible; this.Label_filename.Content = "Previous versions of the file " + FileList[0].Filename; this.Label_filename.Visibility = Visibility.Visible; this.filePrev_grid.ItemsSource = FileList; }
/***** END CLEAN DB ******/ public static bool insertFile(SQLiteConnection conn, DirectoryStatus newStatus, String filename, String path, byte[] file, DateTime lastModTime) { try { /*****DB cleaning******/ if (!cleanDBfiles(conn, newStatus, filename, path)) return false; /*****END CLEANING******/ using (SQLiteCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"insert into files (user_id,path,filename,content,last_mod_time) values" + " (@user, @path, @filename, @content, @lastModTime);"; cmd.Parameters.AddWithValue("@user", newStatus.Username); cmd.Parameters.AddWithValue("@path", path + "\\"); cmd.Parameters.AddWithValue("@filename", filename); cmd.Parameters.AddWithValue("@content", file); cmd.Parameters.AddWithValue("@lastModTime", lastModTime.ToString(date_format)); cmd.ExecuteNonQuery(); } Int64? fileId = -1; using (SQLiteCommand cmd = conn.CreateCommand()) { cmd.CommandText = "select file_id from files where user_id = @user and path = @path and" + " filename = @filename and last_mod_time = @lastModTime;"; cmd.Parameters.AddWithValue("@user", newStatus.Username); cmd.Parameters.AddWithValue("@path", path + "\\"); cmd.Parameters.AddWithValue("@filename", filename); cmd.Parameters.AddWithValue("@lastModTime", lastModTime.ToString(date_format)); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { fileId = (Int64?)reader[0]; } } } if (fileId == null || fileId <= 0) return false; String checksum = Security.CalculateMD5Hash(file); using (SQLiteCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"insert into snapshots (user_id,file_id,creation_time,checksum,path,last_mod_time,filename) values" + " (@user, @fileId, @creationTime, @checksum, @path, @lastModTime, @filename);"; cmd.Parameters.AddWithValue("@user", newStatus.Username); cmd.Parameters.AddWithValue("@fileId", fileId); cmd.Parameters.AddWithValue("@creationTime", newStatus.CreationTime.ToString(date_format)); cmd.Parameters.AddWithValue("@checksum", checksum); cmd.Parameters.AddWithValue("@lastModTime", lastModTime.ToString(date_format)); cmd.Parameters.AddWithValue("@path", path + "\\"); cmd.Parameters.AddWithValue("@filename", filename); cmd.ExecuteNonQuery(); } //add file DirectoryFile dirFile = new DirectoryFile((Int64)fileId, path, filename, newStatus.Username, checksum, lastModTime); newStatus.Files.Add(dirFile.Fullname, dirFile); return true; } catch (SQLiteException) { return false;} }
private void Sync_init_button_Click(object sender, RoutedEventArgs e) { try { DispatcherOperation result = this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new LoginDelegate(updateUI_logged)); result.Wait(); RootDirectory = (String)result.Result; if (RootDirectory != null && RootDirectory != String.Empty) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.Sync_init_button.Visibility = Visibility.Hidden; this.Home_button.Visibility = Visibility.Hidden; this.Restore_init_button.Visibility = Visibility.Hidden; this.progressBar_file.Visibility = Visibility.Visible; this.progressBar_file.IsIndeterminate = true; this.Label_log.Content = "Retrieving directory infromation . . ."; this.Label_log.Visibility = Visibility.Visible; })); if (!client.resumeSession()) { connected = false; client.TcpClient.Close(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "Your session is expired, please login again"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } else { DirectoryStatus local = new DirectoryStatus(); local.FolderPath = RootDirectory; local.Username = client.UserId; CurrentDirectory = String.Copy(RootDirectory); client.fillDirectoryStatus(local, RootDirectory); DirectoryStatus remote = new DirectoryStatus(); remote.Username = client.UserId; remote.FolderPath = RootDirectory; // for updating the progress bar PbUpdater up = new PbUpdater(); up.rootDir = RootDirectory; up.remote = remote; up.local = local; sync_worker.RunWorkerAsync(up); this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.progressBar_file.IsIndeterminate = false; this.Label_log.Content = "Checking for previous sessions of the directory ..."; })); // try to free some memory ... local = null; remote = null; GC.Collect(); } } } catch (UnauthorizedAccessException) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(async () => { await this.ShowMessageAsync("Operation not permitted", "You don't have the rights to synchornize this folder. Please choose another folder and retry."); this.Grid_initial.Visibility = Visibility.Collapsed; this.progressBar_file.Visibility = Visibility.Hidden; this.Grid_logged.Visibility = Visibility.Visible; this.file_grid.Visibility = Visibility.Hidden; this.dir_grid.Visibility = Visibility.Hidden; this.fileSnap_grid.Visibility = Visibility.Hidden; this.Back_button.Visibility = Visibility.Hidden; this.Back_button_2.Visibility = Visibility.Collapsed; this.Refresh_button.Visibility = Visibility.Hidden; this.Home_button.Visibility = Visibility.Hidden; this.Sync_init_button.Visibility = Visibility.Visible; this.Restore_init_button.Visibility = Visibility.Visible; this.Label_log.Visibility = Visibility.Visible; this.Label_log.Content = "Welcome back, " + client.UserId + "! Choose one of the following options"; })); } catch (IOException) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(async () => { await this.ShowMessageAsync("Something were wrong", "An error occurred. Please check if one file that must be synchronized is opened by another process."); this.Grid_initial.Visibility = Visibility.Collapsed; this.Grid_logged.Visibility = Visibility.Visible; this.progressBar_file.Visibility = Visibility.Hidden; this.file_grid.Visibility = Visibility.Hidden; this.dir_grid.Visibility = Visibility.Hidden; this.fileSnap_grid.Visibility = Visibility.Hidden; this.Back_button.Visibility = Visibility.Hidden; this.Back_button_2.Visibility = Visibility.Collapsed; this.Refresh_button.Visibility = Visibility.Hidden; this.Home_button.Visibility = Visibility.Hidden; this.Sync_init_button.Visibility = Visibility.Visible; this.Restore_init_button.Visibility = Visibility.Visible; this.Label_log.Visibility = Visibility.Visible; this.Label_log.Content = "Welcome back, " + client.UserId + "! Choose one of the following options"; })); } }
public static bool deleteFile(SQLiteConnection conn, DirectoryFile file, DirectoryStatus newStatus) { try { using (SQLiteCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"insert into snapshots (user_id,file_id,creation_time,checksum,path," + " filename,last_mod_time,deleted) values (@user, @fileId, @creationTime, @checksum, @path," + " @filename, @lastModTime, @deleted);"; cmd.Parameters.AddWithValue("@user", file.UserId); cmd.Parameters.AddWithValue("@fileId", file.Id); cmd.Parameters.AddWithValue("@creationTime", newStatus.CreationTime.ToString(date_format)); cmd.Parameters.AddWithValue("@checksum", file.Checksum); cmd.Parameters.AddWithValue("@path", file.Path + "\\"); cmd.Parameters.AddWithValue("@filename", file.Filename); cmd.Parameters.AddWithValue("@lastModTime", file.LastModificationTime.ToString(date_format)); cmd.Parameters.AddWithValue("@deleted", true); cmd.ExecuteNonQuery(); } DirectoryFile dirFile = new DirectoryFile(file.Id, file.Path, file.Filename, file.UserId, file.Checksum, file.LastModificationTime); file.Deleted = true; newStatus.Files.Add(dirFile.Fullname, dirFile); return true; } catch (SQLiteException) { return false; } }
private void Restore_init_button_Click(object sender, RoutedEventArgs e) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.Sync_init_button.Visibility = Visibility.Hidden; this.Restore_init_button.Visibility = Visibility.Hidden; this.Home_button.Visibility = Visibility.Hidden; this.progressBar_file.Visibility = Visibility.Visible; this.progressBar_file.IsIndeterminate = true; this.Label_log.Content = "Retrieving previous synchronized directories . . ."; this.Label_log.Visibility = Visibility.Visible; })); if (!client.resumeSession()) { connected = false; client.TcpClient.Close(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "Your session is expired, please login again"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } else { DirectoryStatus ds = new DirectoryStatus(); int directories = client.getAllSnapshots(ds); if (directories >= 0) { if (directories == 0) { // no previous sync this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.progressBar_file.Visibility = Visibility.Hidden; this.Home_button.Visibility = Visibility.Visible; this.Label_log.Content = "No previous synchronization found.\nGo back and start synchronize one folder"; })); } else { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new FillGrid(fill_dir_grid), ds); } } else { //error connected = false; client.TcpClient.Close(); String msg = "Log in to the remote server"; String title = "You were disconnected"; String bannerMsg = "Your session is expired, please login again"; this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateDelegateAsync(updateUI_banner), msg, title, bannerMsg); } } }
public static DirectoryStatus getPreviousVersion(String path, String username, DateTime date) { DirectoryStatus ds = new DirectoryStatus(); ds.FolderPath = path; ds.Username = username; try { using (var con = new SQLiteConnection(connectionString)) { con.Open(); using (var cmd = con.CreateCommand()) { cmd.CommandText = @"select path,filename,file_id,last_mod_time,content" + " from files where user_id = @id" + " and path = @dir and filename = @filename" + " and last_mod_time < @date;"; cmd.Parameters.AddWithValue("@id", username); cmd.Parameters.AddWithValue("@dir", Path.GetDirectoryName(path) + "\\"); cmd.Parameters.AddWithValue("@filename", Path.GetFileName(path)); cmd.Parameters.AddWithValue("@date", date.ToString(date_format)); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { DirectoryFile file = new DirectoryFile(); file.UserId = username; file.Path = (String)reader["path"]; file.Path = file.Path.Substring(0, file.Path.LastIndexOf('\\')); file.Filename = (String)reader["filename"]; file.Id = (Int64)reader["file_id"]; file.Checksum = Security.CalculateMD5Hash((byte[])reader["content"]); file.LastModificationTime = (DateTime)reader["last_mod_time"]; file.Deleted = true; file.Fullname = Path.Combine(file.Path, file.Filename); ds.Files.Add(file.NameVersion, file); } } } } return ds; } catch (SQLiteException) { return ds; } }
public bool synchronizationSession(ClientSession clientSession) { DirectoryStatus newStatus = new DirectoryStatus(); newStatus.FolderPath = clientSession.CurrentStatus.FolderPath; newStatus.Username = clientSession.CurrentStatus.Username; SQLiteConnection con = null; SQLiteTransaction transaction = null; bool success = false; try { bool exit = false; con = new SQLiteConnection(DBmanager.connectionString); con.Open(); transaction = con.BeginTransaction(); while (!exit) { byte[] command = Utility.Networking.my_recv(4, clientSession.Socket); if (command != null) { Networking.CONNECTION_CODES code = (Networking.CONNECTION_CODES)BitConverter.ToUInt32(command, 0); switch (code) { case Networking.CONNECTION_CODES.ADD: if (!this.addFile(con, clientSession, newStatus)) exit = true; break; case Networking.CONNECTION_CODES.UPD: if (!this.updateFile(con, clientSession, newStatus)) exit = true; break; case Networking.CONNECTION_CODES.DEL: if (!this.deleteFile(con, clientSession, newStatus)) exit = true; break; case Networking.CONNECTION_CODES.HELLO: this.Hello(clientSession.Socket); break; case Networking.CONNECTION_CODES.SESSION: if (!this.resumeSession(ref clientSession, clientSession.Socket)) exit = true; break; case Networking.CONNECTION_CODES.END_SYNCH: if (DBmanager.insertUnchanged(con, clientSession.CurrentStatus, newStatus)) { //success success = true; lock (this.id2client[clientSession.SessionId]) { this.id2client[clientSession.SessionId].CurrentStatus = null; this.id2client[clientSession.SessionId].CurrentStatus = newStatus; this.id2client[clientSession.SessionId].LastActivationTime = DateTime.Now; } } exit = true; break; default: exit = true; break; } } else { exit = true; } } if (success) { transaction.Commit(); transaction.Dispose(); byte[] command = BitConverter.GetBytes((UInt32)Networking.CONNECTION_CODES.OK); clientSession.Socket.Send(command); } else { transaction.Rollback(); } } catch (SocketException) { newStatus = null; if (transaction != null) { transaction.Rollback(); } return false; } catch (SQLiteException) { newStatus = null; if (transaction != null) { transaction.Rollback(); } return false; } finally { if (transaction != null) { transaction.Dispose(); } if (con != null && con.State == System.Data.ConnectionState.Open) con.Dispose(); } return success; }
private bool deleteFile(SQLiteConnection conn, ClientSession clientSession, DirectoryStatus newStatus) { Socket s = clientSession.Socket; AesCryptoServiceProvider aes = clientSession.AESKey; try { byte[] recvBuf = Networking.my_recv(4, s); if (recvBuf == null) return false; byte[] encryptedData = Networking.my_recv(BitConverter.ToInt32(recvBuf, 0), s); if (encryptedData == null) return false; String filename = Encoding.UTF8.GetString(Security.AESDecrypt(aes, encryptedData)); recvBuf = Networking.my_recv(4, s); if (recvBuf == null) return false; encryptedData = Networking.my_recv(BitConverter.ToInt32(recvBuf, 0), s); if (encryptedData == null) return false; String path = Encoding.UTF8.GetString(Security.AESDecrypt(aes, encryptedData)); recvBuf = Networking.my_recv(8, s); if (recvBuf == null) return false; DateTime lastModTime = DateTime.FromBinary(BitConverter.ToInt64(recvBuf, 0)); recvBuf = Networking.my_recv(4, s); if (recvBuf == null) return false; if ((Networking.CONNECTION_CODES)BitConverter.ToUInt32(recvBuf, 0) == Networking.CONNECTION_CODES.DIR) { //directory String fullname = Path.Combine(path, filename); return DBmanager.deleteDirectory(conn, newStatus, clientSession.CurrentStatus, fullname, lastModTime); } if ((Networking.CONNECTION_CODES)BitConverter.ToUInt32(recvBuf, 0) == Networking.CONNECTION_CODES.FILE) { //file String fullname = Path.Combine(path, filename); DirectoryFile file = clientSession.CurrentStatus.Files[fullname]; return DBmanager.deleteFile(conn, file, newStatus); } return false; } catch (SocketException) {return false; } }
private bool updateFile(SQLiteConnection conn, ClientSession clientSession, DirectoryStatus newStatus) { Socket s = clientSession.Socket; AesCryptoServiceProvider aes = clientSession.AESKey; try { byte[] recvBuf = Networking.my_recv(4, s); if (recvBuf == null) return false; byte[] encryptedData = Networking.my_recv(BitConverter.ToInt32(recvBuf, 0), s); if (encryptedData == null) return false; String filename = Encoding.UTF8.GetString(Security.AESDecrypt(aes, encryptedData)); recvBuf = Networking.my_recv(4, s); if (recvBuf == null) return false; encryptedData = Networking.my_recv(BitConverter.ToInt32(recvBuf, 0), s); if (encryptedData == null) return false; String path = Encoding.UTF8.GetString(Security.AESDecrypt(aes, encryptedData)); recvBuf = Networking.my_recv(8, s); if (recvBuf == null) return false; DateTime lastModTime = DateTime.FromBinary(BitConverter.ToInt64(recvBuf, 0)); byte[] command = BitConverter.GetBytes((UInt32)Networking.CONNECTION_CODES.OK); s.Send(command); recvBuf = Networking.my_recv(8, s); if (recvBuf == null) return false; Int64 fileLen = BitConverter.ToInt64(recvBuf, 0); byte[] file = Networking.recvEncryptedFile(fileLen, s, aes); if (file == null) return false; return DBmanager.insertFile(conn, newStatus, filename, path, file, lastModTime); } catch (SocketException) { return false;} }
/// <summary> /// Produce the intersection set of this and src /// </summary> /// <param name="src">the set with which to perform the intersection </param> /// <returns>the intersect set</returns> public Dictionary<String, DirectoryFile> getIntersect(DirectoryStatus src) { Dictionary<String, DirectoryFile> d1 = this.files; Dictionary<String, DirectoryFile> d2 = src.files; Dictionary<String, DirectoryFile> d3; d3 = d1.Where(x => d2.ContainsKey(x.Key)).ToDictionary(x => x.Key, x => x.Value); return d3; }
public int getPreviousVersions(DirectoryStatus dir, String path) { try { Socket s = tcpClient.Client; byte[] command = BitConverter.GetBytes((UInt32)Networking.CONNECTION_CODES.PREV); s.Send(command); byte[] buf = Security.AESEncrypt(aesKey, Encoding.UTF8.GetBytes(path)); s.Send(BitConverter.GetBytes(buf.Length)); s.Send(buf); long date = File.GetLastWriteTime(path).ToBinary(); buf = BitConverter.GetBytes(date); s.Send(buf); command = Networking.my_recv(4, tcpClient.Client); if (command != null && ( ((Networking.CONNECTION_CODES)BitConverter.ToUInt32(command, 0) == Networking.CONNECTION_CODES.OK))) { byte[] recvBuf = Networking.my_recv(4, s); if (recvBuf == null) return -1; Int32 filesInfoToRecv = BitConverter.ToInt32(recvBuf, 0); for (int i = 0; i < filesInfoToRecv; i++) { DirectoryFile file = new DirectoryFile(); recvBuf = Networking.my_recv(8, s); if (recvBuf == null) return -1; DateTime lastModTime = DateTime.FromBinary(BitConverter.ToInt64(recvBuf, 0)); recvBuf = Networking.my_recv(8, s); if (recvBuf == null) return -1; Int64 id = BitConverter.ToInt64(recvBuf, 0); byte[] encryptedData = Networking.my_recv(48, s); if (encryptedData == null) return -1; String checksum = Encoding.UTF8.GetString(Security.AESDecrypt(aesKey, encryptedData)); file.Checksum = checksum; file.Id = id; file.Deleted = true; file.UserId = userId; file.Filename = Path.GetFileName(path); file.Path = Path.GetDirectoryName(path); file.LastModificationTime = lastModTime; file.Fullname = Path.Combine(file.Path, file.Filename); dir.Files.Add(file.NameVersion, file); } return filesInfoToRecv; } } catch (SocketException) { return -1; } return -1; }