// Custom Methods private void LoadMaps() { var server = Servers.RegisteredServers.Find(k => k.Name == _targetServer); var dir = Path.Combine(ServerPath.Value, "Maps"); FileActions.VerifyPath(dir, true); var rocketModDirectoryInfo = new DirectoryInfo(dir); foreach (var rocketServer in rocketModDirectoryInfo.GetDirectories()) { Maps.Items.Add(rocketServer.Name); } var workshopMaps = Path.Combine(server.Folder, "Workshop", "Maps"); FileActions.VerifyPath(workshopMaps, true); var folder = new DirectoryInfo(workshopMaps); var content = folder.GetDirectories(); foreach (var mapName in content.SelectMany(item => item.GetDirectories())) { Maps.Items.Add(mapName.Name); } }
public override int Invoke(IEnumerable <string> arguments) { Options.Parse(arguments); config = FileActions.OpenFileFrom(configFilename); if (config == null) { logger.Error($"Did not find or cold not access the file \"{configFilename}\"."); return(0); } publicKey = FindPublicKey(config); privateKey = FindPrivateKey(); if (privateKey == null || publicKey == null) { logger.Error($"Did not find a public key or a private key in {configFilename} or the key dir. Make sure we have the public key in the config file, and the private key as a PEM in the key dir."); return(0); } using (new Stopwatch("Decrypting config")) { encrypt = new Encrypt { PublicKey = publicKey, PrivateKey = privateKey }; Walker.Action = DecryptIf; Walker.FindStringValueByKeys(config.Keys.ToList(), config); } FileActions.SaveFileTo(configFilename, config); return(1); }
public ProjectActions AnalyzeFiles(ProjectActions projectActions, List <string> updatedFiles) { var options = new ParallelOptions() { MaxDegreeOfParallelism = Constants.ThreadCount }; var selectedSourceFileResults = _sourceFileResults.Where(s => updatedFiles.Contains(s.FileFullPath)); Parallel.ForEach(selectedSourceFileResults, options, result => { var fileAction = new FileActions() { FilePath = result.FileFullPath }; if (AnalyzeChildren(fileAction, result.Children, 0)) { var existingFileAction = _projectActions.FileActions.FirstOrDefault(f => f.FilePath == fileAction.FilePath); if (existingFileAction != null) { existingFileAction = fileAction; } else { _projectActions.FileActions.Add(fileAction); } } }); return(_projectActions); }
public void ReadActionFromUnexistingFile() { //Act FileActions newFileActions = new FileActions(unexistingPath); Assert.AreEqual(newFileActions.Read(), null); }
/// <summary> /// Verifies that SteamCMD is present in the installation. Should be called before running SteamCMD.exe or doing /// anything with SteamCMD. /// </summary> private static void VerifySteam() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return; } var inst = Installation.Load(); var steamCmdExe = Path.Combine(inst.InstallationPath, "steamcmd.exe"); try { if (FileActions.VerifyFile(steamCmdExe)) { return; } var zipTarget = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); FileActions.Download(DownloadLink, zipTarget); FileActions.ExtractZip(zipTarget, inst.InstallationPath); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private List <GenericActionExecution> AddActionsWithoutExecutions(FileActions currentFileActions, List <GenericActionExecution> allActions) { var filePath = currentFileActions.FilePath; //We are looking for an action that is in our file actions but has no executions: var actionsWithNoMatch = currentFileActions.AllActions .Where(a => !allActions.Any(runInstance => runInstance.Name == a.Name && runInstance.Type == a.Type && runInstance.Key == a.Key && runInstance.Value == a.Value)); foreach (var action in actionsWithNoMatch) { var genericActionExecution = new GenericActionExecution(action, filePath) { TimesRun = 0 }; allActions.Add(genericActionExecution); } allActions = allActions .GroupBy(a => new { a.Type, a.Name, a.Value }) .Select(g => new GenericActionExecution() { Type = g.First().Type, Name = g.First().Name, Value = g.First().Value, FilePath = filePath, TimesRun = g.Sum(gt => gt.TimesRun), InvalidExecutions = g.Sum(gi => gi.InvalidExecutions) }) .ToList(); return(allActions); }
public ActionsRewriter(SemanticModel semanticModel, SyntaxGenerator syntaxGenerator, FileActions fileActions) { _semanticModel = semanticModel; _syntaxGenerator = syntaxGenerator; _fileActions = fileActions; allActions = new List <GenericActionExecution>(); }
static void Main(string[] args) { FileActions FA = new FileActions(); if (args != null) { if (args[0] == "DriveCheck") { if (FA.checkForSpecificDrive()) { FA.SetDestPathComp(true); } } } else { FA.SetDestPathComp(false); } switch (ConfigurationManager.AppSettings["Usage"].ToLower()) { case "move": Console.WriteLine(FA.RunMoveWorkflow()); break; case "copy": Console.WriteLine(FA.RunCopyWorkflow()); break; default: Console.WriteLine("Function not implemented. Please change \"Usage\"."); break; } }
public void TestOpen() { //Arrange var fs = new MockFileSystem(); const string file = @"C:\my\file.txt"; _ = fs.Directory.CreateDirectory(@"C:\my"); _ = fs.File.Create(file); //Act var f = new FileActions(fs).Open(file, 1, out var e); //Assert Assert.IsTrue(fs.File.Exists(file)); Assert.AreEqual(0, e.AllocationSize); Assert.AreEqual((uint)fs.DirectoryInfo.FromDirectoryName(file).Attributes, e.Attributes); Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(file).LastWriteTimeUtc.ToFileTimeUtc(), e.ChangeTime); Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(file).CreationTimeUtc.ToFileTimeUtc(), e.CreationTime); Assert.AreEqual(0, e.EaSize); Assert.AreEqual(0, e.FileSize); Assert.AreEqual(0, e.HardLinks); Assert.AreEqual(0, e.IndexNumber); Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(file).LastAccessTimeUtc.ToFileTimeUtc(), e.LastAccessTime); Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(file).LastWriteTimeUtc.ToFileTimeUtc(), e.LastWriteTime); Assert.AreEqual(0, e.ReparseTag); Assert.IsTrue(e.IsFile()); }
public EventModel(string itemPath, string source, string target, FileActions fileActions) { FileName = itemPath; SourcePath = source; TargetPath = target; FileActions = fileActions; }
public void TestCreate() { //Arrange var fs = new MockFileSystem(); var file = @"C:\my\file.txt"; fs.Directory.CreateDirectory(@"C:\my"); //Act var s = new FileSecurity(); var fsecurity = s.GetSecurityDescriptorBinaryForm(); _ = new FileActions(fs).Create(file, 1, (uint)FileAttributes.Normal, fsecurity, out var e); //Assert Assert.IsTrue(fs.File.Exists(file)); Assert.AreEqual(0, e.AllocationSize); Assert.AreEqual((uint)fs.DirectoryInfo.FromDirectoryName(file).Attributes, e.Attributes); Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(file).LastWriteTimeUtc.ToFileTimeUtc(), e.ChangeTime); Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(file).CreationTimeUtc.ToFileTimeUtc(), e.CreationTime); Assert.AreEqual(0, e.EaSize); Assert.AreEqual(0, e.FileSize); Assert.AreEqual(0, e.HardLinks); Assert.AreEqual(0, e.IndexNumber); Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(file).LastAccessTimeUtc.ToFileTimeUtc(), e.LastAccessTime); Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(file).LastWriteTimeUtc.ToFileTimeUtc(), e.LastWriteTime); Assert.AreEqual(0, e.ReparseTag); Assert.IsTrue(e.IsFile()); }
// Custom Methods private void LoadInstalled() { AlreadyInstalled.Items.Clear(); var pluginLocation = Path.Combine(_server, "Rocket", "Plugins"); FileActions.VerifyPath(pluginLocation, true); var folder = new DirectoryInfo(pluginLocation); var content = folder.GetFiles("*.dll", SearchOption.TopDirectoryOnly); foreach (var file in content) { AlreadyInstalled.Items.Add(file.Name.Substring(0, file.Name.Length - 4)); } if (AlreadyInstalled.Items.Count == 0) { Delete.Enabled = false; DeleteAll.Enabled = false; Configuration.Enabled = false; _itemId = ""; } else { AlreadyInstalled.SelectedIndex = 0; Delete.Enabled = true; DeleteAll.Enabled = true; Configuration.Enabled = true; } }
private void AddDirectory(object eventArgs) { Status.Text = "Adding directory"; using (var dialog = new FolderBrowserDialog()) { var result = dialog.ShowDialog(); if (result != DialogResult.OK) { return; } _logger.Debug($"GOT :: {result.ToString()}, {dialog.SelectedPath}"); // make sure the directory is not empty as this will kill the CLI if (!FileActions.GetFilesInDirectory(dialog.SelectedPath, SearchOption.AllDirectories).Any()) { _logger.Debug($"Ignoring: '{dialog.SelectedPath}' as the folder is empty"); return; } if (SafeAddAssetFolder(dialog.SelectedPath)) { Status.Text = $"Added: {dialog.SelectedPath}"; CheckMissingAssets(dialog.SelectedPath); } } }
public void ReadActionFromExistingFile() { //Act FileActions newFileActions = new FileActions(filePath); Assert.AreEqual(newFileActions.Read(), fileData); }
public static void Delete(string serverName) { _filePath = $@"config/Server_{serverName}_commands.json"; if (FileActions.VerifyFile(_filePath)) { File.Delete(_filePath); } }
public override void Run() { FileActions.ForEach(action => { action.FileName = FileName + action.FileName; action.Run(); }); }
private void RenameAndCopyFile(string filename, string show) { string checkedFile = filename; string newFile = Path.Combine(ContentDirectory, show); Logging.Log.DebugFormat("Found match for {0} on show {1} and copying to {2}...", checkedFile, show, newFile); FileActions.Copy(checkedFile, newFile); }
public static void Load() { if (RegisteredServers.Count > 0) { return; } var unturnedExec = "Unturned.exe"; var linux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); if (linux) { Console.WriteLine( "You are running USM in linux, please verify that you have SteamCMD installed and that it can be executed from bash, otherwise it will not load."); } for (var i = 0; i <= 10; i++) { if (linux) { unturnedExec = new[] { "Unturned_Headless.x86", "Unturned.x86", "Unturned_Headless.x86_64", "Unturned.x86_64" } .FirstOrDefault(exec => FileActions.VerifyFile(Path.Combine(ServerPath.Value, exec))); if (string.IsNullOrEmpty(unturnedExec)) { unturnedExec = "Unturned_Headless.x86_64"; } } if (FileActions.VerifyFile(Path.Combine(ServerPath.Value, unturnedExec))) { break; } if (i == 10) { Console.WriteLine( "Unable to install correctly unturned in your system. Please verify that you have met all pre-install requirements."); Environment.Exit(0); return; } Updater.ValidateUnturned(); } var serverDirectory = Path.Combine(ServerPath.Value, "Servers"); FileActions.VerifyPath(serverDirectory, true); var serverDirectoryInfo = new DirectoryInfo(serverDirectory); foreach (var server in serverDirectoryInfo.GetDirectories()) { RegisteredServers.Add(Server.Create(server.Name)); } }
private void Configuration_Click(object sender, EventArgs e) { var pluginLocation = Path.Combine(_server, "Rocket", "Plugins", _itemId); if (FileActions.VerifyPath(pluginLocation, false)) { Process.Start(pluginLocation); } }
public RavenFileSystem(InMemoryRavenConfiguration config, string name, TransportState receivedTransportState = null) { ExtensionsState = new AtomicDictionary <object>(); Name = name; ResourceName = string.Concat(Constants.FileSystem.UrlPrefix, "/", name); configuration = config; try { ValidateStorage(); configuration.Container.SatisfyImportsOnce(this); transportState = receivedTransportState ?? new TransportState(); storage = CreateTransactionalStorage(configuration); sigGenerator = new SigGenerator(); fileLockManager = new FileLockManager(); BufferPool = new BufferPool(1024 * 1024 * 1024, 65 * 1024); conflictDetector = new ConflictDetector(); conflictResolver = new ConflictResolver(storage, new CompositionContainer(configuration.Catalog)); notificationPublisher = new NotificationPublisher(transportState); synchronizationTask = new SynchronizationTask(storage, sigGenerator, notificationPublisher, configuration); metricsCounters = new MetricsCountersManager(); search = new IndexStorage(name, configuration); conflictArtifactManager = new ConflictArtifactManager(storage, search); TimerManager = new ResourceTimerManager(); Tasks = new TaskActions(this, Log); Files = new FileActions(this, Log); Synchronizations = new SynchronizationActions(this, Log); AppDomain.CurrentDomain.ProcessExit += ShouldDispose; AppDomain.CurrentDomain.DomainUnload += ShouldDispose; } catch (Exception e) { Log.ErrorException(string.Format("Could not create file system '{0}'", Name ?? "unknown name"), e); try { Dispose(); } catch (Exception ex) { Log.FatalException("Failed to dispose when already getting an error in file system ctor", ex); } throw; } }
private void Delete_Click(object sender, EventArgs e) { var pluginLocation = Path.Combine(_server, "Rocket", "Plugins", _itemId); FileActions.DeleteDirectory(pluginLocation); File.Delete($"{pluginLocation}.dll"); LoadInstalled(); }
/// <summary> /// Initialize a new instance of this class with the specified FILE_NOTIFY_INFORMATION structure. /// </summary> /// <param name="fni"></param> /// <remarks></remarks> internal FileNotifyInfo(FILE_NOTIFY_INFORMATION fni) { _Filename = fni.Filename; _Action = fni.Action; if (fni.NextEntryOffset > 0) { _Next = new FileNotifyInfo(fni.NextEntry); } }
public PluginUI(PluginMain plugin, FDMenus menus, FileActions fileActions, ProjectActions projectActions) { this.plugin = plugin; this.menus = menus; this.Tag = "Project"; this.Text = "Project Explorer"; #region Build TreeView menu = new ProjectContextMenu(menus); menu.Rename.Click += new EventHandler(RenameNode); treeBar = new TreeBar(menus, menu); treeBar.Dock = DockStyle.Top; treeBar.Visible = false; tree = new ProjectTreeView(); tree.Visible = false; tree.Dock = DockStyle.Fill; tree.ImageIndex = 0; tree.ImageList = Icons.ImageList; tree.LabelEdit = true; tree.SelectedImageIndex = 0; tree.ShowRootLines = false; tree.HideSelection = false; tree.ContextMenu = menu; tree.DoubleClick += new EventHandler(tree_DoubleClick); tree.AfterLabelEdit += new NodeLabelEditEventHandler(tree_AfterLabelEdit); tree.BeforeLabelEdit += new NodeLabelEditEventHandler(tree_BeforeLabelEdit); tree.AfterSelect += new TreeViewEventHandler(tree_AfterSelect); this.Controls.Add(tree); this.Controls.Add(treeBar); #endregion #region Instructions LinkLabel link = new LinkLabel(); link.Text = "Create a new project\nor\nOpen an existing project"; link.Links.Add(0, 20, "create"); link.Links.Add(24, 24, "open"); link.LinkClicked += new LinkLabelLinkClickedEventHandler(link_LinkClicked); link.TextAlign = ContentAlignment.MiddleCenter; link.Dock = DockStyle.Fill; link.ContextMenu = new ContextMenu(); this.Controls.Add(link); #endregion // we care about some of these events fileActions.FileCreated += new FileNameHandler(NewFileCreated); fileActions.ProjectModified += new ProjectModifiedHandler(ProjectModified); projectActions.ProjectModified += new ProjectModifiedHandler(ProjectModified); }
private void Delete_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(_itemId)) { FileActions.DeleteDirectory(Path.Combine(_server, "Workshop", "Content", _itemId)); FileActions.DeleteDirectory(Path.Combine(_server, "Workshop", "Maps", _itemId)); } LoadInstalled(); }
private void DeleteAll_Click(object sender, EventArgs e) { var pluginLocation = Path.Combine(_server, "Rocket", "Plugins"); var librariesLocation = Path.Combine(_server, "Rocket", "Libraries"); FileActions.DeleteDirectory(pluginLocation); FileActions.DeleteDirectory(librariesLocation); LoadInstalled(); }
/// <summary> /// Moves a downloaded workshop folder. /// </summary> /// <param name="id">The ID of the workshop folder.</param> /// <param name="directoryDestination">The destination for the workshop folder.</param> public static void MoveWorkshopFolder(string id, string directoryDestination) { var inst = Installation.Load(); var workshopDir = Path.Combine(inst.InstallationPath, "steamapps", "workshop", "content", "304930", id); var mapMeta = Path.Combine(workshopDir, "Map.meta"); var mapsDir = Path.Combine(directoryDestination, "Maps", id); var contentDir = Path.Combine(directoryDestination, "Content", id); FileActions.CopyDirectory(workshopDir, FileActions.VerifyFile(mapMeta) ? mapsDir : contentDir); }
private async Task MakeWorkAsync(string filePath) { _threadCount++; try { if (await _dbInstance.CheckMongoConnection()) { if (!await _dbInstance.IsFileInDbAsync(FileActions.FileHash(filePath))) { var documentTfIdfDict = await DocumentActions.MakeTfIdfVectorAsync( DocumentActions.MakeTfVector(DocumentActions.GetWordCanonedTokens(filePath))); var allDocuments = await _dbInstance.GetAllDocumentsAsync(); var cosineSimilarityList = new List <double>(); var similarityDocuments = new List <PlagiarismDetectExpandedResult>(); foreach (var document in allDocuments) { var currentDocumentTfIdfDict = await DocumentActions.MakeTfIdfVectorAsync( document.DocumentTfVector); var vectors = MakeVectorsForCompare(currentDocumentTfIdfDict, documentTfIdfDict); var cosineSim = Cosine_similarity(vectors.Item1, vectors.Item2); cosineSimilarityList.Add(cosineSim); if (cosineSim >= 0.4) { similarityDocuments.Add(new PlagiarismDetectExpandedResult(document.DocumentPath, document.DocumentName, cosineSim)); } } M_Model.HandledFiles.Add(new PlagiarismDetectResult(Path.GetFileNameWithoutExtension(filePath), cosineSimilarityList.Max() * 100, similarityDocuments)); } else { M_Model.HandledFiles.Add(new PlagiarismDetectResult(Path.GetFileNameWithoutExtension(filePath), 100)); } } } catch (Exception e) { await Console.Error.WriteLineAsync( "Не удалось подключиться к серверу MongoDb! \nВыполнение дальнейшей работы невозможно!\n" + e); StopProgramm(); } _threadCount--; }
private void LoadFiles() { DirectoryInfo d = new DirectoryInfo(Directory); var files = d.GetFiles("*.*").ToList(); files.ForEach(file => { var content = File.ReadAllBytes(file.FullName); FileActions.Add(new ModifyFileAction(file.Name, content)); }); }
internal void Delete() { Shutdown(); while (_instance?.HasExited == false) { } Servers.RegisteredServers.Remove(this); GameConfiguration.Delete(Name); FileActions.DeleteDirectory(Folder); }
private void Reset_Click(object sender, EventArgs e) { var server = Loading.Servers.RegisteredServers.Find(k => k.Name == _selectedServer); if (server == null) { return; } FileActions.DeleteDirectory(Path.Combine(server.Folder, "Players")); FileActions.DeleteDirectory(Path.Combine(server.Folder, "Level")); }
private FileActions GetFileActions_NoLock(string path) { _guard.AssertHasLock(); FileActions actions; if (!_fileActionsMap.TryGetValue(path, out actions)) { actions = new FileActions(this, path); _fileActionsMap.Add(path, actions); } return actions; }
// File manipulation operations protected void ManipulateFile(string file, FileActions action) { FileInfo aFile = new FileInfo(file); switch (action) { case FileActions.CREATE: // Create a blank file if (aFile.Exists) { PrintError(String.Format("File \'{0}\' already exists", file)); } aFile.Create(); break; case FileActions.ERASE: // Erase a file if (!aFile.Exists) { PrintError(String.Format("File \'{0}\' does not exist", file)); } aFile.Delete(); break; } }
public event ErrorDelegate ErrorEvent; // If this is raised, then you have a problem /// <summary> /// Initializes a new instance of the FolderSync class which uses FolderDiff to /// synchronize two folders. Call Sync() to start synchronizing. /// </summary> /// <param name="folderName1">First folder name</param> /// <param name="folderName2">Second folder name</param> /// <param name="defMissingInFolder1">Default action for files which are missing in the first folder.</param> /// <param name="defMissingInFolder2">Default action for files which are missing in the second folder.</param> /// <param name="defDifferentFiles">Default action for files which have different sizes.</param> public FolderSync(string folderName1, string folderName2, FileActions defMissingInFolder1, FileActions defMissingInFolder2, FileActions defDifferentFiles) { if (defMissingInFolder1 == FileActions.OverwriteNewer | defMissingInFolder1 == FileActions.OverwriteOlder | defMissingInFolder1 == FileActions.Write1to2 | // These choices are not valid defMissingInFolder1 == FileActions.Write2to1) { this.initialized = false; if (this.ErrorEvent != null) this.ErrorEvent(new ArgumentException("defaultActionForMissingFiles1 is not correct"), null); } if (defMissingInFolder2 == FileActions.OverwriteNewer | defMissingInFolder2 == FileActions.OverwriteOlder | defMissingInFolder2 == FileActions.Write1to2 | // These choices are not valid defMissingInFolder2 == FileActions.Write2to1) { this.initialized = false; if (this.ErrorEvent != null) this.ErrorEvent(new ArgumentException("defaultActionForMissingFiles2 is not correct"), null); } if (defDifferentFiles == FileActions.Copy) { this.initialized = false; if (this.ErrorEvent != null) this.ErrorEvent(new ArgumentException("defaultActionForDifferentFiles is not correct"), null); } this.defMissing1 = defMissingInFolder1; this.defMissing2 = defMissingInFolder2; this.defSize = defDifferentFiles; this.folderName1 = folderName1; this.folderName2 = folderName2; this.diff = new FolderDiff(this.folderName1, this.folderName2); this.diff.CompareEvent += new CompareDelegate(Compared); }