public void PersistAndDeserialize() { string[] lines = { "First line", "Second line", "Third line" }; System.IO.Directory.CreateDirectory("asd"); System.IO.Directory.CreateDirectory(@"asd\ciao"); DirectoryInfo rinfo = new DirectoryInfo("asd"); System.IO.File.WriteAllLines(@"asd\uno.txt", lines); System.IO.File.WriteAllLines(@"asd\ciao\due.txt", lines); FileInfo finfo = new FileInfo(@"asd\ciao\due.txt"); FBVersionBuilder vb = new FBVersionBuilder(rinfo.FullName); FolderBackup.Shared.FBVersion v = (FolderBackup.Shared.FBVersion)vb.generate(); Stream TestFileStream = File.Create("version.bin"); BinaryFormatter serializer = new BinaryFormatter(); serializer.Serialize(TestFileStream, v); TestFileStream.Close(); TestFileStream = File.OpenRead("version.bin"); BinaryFormatter deserializer = new BinaryFormatter(); FBVersion v2 = (FBVersion)deserializer.Deserialize(TestFileStream); TestFileStream.Close(); File.Delete("version.bin"); System.IO.Directory.Delete("asd", true); Assert.AreEqual(v2, v); }
public UploadData resetToCraftedVersion(SerializedVersion serV) { FBVersion newVersion = FBVersion.deserialize(serV.encodedVersion); FBVersion current = this.currentVersion(); return(this.resetInternals(newVersion, current)); }
private void revert_Click(object sender, RoutedEventArgs e) { if (this.versions != null) { FBVersion lastVers = (FBVersion)this.versions[versions.Length - 1].Clone(); FBDirectory dir = lastVers.root; Dictionary <string, List <TreeViewItemFat> > revertItems = new Dictionary <string, List <TreeViewItemFat> >(); if (revertList.Items.Count == 0) { MessageBox.Show("There are no file to revert in the list please add them!", "List empty"); } foreach (TreeViewItemFat el in revertList.Items) { if (!revertItems.ContainsKey(el.relativePath)) { revertItems[el.relativePath] = new List <TreeViewItemFat>(); } revertItems[el.relativePath].Add(el); } modifyDir(revertItems, dir, dir.Name); se.resetToVersion(lastVers); revertList.Items.Clear(); } else { MessageBox.Show("There is a problem with connection, please retry to login!", "Error in connection"); } }
public UploadData getFile(SerializedVersion serV) { FBVersion ver = FBVersion.deserialize(serV.encodedVersion); PhysicFile found = null; if (ver.fileList.Count != 1) { return(null); } foreach (FBFile file in ver.fileList) { found = findPhysicFile(file); if (found == null) { return(null); } } FileStream fStream = new FileStream(found.getRealFileInfo().FullName, FileMode.Open, FileAccess.Read); String token = Server.GetUniqueKey(20); var secDown = new SecureDownloader(this, token, null, null, fStream); return(new UploadData(UsefullMethods.GetLocalIPAddress(), secDown.port, token)); }
public bool newTransaction(SerializedVersion newVersion) { this.checkAuthentication(); if (this.transactionEnabled) { throw new FaultException <ServiceErrorMessage>(new ServiceErrorMessage(ServiceErrorMessage.TRANSACTIONALREADYENABLED)); } FBVersion vers = FBVersion.deserialize(newVersion.encodedVersion); FBVersion current = FBVersion.deserialize(this.getCurrentVersion().encodedVersion); if (vers.Equals(current)) { return(false); } this.transactionEnabled = true; this.inSyncVersion = vers; String newDirPath = this.user.rootDirectory.FullName; newDirPath += "\\" + this.inSyncVersion.timestamp.ToString(directoryFormat, CultureInfo.InvariantCulture); this.transactDir = Directory.CreateDirectory(newDirPath); if (this.transactDir == null) { throw new FaultException <ServiceErrorMessage>(new ServiceErrorMessage(ServiceErrorMessage.CREATEVERSIONDIRECTORYFAILED)); } necessaryFiles = new ThreadSafeList <FBFile>(FBVersion.getNecessaryFilesToUpgrade(this.inSyncVersion, this.realFiles.filesAlreadyRepresented())); return(true); }
public void NecessaryFilesToUpgradeTest() { string[] lines1 = { "First line", "Second line", "Third line" }; string[] lines2 = { "First line", "Second line", "NO" }; System.IO.Directory.CreateDirectory("asd"); System.IO.Directory.CreateDirectory(@"asd\ciao"); DirectoryInfo rinfo = new DirectoryInfo("asd"); System.IO.File.WriteAllLines(@"asd\uno.txt", lines1); System.IO.File.WriteAllLines(@"asd\ciao\due.txt", lines1); System.IO.File.WriteAllLines(@"asd\ciao\tre.txt", lines1); System.IO.File.WriteAllLines(@"asd\ciao\quattro.txt", lines1); FBVersionBuilder vb = new FBVersionBuilder(rinfo.FullName); FolderBackup.Shared.FBVersion vold = (FolderBackup.Shared.FBVersion)vb.generate(); System.IO.File.WriteAllLines(@"asd\ciao\cinque.txt", lines2); System.IO.File.WriteAllLines(@"asd\sei.txt", lines2); System.IO.File.WriteAllLines(@"asd\sette.txt", lines1); FolderBackup.Shared.FBVersion vnew = (FolderBackup.Shared.FBVersion)vb.generate(); FBVersion diff = vnew - vold; List <FBFile> fl = FBVersion.getNecessaryFilesToUpgrade(vnew, vold.fileList); Assert.AreEqual(fl.Count, 1); FBFileBuilder fb = new FBFileBuilder(@"asd\ciao\cinque.txt"); FBFile necessary = (FBFile)fb.generate(); Assert.AreEqual(fl[0], necessary); System.IO.Directory.Delete("asd", true); }
private void initializeUser() { if (!File.Exists(this.user.rootDirectory + @"\files.bin")) //primo accesso { this.realFiles = new PhysicFilesList(); Stream FilesStream = File.OpenWrite(this.user.rootDirectory + @"\files.bin"); BinaryFormatter serializer = new BinaryFormatter(); serializer.Serialize(FilesStream, realFiles); FilesStream.Close(); this.user.rootDirectory.CreateSubdirectory(firstDirectory); FBVersionBuilder vb = new FBVersionBuilder(user.rootDirectory.FullName + @"\" + firstDirectory); FBVersion v = (FBVersion)vb.generate(); FilesStream = File.OpenWrite(this.user.rootDirectory.FullName + @"\" + firstDirectory + @"\version.bin"); serializer.Serialize(FilesStream, v); FilesStream.Close(); } else { Stream FilesStream1 = File.OpenRead(this.user.rootDirectory + @"\files.bin"); BinaryFormatter deserializer = new BinaryFormatter(); this.realFiles = (PhysicFilesList)deserializer.Deserialize(FilesStream1); FilesStream1.Close(); } }
private void buildGraphic() { SerializedVersion[] sversions = null; try { sversions = server.getOldVersions(); } catch { UsefullMethods.setLabelAlert("danger", this.errorBox, "No internet connection!Check it and retry"); return; } this.versions = new FBVersion[sversions.Length]; int i = 0; se.watcher.EnableRaisingEvents = false; versionBox.Items.Clear(); foreach (SerializedVersion v in sversions) { versions[i] = FBVersion.deserialize(v.encodedVersion); System.Windows.Controls.Button button = new System.Windows.Controls.Button(); button.Name = versions[i].timestamp.ToString(TIMESTAMP_FORMAT); button.Content = versions[i].timestamp.ToString("MMM, dd yyyy HH:mm"); button.Click += versionClick; button.MinWidth = 200; button.MinHeight = 22; if (i == sversions.Length - 1) { Color c = (Color)ColorConverter.ConvertFromString("#FF9C1A04"); button.Background = new SolidColorBrush(c); c = (Color)ColorConverter.ConvertFromString("#FFFFFFFF"); button.Foreground = new SolidColorBrush(c); } else { Color c = (Color)ColorConverter.ConvertFromString("#FFFFFFFF"); button.Background = new SolidColorBrush(c); c = (Color)ColorConverter.ConvertFromString("#FF000000"); button.Foreground = new SolidColorBrush(c); } versionBox.Items.Add(button); versionButtons.Add(button); i++; } versionView.Items.Clear(); if (versions.Length > 0) { this.selectedVersion = versions[versions.Length - 1]; versionView.Items.Add(CreateDirectoryNode(this.selectedVersion.root, this.selectedVersion.root.Name)); this.revertVersion.IsEnabled = false; } }
public void GetOldVersionsTest() { doTransaction(); server.commit(); SerializedVersion[] serVers = server.getOldVersions(); Assert.IsTrue(serVers.Length == 1); foreach (SerializedVersion serVer in serVers) { FBVersion ver = FBVersion.deserialize(serVer.encodedVersion); Assert.IsFalse(ver.root.Name.Contains("1970")); } }
public UploadData resetToPreviousVersion(int versionAgo) { var directories = Directory.EnumerateDirectories(user.rootDirectory.FullName).OrderByDescending(filename => filename); Stream TestFileStream = File.OpenRead((new DirectoryInfo(directories.ElementAt(versionAgo))).FullName + @"\version.bin"); BinaryFormatter deserializer = new BinaryFormatter(); FBVersion old = (FBVersion)deserializer.Deserialize(TestFileStream); TestFileStream.Close(); FBVersion actual = this.currentVersion(); return(resetInternals(old, actual)); }
public void resetPrevoiusVersion(int vIndex, FBVersion v) { this.sync(); UploadData ud = null; try { ud = server.resetToPreviousVersion(vIndex); resetVersion(ud, v); } catch (System.ServiceModel.CommunicationException e) { MessageBox.Show("There is a problem with connection, please retry to login!", "Error in connection"); } }
public void GetFileFailTest() { doTransaction(); server.commit(); FBVersion vers = new FBVersion(); FBFile file = (FBFile)(new FBFileBuilder(@"asd\due.txt")).generate(); file.hash = "asdsdaasd"; vers.addElement(file); SerializedVersion serV = new SerializedVersion(vers.serialize()); var uploadData = server.getFile(serV); Assert.IsNull(uploadData); }
public byte[][] getFilesToUpload() { this.checkAuthentication(); this.checkTransactionIsEnabled(); necessaryFiles = new ThreadSafeList <FBFile>(FBVersion.getNecessaryFilesToUpgrade(this.inSyncVersion, this.realFiles.filesAlreadyRepresented())); this.uploadedFiles = new PhysicFilesList(); byte[][] ret = new byte[necessaryFiles.Count][]; for (int i = 0; i < necessaryFiles.Count; ++i) { ret[i] = necessaryFiles.ElementAt(i).serialize(); } return(ret); }
public void GetFileTest() { doTransaction(); server.commit(); FBVersion vers = new FBVersion(); FBFile file = (FBFile)(new FBFileBuilder(@"asd\due.txt")).generate(); vers.addElement(file); SerializedVersion serV = new SerializedVersion(vers.serialize()); var uploadData = server.getFile(serV); UsefullMethods.ReceiveFile(uploadData.ip, uploadData.port, uploadData.token, @"asd\test.txt"); String content = File.ReadAllText(@"asd\test.txt"); Assert.IsTrue(content.Contains("Third lines")); }
private void resetVersion(UploadData ud, FBVersion v) { string filename = Path.GetTempFileName(); UsefullMethods.ReceiveFile(ud.ip, ud.port, ud.token, filename); String pathFiles; List <Instruction> instructionList = UsefullMethods.ExtractInstructions(filename, out pathFiles); instructionList.Sort((emp1, emp2) => emp1.cmd.CompareTo(emp2.cmd)); foreach (Instruction i in instructionList) { ExecuteInstruction(i, pathFiles); } CleanUpDir(v.root, ""); StartSync(); }
public string getFile(FBFile f) { SerializedVersion serV = new SerializedVersion(); FBVersion tmpVer = new FBVersion(); tmpVer.addElement(f); serV.encodedVersion = tmpVer.serialize(); var uploadData = server.getFile(serV); string tmpPath = Path.GetTempPath() + f.Name; if (File.Exists(tmpPath)) { File.Delete(tmpPath); } UsefullMethods.ReceiveFile(uploadData.ip, uploadData.port, uploadData.token, tmpPath); return(tmpPath); }
private FBVersion currentVersion() { DirectoryInfo[] versionDirs = user.rootDirectory.GetDirectories(); if (versionDirs == null) { throw new Exception(); } if (versionDirs.Length == 0) { Directory.CreateDirectory(user.rootDirectory.FullName + @"\" + firstDirectory); versionDirs = user.rootDirectory.GetDirectories(); } DirectoryInfo last = versionDirs[0]; foreach (DirectoryInfo di in versionDirs) { if (last.Equals(di)) { continue; } DateTime dtl = DateTime.ParseExact(last.Name, directoryFormat, CultureInfo.InvariantCulture); DateTime dt2 = DateTime.ParseExact(di.Name, directoryFormat, CultureInfo.InvariantCulture); if (dt2 > dtl) { last = di; } } Stream TestFileStream = null; try { TestFileStream = File.OpenRead(last.FullName + @"\version.bin"); }catch (FileNotFoundException) { Directory.Delete(last.FullName); return(currentVersion()); } BinaryFormatter deserializer = new BinaryFormatter(); FBVersion version = (FBVersion)deserializer.Deserialize(TestFileStream); TestFileStream.Close(); return(version); }
public void resetToVersion(FBVersion v) { this.sync(); SerializedVersion serV = new SerializedVersion(); serV.encodedVersion = v.serialize(); UploadData ud = null; try { ud = server.resetToCraftedVersion(serV); resetVersion(ud, v); } catch (System.ServiceModel.CommunicationException e) { MessageBox.Show("There is a problem with connection, please retry to login!", "Error in connection"); } }
private void versionClick(object sender, RoutedEventArgs e) { String name = ((System.Windows.Controls.Button)sender).Name; //search version FBVersion v = null; foreach (System.Windows.Controls.Button x in versionBox.Items) { if (sender == x) { Color c = (Color)ColorConverter.ConvertFromString("#FF9C1A04"); x.Background = new SolidColorBrush(c); c = (Color)ColorConverter.ConvertFromString("#FFFFFFFF"); x.Foreground = new SolidColorBrush(c); } else { Color c = (Color)ColorConverter.ConvertFromString("#FFFFFFFF"); x.Background = new SolidColorBrush(c); c = (Color)ColorConverter.ConvertFromString("#FF000000"); x.Foreground = new SolidColorBrush(c); } } foreach (FBVersion x in this.versions) { if (x.timestamp.ToString(TIMESTAMP_FORMAT) == name) { v = x; break; } } versionView.Items.Clear(); this.selectedVersion = v; versionView.Items.Add(CreateDirectoryNode(this.selectedVersion.root, this.selectedVersion.root.Name)); if (selectedVersion == versions[versions.Length - 1]) { this.revertVersion.IsEnabled = false; } else { this.revertVersion.IsEnabled = true; } }
public SerializedVersion getCurrentVersion() { this.checkAuthentication(); this.checkTransactionIsNotEnabled(); try { FBVersion version = currentVersion(); SerializedVersion serVersion = new SerializedVersion(version.serialize()); return(serVersion); } catch (Exception e) { Console.WriteLine(e.Message); throw new FaultException <ServiceErrorMessage>(new ServiceErrorMessage(ServiceErrorMessage.ROOTDIRECTORYNOTFOUND)); } }
public bool commit() { this.checkAuthentication(); this.checkTransactionIsEnabled(); FBVersionBuilder fvb = new FBVersionBuilder(this.ptransactDir.FullName); FBVersion actualVersion = (FBVersion)fvb.generate(); actualVersion.timestamp = inSyncVersion.timestamp; foreach (KeyValuePair <String, SecureChannel> pair in channels) { pair.Value.join(); } if (this.necessaryFiles.Count == 0) { Stream FileStream = File.Create(this.transactDir.FullName + @"\version.bin"); BinaryFormatter serializer = new BinaryFormatter(); serializer.Serialize(FileStream, this.inSyncVersion); FileStream.Close(); if (this.uploadedFiles != null) { realFiles.add(this.uploadedFiles); } FileStream = File.Open(this.user.rootDirectory + @"\files.bin", FileMode.Create, FileAccess.Write, FileShare.None); serializer.Serialize(FileStream, realFiles); FileStream.Close(); this.uploadedFiles = null; this.transactDir = null; this.inSyncVersion = null; this.transactionEnabled = false; return(true); } else { throw new FaultException <ServiceErrorMessage>(new ServiceErrorMessage(ServiceErrorMessage.SYNCNOTTERMINATED)); } }
private LinkedList <FBVersion> OldVersions() { DirectoryInfo[] versionDirs = user.rootDirectory.GetDirectories(); LinkedList <FBVersion> versions = new LinkedList <FBVersion>(); if (versionDirs == null) { throw new Exception(); } if (versionDirs.Length == 0) { Directory.CreateDirectory(user.rootDirectory.FullName + @"\" + firstDirectory); versionDirs = user.rootDirectory.GetDirectories(); } foreach (DirectoryInfo di in versionDirs) { Stream TestFileStream = null; try { TestFileStream = File.OpenRead(di.FullName + @"\version.bin"); } catch (FileNotFoundException) { Directory.Delete(di.FullName); continue; } BinaryFormatter deserializer = new BinaryFormatter(); FBVersion version = (FBVersion)deserializer.Deserialize(TestFileStream); versions.AddLast(version); TestFileStream.Close(); } return(versions); }
private void sync() { String dirPath = conf.targetPath.get(); if (dirPath == null || !Directory.Exists(dirPath)) { throw new DirectoryNotFoundException("Directory in configuration is not valid"); } try { cv = (FBVersion)vb.generate(); }catch (Exception e) { MessageBox.Show(e.Message + "\nThe application will be closed", "Unexpected error"); Environment.Exit(0); } SerializedVersion serV = new SerializedVersion(); serV.encodedVersion = cv.serialize(); threadCallback.Invoke(TypeThread.SYNC, StatusCode.WORKING, "Start syncing"); FileStream fs = null; try { if (server.newTransaction(serV)) { this.status = "Syncing"; byte[][] bfiles = server.getFilesToUpload(); List <FBFile> fileToSync = new List <FBFile>(); foreach (byte[] bf in bfiles) { fileToSync.Add(FBFile.deserialize(bf)); } int i = 0; foreach (FBFile f in fileToSync) { if (!this.stopSync) { threadCallback.Invoke(TypeThread.SYNC, StatusCode.WORKING, "Syncing file " + i + " of " + fileToSync.Count); i++; FBFileClient cf = FBFileClient.generate(f); UploadData cedential = server.uploadFile(); UsefullMethods.SendFile(cedential.ip, cedential.port, cedential.token, new FileStream(cf.FullName, FileMode.Open)); } else { break; } } if (!this.stopSync) { server.commit(); threadCallback.Invoke(TypeThread.SYNC, StatusCode.SUCCESS, "Sync completed"); } else { threadCallback.Invoke(TypeThread.SYNC, StatusCode.ABORTED, "Syncing Stopped"); server.rollback(); } this.status = "Idle"; } else { threadCallback.Invoke(TypeThread.SYNC, StatusCode.IDLE, "Nothing to be done"); } } catch (System.ServiceModel.CommunicationException e) { MessageBox.Show("There is a problem with connection, please retry to login!", "Error in connection"); threadCallback.Invoke(TypeThread.SYNC, StatusCode.ABORTED, "Connection error"); } catch { server.rollback(); } }
private UploadData resetInternals(FBVersion newVersion, FBVersion current) { FBVersion diff = newVersion - current; newVersion.setAbsoluteNameToFile(); if (diff.root != null) { diff.setAbsoluteNameToFile(); } current.setAbsoluteNameToFile(); List <Instruction> instrucionList = new List <Instruction>(); try { File.Delete(user.rootDirectory.FullName + @"\tmp.zip"); } catch { } ZipArchive zip = ZipFile.Open(user.rootDirectory.FullName + @"\tmp.zip", ZipArchiveMode.Update); if (diff.fileList != null) { foreach (FBAbstractElement to in diff.fileList) { bool found = false; foreach (FBAbstractElement from in current.fileList) { if (from.Equals(to)) { found = true; instrucionList.Add(new Instruction(InstructionType.COPY, from.Name, to.Name)); break; } } if (!found) { foreach (PhysicFile ph in realFiles.list) { if (ph.getFBFile().Equals(to)) { if (zip.GetEntry(ph.getRealFileInfo().Name) == null) { zip.CreateEntryFromFile(ph.getRealFileInfo().FullName, ph.getRealFileInfo().Name, CompressionLevel.Optimal); } instrucionList.Add(new Instruction(InstructionType.NEW, ph.getRealFileInfo().Name, to.Name)); } } } } } diff = current - newVersion; if (diff.fileList != null) { //diff.setAbsoluteNameToFile(); foreach (FBAbstractElement toDelete in diff.fileList) { instrucionList.Add(new Instruction(InstructionType.DELETE, toDelete.Name, "")); } } Stream FilesStream = File.OpenWrite(this.user.rootDirectory + @"\instructions.bin"); BinaryFormatter serializer = new BinaryFormatter(); serializer.Serialize(FilesStream, instrucionList); FilesStream.Close(); zip.CreateEntryFromFile(this.user.rootDirectory + @"\instructions.bin", "instructions.bin", CompressionLevel.Optimal); File.Delete(this.user.rootDirectory + @"\instructions.bin"); zip.Dispose(); FilesStream = new FileStream(user.rootDirectory.FullName + @"\tmp.zip", FileMode.Open, FileAccess.Read); string token = Server.GetUniqueKey(20); SecureDownloader sr = new SecureDownloader(this, token, this.ManageCompleteUpload, this.ManageFailedUpload, FilesStream); UInt16 port = sr.port; return(new UploadData(UsefullMethods.GetLocalIPAddress(), port, token)); }