private void SafeDeleteDirectory(string directoryPath) { if (Directory.Exists(directoryPath)) { //try delete whole directory try { _txFileManager.DeleteDirectory(directoryPath); } //Because some folder can be locked by ASP.NET Bundles file monitor we should ignore IOException catch (IOException) { //If fail need to delete directory content first //Files foreach (var file in Directory.EnumerateFiles(directoryPath, "*.*", SearchOption.AllDirectories)) { _txFileManager.Delete(file); } //Dirs foreach (var subDirectory in Directory.EnumerateDirectories(directoryPath, "*", SearchOption.AllDirectories)) { try { _txFileManager.DeleteDirectory(subDirectory); } catch (IOException) { } } //Then try to delete main directory itself try { _txFileManager.DeleteDirectory(directoryPath); } catch (IOException) { } } } }
/// <summary> /// Create the CKAN directory and any supporting files. /// </summary> private void SetupCkanDirectories(bool scan = true) { log.InfoFormat("Initialising {0}", CkanDir()); // TxFileManager knows if we are in a transaction TxFileManager txFileMgr = new TxFileManager(); if (!Directory.Exists(CkanDir())) { User.RaiseMessage("Setting up CKAN for the first time..."); User.RaiseMessage("Creating {0}", CkanDir()); txFileMgr.CreateDirectory(CkanDir()); if (scan) { User.RaiseMessage("Scanning for installed mods..."); Scan(); } } playTime = TimeLog.Load(TimeLog.GetPath(CkanDir())) ?? new TimeLog(); if (!Directory.Exists(InstallHistoryDir())) { User.RaiseMessage("Creating {0}", InstallHistoryDir()); txFileMgr.CreateDirectory(InstallHistoryDir()); } // Clear any temporary files we find. If the directory // doesn't exist, then no sweat; FilesystemTransaction // will auto-create it as needed. // Create our temporary directories, or clear them if they // already exist. if (Directory.Exists(TempDir())) { var directory = new DirectoryInfo(TempDir()); foreach (FileInfo file in directory.GetFiles()) { txFileMgr.Delete(file.FullName); } foreach (DirectoryInfo subDirectory in directory.GetDirectories()) { txFileMgr.DeleteDirectory(subDirectory.FullName); } } log.InfoFormat("Initialised {0}", CkanDir()); }
// Delete group private void cmdDelete_Click(object sender, EventArgs e) { resetSelection(); try { string configPath = Path.Combine(Paths.ConfigPath, Category.Name); string shortcutPath = Path.Combine(Paths.ShortcutsPath, Regex.Replace(Category.Name, @"(_)+", " ") + ".lnk"); var dir = new DirectoryInfo(configPath); try { IFileManager fm = new TxFileManager(); using (TransactionScope scope1 = new TransactionScope()) { fm.DeleteDirectory(configPath); fm.Delete(shortcutPath); //this.Hide(); //this.Dispose(); this.Close(); Client.Reload(); //flush and reload category panels scope1.Complete(); } } catch (Exception) { MessageBox.Show("Please close all programs used within the taskbar group in order to delete!"); return; } } catch (IOException ex) { MessageBox.Show(ex.Message); } Client.Reset(); }
// Save group private void cmdSave_Click(object sender, EventArgs e) { resetSelection(); //List <Directory> directories = if (txtGroupName.Text == "Name the new group...") // Verify category name { lblErrorTitle.Text = "Must select a name"; lblErrorTitle.Visible = true; } else if (IsNew && Directory.Exists(Path.Combine(Paths.ConfigPath, txtGroupName.Text)) || !IsNew && Category.Name != txtGroupName.Text && Directory.Exists(Path.Combine(Paths.ConfigPath, txtGroupName.Text))) { lblErrorTitle.Text = "There is already a group with that name"; lblErrorTitle.Visible = true; } else if (!new Regex("^[0-9a-zA-Z \b]+$").IsMatch(txtGroupName.Text)) { lblErrorTitle.Text = "Name must not have any special characters"; lblErrorTitle.Visible = true; } else if (cmdAddGroupIcon.BackgroundImage == global::client.Properties.Resources.AddWhite) // Verify icon { lblErrorIcon.Text = "Must select group icon"; lblErrorIcon.Visible = true; } else if (Category.ShortcutList.Count == 0) // Verify shortcuts { lblErrorShortcut.Text = "Must select at least one shortcut"; lblErrorShortcut.Visible = true; } else { try { foreach (ProgramShortcut shortcutModifiedItem in shortcutChanged) { if (!Directory.Exists(shortcutModifiedItem.WorkingDirectory)) { shortcutModifiedItem.WorkingDirectory = getProperDirectory(shortcutModifiedItem.FilePath); } } if (!IsNew) { // // Delete old config // string configPath = Path.Combine(Paths.ConfigPath, Category.Name); string shortcutPath = Path.Combine(Paths.ShortcutsPath, Regex.Replace(Category.Name, @"(_)+", " ") + ".lnk"); try { IFileManager fm = new TxFileManager(); using (TransactionScope scope1 = new TransactionScope()) { fm.DeleteDirectory(configPath); fm.Delete(shortcutPath); scope1.Complete(); } } catch (Exception) { MessageBox.Show("Please close all programs used within the taskbar group in order to save!"); return; } } // // Creating new config // //int width = int.Parse(lblNum.Text); Category.Width = int.Parse(lblNum.Text); //Category category = new Category(txtGroupName.Text, Category.ShortcutList, width, System.Drawing.ColorTranslator.ToHtml(CategoryColor), Category.Opacity); // Instantiate category // Normalize string so it can be used in path; remove spaces Category.Name = Regex.Replace(txtGroupName.Text, @"\s+", "_"); Category.CreateConfig(cmdAddGroupIcon.BackgroundImage); // Creating group config files Client.LoadCategory(Path.Combine(Paths.ConfigPath, Category.Name)); // Loading visuals this.Dispose(); Client.Reload(); } catch (IOException ex) { MessageBox.Show(ex.Message); } Client.Reset(); } }
public void Install(IEnumerable <ManifestModuleInfo> modules, IProgress <ProgressMessage> progress) { var isValid = true; //Dependency and version validation foreach (var module in modules.Where(x => !x.IsInstalled)) { //Check platform version if (!module.PlatformVersion.IsCompatibleWith(PlatformVersion.CurrentVersion)) { Report(progress, ProgressMessageLevel.Error, string.Format("Target Platform version {0} is incompatible with current {1}", module.PlatformVersion, PlatformVersion.CurrentVersion)); isValid = false; } //Check that installable version compatible with already installed var alreadyInstalledModule = _moduleCatalog.Modules.OfType <ManifestModuleInfo>().Where(x => x.IsInstalled).FirstOrDefault(x => x.Id.EqualsInvariant(module.Id)); if (alreadyInstalledModule != null && !alreadyInstalledModule.Version.IsCompatibleWithBySemVer(module.Version)) { //Allow downgrade or install not compatible version only if all dependencies will be compatible with installed version var modulesHasIncompatibleDependecies = _moduleCatalog.Modules.OfType <ManifestModuleInfo>() .Where(x => x.IsInstalled) .Where(x => x.DependsOn.Contains(module.Id, StringComparer.OrdinalIgnoreCase)) .Where(x => x.Dependencies.Any(d => !module.Version.IsCompatibleWithBySemVer(d.Version))); if (modulesHasIncompatibleDependecies.Any()) { Report(progress, ProgressMessageLevel.Error, string.Format("{0} is incompatible with installed {1} is required by {2} ", module, alreadyInstalledModule, string.Join(", ", modulesHasIncompatibleDependecies.Select(x => x.ToString())))); isValid = false; } } //Check that dependencies for installable modules var missedDependencies = _moduleCatalog.CompleteListWithDependencies(new[] { module }).OfType <ManifestModuleInfo>() .Where(x => !x.IsInstalled).Except(modules); if (missedDependencies.Any()) { Report(progress, ProgressMessageLevel.Error, string.Format("{0} dependencies required for {1}", string.Join(" ", missedDependencies), module)); isValid = false; } } if (isValid) { var installedModulesIds = _moduleCatalog.Modules.OfType <ManifestModuleInfo>().Where(x => x.IsInstalled).Select(x => x.Id).ToArray(); var updatableModules = modules.Where(x => installedModulesIds.Contains(x.Id)); var installableModules = modules.Except(updatableModules); var changedModulesLog = new List <ManifestModuleInfo>(); using (TransactionScope scope = new TransactionScope()) { try { foreach (var installableModule in installableModules) { Report(progress, ProgressMessageLevel.Info, "Installing '{0}'", installableModule); InnerInstall(installableModule, progress); changedModulesLog.Add(installableModule); installableModule.IsInstalled = true; } foreach (var newModule in updatableModules) { var existModule = _moduleCatalog.Modules.OfType <ManifestModuleInfo>().Where(x => x.IsInstalled && x.Id == newModule.Id).First(); var dstModuleDir = Path.Combine(_modulesPath, existModule.Id); if (Directory.Exists(dstModuleDir)) { _txFileManager.DeleteDirectory(dstModuleDir); } Report(progress, ProgressMessageLevel.Info, "Updating '{0}' -> '{1}'", existModule, newModule); InnerInstall(newModule, progress); existModule.IsInstalled = false; newModule.IsInstalled = true; changedModulesLog.AddRange(new[] { existModule, newModule }); } scope.Complete(); } catch (Exception ex) { Report(progress, ProgressMessageLevel.Error, ex.ToString()); Report(progress, ProgressMessageLevel.Error, "Rollback all changes..."); //Revert changed modules state foreach (var changedModule in changedModulesLog) { changedModule.IsInstalled = !changedModule.IsInstalled; } } } } }
static void RunStressTest() { Stopwatch sw = new Stopwatch(); sw.Start(); { // Pre-test checks string tempDir; IFileManager fm = new TxFileManager(); using (TransactionScope s1 = new TransactionScope()) { tempDir = (new DirectoryInfo(fm.CreateTempDirectory())).Parent.FullName; Console.WriteLine("Temp path: " + tempDir); } string[] directories = Directory.GetDirectories(tempDir); string[] files = Directory.GetFiles(tempDir); if (directories.Length > 0 || files.Length > 0) { Console.WriteLine(string.Format("ERROR Please ensure temp path {0} has no children before running this test.", tempDir)); return; } } // Start each test in its own thread and repeat for a few interations const int numThreads = 10; const int iterations = 250; const string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; long count = 0; IList <Thread> threads = new List <Thread>(); for (int i = 0; i < numThreads; i++) { Thread t = new Thread(() => { IFileManager fm = new TxFileManager(); for (int j = 0; j < iterations; j++) { using (TransactionScope s1 = new TransactionScope()) { TransactionOptions to = new TransactionOptions(); to.Timeout = TimeSpan.FromMinutes(30); long myCount = Interlocked.Increment(ref count); if (myCount % 250 == 0) { Console.WriteLine(myCount + " (" + myCount * 100 / (numThreads * iterations) + " %)"); } string f1 = fm.CreateTempFileName(); string f2 = fm.CreateTempFileName(); string d1 = fm.CreateTempDirectory(); if (i % 100 == 0) { Console.WriteLine(i); } fm.AppendAllText(f1, text); fm.Copy(f1, f2, false); fm.CreateDirectory(d1); fm.Delete(f2); fm.DeleteDirectory(d1); bool b1 = fm.DirectoryExists(d1); bool b2 = fm.FileExists(f1); string f3 = fm.CreateTempFileName(); fm.Move(f1, f3); string f4 = fm.CreateTempFileName(); fm.Snapshot(f4); fm.WriteAllBytes(f4, new byte[] { 64, 65 }); string f5 = fm.CreateTempFileName(); fm.WriteAllText(f5, text); fm.Delete(f1); fm.Delete(f2); fm.Delete(f3); fm.Delete(f4); fm.Delete(f5); fm.DeleteDirectory(d1); s1.Complete(); } } }); threads.Add(t); } foreach (Thread t in threads) { t.Start(); } Console.WriteLine("All threads started."); foreach (Thread t in threads) { t.Join(); } sw.Stop(); Console.WriteLine("All threads joined. Elapsed: {0}.", sw.ElapsedMilliseconds); }
// Moves files from AppData to current folder and vice versa // This is based off of the array below // Index 0 = Current Path // Index 1 = Default Path // Mode 0 = Current path -> Default Path (Turning off) // Mode 1 = Default path -> Current Path (Turning on) private void portibleModeToggle(int mode) { String[,] folderArray = new string[, ] { { Path.Combine(Paths.exeFolder, "config"), Paths.defaultConfigPath }, { Path.Combine(Paths.exeFolder, "Shortcuts"), Paths.defaultShortcutsPath } }; String[,] fileArray = new string[, ] { { Path.Combine(Paths.exeFolder, "Taskbar Groups Background.exe"), Paths.defaultBackgroundPath }, { Path.Combine(Paths.exeFolder, "Settings.xml"), Settings.defaultSettingsPath } }; int int1; int int2; if (mode == 0) { int1 = 0; int2 = 1; } else { int1 = 1; int2 = 0; } try { // Kill off the background process Process[] pname = Process.GetProcessesByName(Path.GetFileNameWithoutExtension("Taskbar Groups Background")); if (pname.Length != 0) { pname[0].Kill(); } IFileManager fm = new TxFileManager(); using (TransactionScope scope1 = new TransactionScope()) { Settings.settingInfo.portableMode = true; Settings.writeXML(); for (int i = 0; i < folderArray.Length / 2; i++) { if (fm.DirectoryExists(folderArray[i, int1])) { // Need to use another method to move from one partition to another Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(folderArray[i, int1], folderArray[i, int2]); // Folders may still reside after being moved if (fm.DirectoryExists(folderArray[i, int1]) && !Directory.EnumerateFileSystemEntries(folderArray[i, int1]).Any()) { fm.DeleteDirectory(folderArray[i, int1]); } } else { fm.CreateDirectory(folderArray[i, int2]); } } for (int i = 0; i < fileArray.Length / 2; i++) { if (fm.FileExists(fileArray[i, int1])) { fm.Move(fileArray[i, int1], fileArray[i, int2]); } } if (mode == 0) { Paths.ConfigPath = Paths.defaultConfigPath; Paths.ShortcutsPath = Paths.defaultShortcutsPath; Paths.BackgroundApplication = Paths.defaultBackgroundPath; Settings.settingsPath = Settings.defaultSettingsPath; portabilityButton.Tag = "n"; portabilityButton.Image = Properties.Resources.toggleOff; } else { Paths.ConfigPath = folderArray[0, 0]; Paths.ShortcutsPath = folderArray[1, 0]; Paths.BackgroundApplication = fileArray[0, 0]; Settings.settingsPath = fileArray[1, 0]; portabilityButton.Tag = "y"; portabilityButton.Image = Properties.Resources.toggleOn; } changeAllShortcuts(); scope1.Complete(); MessageBox.Show("File moving done!"); } } catch (IOException e) { MessageBox.Show("The application does not have access to this directory!\r\n\r\nError: " + e.Message); } }