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)); }
private TreeViewItemFat addItemInRevertList(TreeViewItemFat item) { TreeViewItemFat ret = null; if (item.item.GetType() == typeof(FBDirectory)) { foreach (TreeViewItemFat i in item.Items) { addItemInRevertList(i); } } else { TreeViewItemFat el = findItem(revertList.Items, item); if (el != null) { UsefullMethods.setLabelAlert("danger", errorBox, "File is already in the revert list"); flashItem(el); } else { ret = item.Duplicate(); revertList.Items.Add(ret); item.Select = true; } } return(ret); }
public void RevertWithFileDeletion() { this.TestInitialize(); string[] lines = { "First line", "Second line", "Third line" }; System.IO.File.WriteAllLines(@"asd\ciao\tre.txt", lines); FBVersionBuilder vb = new FBVersionBuilder(rinfo.FullName); FolderBackup.Shared.FBVersion v = (FolderBackup.Shared.FBVersion)vb.generate(); SerializedVersion serV = new SerializedVersion(v.serialize()); server.newTransaction(serV); server.commit(); UploadData ud = server.resetToPreviousVersion(1); UsefullMethods.ReceiveFile(ud.ip, ud.port, ud.token, @"asd\asd.zip"); String ignore; List <Instruction> instructionList = UsefullMethods.ExtractInstructions(@"asd\asd.zip", out ignore); Assert.IsTrue(instructionList.Count == 1); Assert.IsTrue(instructionList[0].cmd == InstructionType.DELETE); Assert.IsTrue(instructionList[0].src == @"ciao\tre.txt"); }
protected override void ServeRequest(Stream ssl) { string token = ""; char[] chars = new char[20]; StreamReader sr = new StreamReader(ssl, Encoding.Default); sr.Read(chars, 0, 20); foreach (char c in chars) { token += c; } if (token != this.token) { if (this.errorEvent != null) { this.errorEvent(this.token); } return; } UsefullMethods.CopyStream(this.fileStream, ssl); ssl.Close(); fileStream.Close(); }
public void Serialize() { MemoryStream ms = new MemoryStream(); BinaryFormatter serializer = new BinaryFormatter(); serializer.Serialize(ms, this); ms.Seek(0, SeekOrigin.Begin); UsefullMethods.SaveStreamToFile(ms, fileName); }
private async void Button_Click(object sender, RoutedEventArgs e) { string username = this.usernameTxtBox.Text; string password = this.paswordTxtBox.Password; if (username.Equals("")) { UsefullMethods.setLabelAlert("danger", this.errorBox, "Missing username! Username field cannot be empty."); return; } if (password.Equals("")) { UsefullMethods.setLabelAlert("danger", this.errorBox, "Missing password! Password field cannot be empty."); return; } string token; BackupServiceClient server = null; try { if (Const <BackupServiceClient> .Instance().get() == null) { server = logIn(username, password, out token); } } catch (LoginExcpetion ex) { UsefullMethods.setLabelAlert("danger", this.errorBox, ex.Message); } if (server != null) { Const <BackupServiceClient> .Instance().set(server); UsefullMethods.setLabelAlert("success", this.errorBox, "Log in succeed!"); conf.userName.set(this.usernameTxtBox.Text); await Task.Delay(500); this.Hide(); string targetPath = conf.targetPath.get(); // if the path is not setted a windows for selecting the path must be shown if (targetPath == null) { WelcomeWindows ww = new WelcomeWindows(); ww.parent = this; ww.Show(); ww.Activate(); } else { TrayiconMode.Instance(); } } }
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; } }
static void Main(string[] args) { UsefullMethods ob = new UsefullMethods(); ob.AddCustomer("Nina", 1); ob.AddProduct("Orange", 20, "Voronezh"); ob.JoinCustomerAndProduct(); ob.GroupByCustomers(); ob.ShowCustomers(); ob.ShowProducts(); }
private async void RegisterButton_Click(object sender, RoutedEventArgs e) { string username = this.usernameTxtBox.Text; string password = this.passwordTxtBox.Password; Config conf = Config.Instance(); if (username.Equals("")) { UsefullMethods.setLabelAlert("danger", this.errorBox, "Missing username! Username field cannot be empty."); return; } if (password.Equals("")) { UsefullMethods.setLabelAlert("danger", this.errorBox, "Missing password! Password field cannot be empty."); return; } BackupServiceClient server = new BackupServiceClient(); string salt; try { salt = server.registerStep1(username); } catch { UsefullMethods.setLabelAlert("danger", this.errorBox, "No internet connection! Check it and retry"); return; } if (salt == null) { UsefullMethods.setLabelAlert("danger", this.errorBox, "Username already choosen! Try another!"); return; } if (server.registerStep2(username, AuthenticationPrimitives.hashPassword(password, salt), salt)) { conf.targetPath.set(null); conf.userName.set(username); UsefullMethods.setLabelAlert("success", this.errorBox, "Registration succeed. You can log in now."); await Task.Delay(500); this.Hide(); this.parent.Activate(); this.parent.Show(); } else { UsefullMethods.setLabelAlert("danger", this.errorBox, "Registration procedure failed!"); } }
private void SendFile(UploadData credential, FileStream fstream) { TcpClient client = new TcpClient(credential.ip, credential.port); SslStream ssl = new SslStream( client.GetStream(), false, new RemoteCertificateValidationCallback(AuthenticationPrimitives.ValidateServerCertificate), null, EncryptionPolicy.RequireEncryption); ssl.AuthenticateAsClient(credential.ip, null, System.Security.Authentication.SslProtocols.Tls12, false); ssl.Write(UsefullMethods.GetBytesFromString(credential.token)); fstream.CopyTo(ssl); ssl.Close(); fstream.Close(); }
public void RollbackTest() { FBVersionBuilder vb = new FBVersionBuilder(rinfo.FullName); FolderBackup.Shared.FBVersion v = (FolderBackup.Shared.FBVersion)vb.generate(); SerializedVersion serV = new SerializedVersion(v.serialize()); Assert.IsTrue(server.newTransaction(serV)); byte[][] bfiles = server.getFilesToUpload(); foreach (byte[] bf in bfiles) { FBFile f = FBFile.deserialize(bf); Assert.IsTrue(v.fileList.Contains(f)); } FBFile file = (FBFile) new FBFileBuilder(@"asd\uno.txt").generate(); string[] lines = { "First line", "Second line", "Third line" }; System.IO.File.WriteAllLines(@"asd\uno.txt", lines); FileStream fstream = new FileStream(@"asd\uno.txt", FileMode.Open, FileAccess.Read); //Assert.AreEqual(server.uploadFile(fstream), file.hash); //fstream.Close(); UploadData credential = server.uploadFile(); UsefullMethods.SendFile(credential.ip, credential.port, credential.token, fstream); file = (FBFile) new FBFileBuilder(@"asd\due.txt").generate(); string[] lines1 = { "First line", "Second line", "Third lines" }; System.IO.File.WriteAllLines(@"asd\due.txt", lines1); fstream = new FileStream(@"asd\due.txt", FileMode.Open, FileAccess.Read); //Assert.AreEqual(server.uploadFile(fstream), file.hash); //fstream.Close(); credential = server.uploadFile(); UsefullMethods.SendFile(credential.ip, credential.port, credential.token, fstream); Assert.IsTrue(server.rollback()); Assert.IsTrue(server.newTransaction(serV)); bfiles = server.getFilesToUpload(); foreach (byte[] bf in bfiles) { FBFile f = FBFile.deserialize(bf); Assert.IsTrue(v.fileList.Contains(f)); } }
private void pathTxtBox_TextChanged(object sender, TextChangedEventArgs e) { if (Directory.Exists(this.pathTxtBox.Text)) { UsefullMethods.setLabelAlert("success", this.errorBox, "Ok!"); } else if (this.PathBoxPlaceholder != this.pathTxtBox.Text && this.pathTxtBox.Text != "") { UsefullMethods.setLabelAlert("danger", this.errorBox, "Selected path does not exists"); } else { UsefullMethods.setLabelAlert("none", this.errorBox, ""); } }
private void TestInitialize() { server = new Server.Server(); AuthenticationData ad = server.authStep1("test1"); token = server.authStep2(ad.token, "test1", AuthenticationPrimitives.hashPassword("test1", ad.salt, ad.token)); CleanUp(); server = new Server.Server(); ad = server.authStep1("test1"); token = server.authStep2(ad.token, "test1", AuthenticationPrimitives.hashPassword("test1", ad.salt, ad.token)); string[] lines = { "First line", "Second line", "Third line" }; string[] lines1 = { "First line", "Second line", "Third lines" }; System.IO.Directory.CreateDirectory("asd"); System.IO.Directory.CreateDirectory(@"asd\ciao"); rinfo = new DirectoryInfo("asd"); System.IO.File.WriteAllLines(@"asd\uno.txt", lines); System.IO.File.WriteAllLines(@"asd\due.txt", lines1); System.IO.File.WriteAllLines(@"asd\ciao\due.txt", lines); FBVersionBuilder vb = new FBVersionBuilder(rinfo.FullName); FolderBackup.Shared.FBVersion v = (FolderBackup.Shared.FBVersion)vb.generate(); SerializedVersion serV = new SerializedVersion(v.serialize()); server.newTransaction(serV); byte[][] bfiles = server.getFilesToUpload(); FBFile file = (FBFile) new FBFileBuilder(@"asd\uno.txt").generate(); FileStream fstream = new FileStream(@"asd\uno.txt", FileMode.Open, FileAccess.Read); UploadData credential = server.uploadFile(); UsefullMethods.SendFile(credential.ip, credential.port, credential.token, fstream); fstream.Close(); file = (FBFile) new FBFileBuilder(@"asd\due.txt").generate(); fstream = new FileStream(@"asd\due.txt", FileMode.Open, FileAccess.Read); credential = server.uploadFile(); UsefullMethods.SendFile(credential.ip, credential.port, credential.token, fstream); Assert.IsTrue(server.commit()); }
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")); }
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 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 UploadData uploadFile() { this.checkAuthentication(); this.checkTransactionIsEnabled(); if (uploadedFiles == null) { return(null); } string token = Server.GetUniqueKey(20); SecureUploader channel = new SecureUploader(this, token, this.ManageCompleteUpload, this.ManageFailedUpload); UInt16 port = channel.port; this.channels.TryAdd(token, channel); return(new UploadData(UsefullMethods.GetLocalIPAddress(), port, token)); }
private void preview_Click(object sender, RoutedEventArgs e) { TreeViewItemFat seletedItem = (TreeViewItemFat)versionView.SelectedItem; string filePath = null; try { filePath = se.getFile((FBFile)seletedItem.item); System.Diagnostics.Process.Start(filePath); } catch (System.ServiceModel.CommunicationException) { UsefullMethods.setLabelAlert("danger", errorBox, "Error with communication! Check your connection!"); } catch { UsefullMethods.setLabelAlert("danger", errorBox, "No file selected!"); } }
public SecureChannel(Server server, string token, NotifyReceiveComplete completeEvent, NotifyErrorReceiving errorEvent) { if (certificate == null) { System.Console.WriteLine(Directory.GetCurrentDirectory()); certificate = new X509Certificate2("Certificates\\certificate.pfx", "malnati"); } this.token = token; this.server = server; this.listener = new TcpListener(IPAddress.Any, UsefullMethods.GetAvailablePort(30000)); this.thread = new Thread(this.ThreadCode); this.errorEvent = errorEvent; this.completeEvent = completeEvent; this.start = new AutoResetEvent(false); this.clientConnected = new AutoResetEvent(false); this.thread.Start(); }
public void RevertWithNewFile() { this.TestInitialize(); string[] lines = { "First line", "Second line", "Third line", "Fourth line" }; System.IO.File.WriteAllLines(@"asd\ciao\tre.txt", lines); FBVersionBuilder vb = new FBVersionBuilder(rinfo.FullName); FolderBackup.Shared.FBVersion v = (FolderBackup.Shared.FBVersion)vb.generate(); SerializedVersion serV = new SerializedVersion(v.serialize()); server.newTransaction(serV); FileStream fstream = new FileStream(@"asd\ciao\tre.txt", FileMode.Open, FileAccess.Read); server.getFilesToUpload(); UploadData credential = server.uploadFile(); UsefullMethods.SendFile(credential.ip, credential.port, credential.token, fstream); server.commit(); System.IO.File.Delete(@"asd\ciao\tre.txt"); vb = new FBVersionBuilder(rinfo.FullName); v = (FolderBackup.Shared.FBVersion)vb.generate(); serV = new SerializedVersion(v.serialize()); server.newTransaction(serV); server.commit(); UploadData ud = server.resetToPreviousVersion(1); UsefullMethods.ReceiveFile(ud.ip, ud.port, ud.token, @"asd\asd.zip"); String ignore; List <Instruction> instructionList = UsefullMethods.ExtractInstructions(@"asd\asd.zip", out ignore); Assert.IsTrue(instructionList.Count == 1); Assert.IsTrue(instructionList[0].cmd == InstructionType.NEW); Assert.IsTrue(instructionList[0].dst == @"ciao\tre.txt"); }
private void uploadFile(Stream fileStream) { string path = this.server.user.rootDirectory.FullName + "\\" + DateTime.UtcNow.ToString("yyyy_MM_dd_HH_mm_ss_fff", CultureInfo.InvariantCulture); FBFile newFile; FBFileBuilder fb; UsefullMethods.SaveStreamToFile(fileStream, path); fb = new FBFileBuilder(path); newFile = (FBFile)fb.generate(); if (!this.server.necessaryFiles.Contains(newFile)) { File.Delete(path); this.errorEvent(token); return; } this.completeEvent(newFile, new PhysicFile(newFile, path), token); }
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)); }