public void Execute(string basePath, string projects, string pattern, bool overwrite) { var projectFiles = DirectoryExtensions.LoadFiles(basePath, projects); foreach (var projectFile in projectFiles) { XDocument doc = XDocument.Load(Path.Combine(basePath, projectFile)); var regex = new Regex(pattern); var imports = doc.Root.Descendants() .Where(item => item.Name.LocalName == "Import" && regex.IsMatch(item.Attribute("Project")?.Value)) .ToList(); if (overwrite && imports.Count > 0) { Logger.Info($"Removing imports from project: {projectFile}"); imports.ForEach(item => { Logger.Info($"Removing import {item.Attribute("Project")?.Value} in {projectFile}"); item.Remove(); }); doc.Save(Path.Combine(basePath, projectFile)); } } }
public static void DeleteDirectoryRecursively(string path) { if (Directory.Exists(path)) { DirectoryExtensions.DeleteRecursively(path); } }
public void GetDirectorySize_WithEmptyPath() { var actual = DirectoryExtensions.GetDirectorySize("", SearchOption.AllDirectories).Bytes; //Assert actual.Should().Be(0); }
/// <summary> /// Attempt to extract a stream from an archive /// </summary> /// <param name="entryName">Name of the entry to be extracted</param> /// <param name="realEntry">Output representing the entry name that was found</param> /// <returns>MemoryStream representing the entry, null on error</returns> public virtual (MemoryStream, string) CopyToStream(string entryName) { MemoryStream ms = new MemoryStream(); string realentry = null; // Copy single file from the current folder to the output directory, if exists try { // Make sure the folders exist Directory.CreateDirectory(this.Filename); // Get all files from the input directory List <string> files = DirectoryExtensions.GetFilesOrdered(this.Filename); // Now sort through to find the first file that matches string match = files.Where(s => s.EndsWith(entryName)).FirstOrDefault(); // If we had a file, copy that over to the new name if (!string.IsNullOrWhiteSpace(match)) { FileExtensions.TryOpenRead(match).CopyTo(ms); realentry = match; } } catch (Exception ex) { logger.Error(ex); return(ms, realentry); } return(ms, realentry); }
/// <summary> /// Initialize service classes for working with our windows service /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void MainForm_Load(object sender, EventArgs e) { servicesOperations = new Serviceinstaller( ConfigurationManager.AppSettings["ExecutableName"], ConfigurationManager.AppSettings["ServiceKnownName"], ConfigurationManager.AppSettings["ServiceProjectFolder"]); var serviceName = ConfigurationManager.AppSettings["ServiceKnownName"] ?? throw new ArgumentNullException("ServiceKnownName not set"); this.Text = $"{serviceName}: utility"; // create a manual uninstall batch file if (Environment.UserName != "Karens") { DirectoryExtensions.CreateManualUninstallBatchFile( servicesOperations.ServiceFolder, servicesOperations.ServiceExecutableName); } utilityOperations = new WindowsServices(); if (servicesOperations.ProceedWithOperations == false) { // disable all buttons except for the close button as // we can not continue because either the install executable or // the service executable were not found. Controls.OfType <Button>() .Where(button => button.Name != "applicationCloseButton") .ToList() .ForEach(button => button.Enabled = false); } }
public void Add(SearchScope scope, SearchBy searchBy, Operator op, string searchText) { var searchPredicate = HookExtensions.FormatSearchClause <T>(searchBy, op, searchText); switch (scope) { case SearchScope.ExecutingAssembly: _hook.AddRange(Assembly.GetExecutingAssembly().GetHooks <T>(searchPredicate)); break; case SearchScope.EntryAssembly: _hook.AddRange(Assembly.GetEntryAssembly().GetHooks <T>(searchPredicate)); break; case SearchScope.CallingAssembly: _hook.AddRange(Assembly.GetCallingAssembly().GetHooks <T>(searchPredicate)); break; case SearchScope.CurrentDirectory: List <Assembly> assemblies = DirectoryExtensions.GetAssemblies(Environment.CurrentDirectory, "*.dll"); assemblies.AddRange(DirectoryExtensions.GetAssemblies(Environment.CurrentDirectory, "*.exe")); foreach (var item in assemblies) { _hook.AddRange(item.GetHooks(searchPredicate)); } break; default: throw new InvalidOperationException("Invalid SearchScope: " + scope); } }
// ReSharper enable InconsistentNaming private Logger() { DirectoryExtensions.CreateDirectoryIfNotExists(Folder); // Will create file if one does not exist, otherwise opens existing file fs = new FileStream(FileFullName, FileMode.Append, FileAccess.Write, FileShare.None); sw = new StreamWriter(fs, Encoding.UTF8); }
private static void Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(DirectoryExtensions.GetCurrentDirectory()) .AddJsonFile("settings.json", optional: true, reloadOnChange: true); var configuration = builder.Build(); var services = new ServiceCollection() .AddSchedulerServices(configuration) .BuildServiceProvider(); LoggerExtensions.CreateLogger("Scheduler"); HostFactory.Run(config => { config.Service <SchedulerHostedService>(s => { s.ConstructUsing(service => services.GetService <SchedulerHostedService>()); s.WhenStarted(async service => await service.StartAsync(CancellationToken.None)); s.WhenStopped(async service => await service.StopAsync(CancellationToken.None)); }); config.RunAsLocalSystem(); config.StartAutomatically(); config.SetDescription("Scheduler (Topshelf Service)"); config.SetDisplayName("HiQoScheduler"); config.SetServiceName("HiQoScheduler"); }); }
public void Teardown() { this.gitRepository.Dispose(); this.gitRepositoryOriginHandle.Dispose(); DirectoryExtensions.DeleteCompletely(GlobalTestConstants.TemporaryTestDataPath); }
public override void ProcessFeatures(Dictionary <string, Feature> features) { base.ProcessFeatures(features); // Get feature flags string olddat = GetString(features, OldStringValue); string outdat = GetString(features, OutStringValue); string newdat = GetString(features, NewStringValue); // Ensure the output directory DirectoryExtensions.Ensure(outdat, create: true); // Check that all required files exist if (!File.Exists(olddat)) { logger.Error($"File '{olddat}' does not exist!"); return; } if (!File.Exists(newdat)) { logger.Error($"File '{newdat}' does not exist!"); return; } // Create the encapsulating datfile DatFile datfile = DatFile.CreateAndParse(olddat); // Diff against the new datfile DatFile intDat = DatFile.CreateAndParse(newdat); datfile.DiffAgainst(intDat, false); intDat.Write(outdat); }
private static async Task CleanupServers() { await Task.Run(() => { Log.Informational("Server Clean Up - Initiated..."); foreach (string dir in Directory.EnumerateDirectories(Program.GameServersDirectory)) { Log.Verbose($"Server Clean Up - Found Directory: {dir}"); // get full directory info of target DirectoryInfo directoryInfo = new DirectoryInfo(dir); // if the folder name only contains digits, it matches our norm.. if (directoryInfo.Name.IsDigitsOnly()) { // get integer value of id int gsID = Convert.ToInt32(directoryInfo.Name); // do we NOT have a server with this id? if (!PreAPIHelper.Servers.Exists(x => x.ID == gsID)) { // delete the folder, we don't manage this Log.Informational($"Server Cleanup: Deleting Directory {directoryInfo.FullName}"); DirectoryExtensions.DeleteOrTimeout(directoryInfo.FullName); } else { Log.Verbose($"Server Clean Up - This directory is being managed, ignoring."); } } else { Log.Verbose($"Server Clean Up - Directory doesn't match our system, ignoring."); } } }); }
public static void ReplaceCurrentChapter(string chapterName) { string chapterDirectory = GetChapterDirectory(chapterName); ClearCurrentSave(); DirectoryExtensions.CopyAll(chapterDirectory, CurrentSavePath); }
public override void ProcessFeatures(Dictionary <string, Feature> features) { base.ProcessFeatures(features); // Get feature flags string name = GetString(features, NameStringValue); string description = GetString(features, DescriptionStringValue); string source = GetString(features, SourceStringValue); string outdat = GetString(features, OutStringValue); // Ensure the output directory DirectoryExtensions.Ensure(outdat, create: true); // Check that all required directories exist if (!Directory.Exists(source)) { logger.Error($"File '{source}' does not exist!"); return; } // Create and write the encapsulating datfile DatFile datfile = DatFile.Create(); datfile.Header.Name = string.IsNullOrWhiteSpace(name) ? "untitled" : name; datfile.Header.Description = description; datfile.PopulateFromDir(source, asFiles: TreatAsFile.NonArchive); datfile.ApplyCleaning(new Cleaner() { ExcludeFields = Hash.DeepHashes.AsFields() }); datfile.Write(outdat); }
/// <summary> /// Moves the client parent directory. /// </summary> /// <param name="destination">Destination directory of the clients.</param> public void MoveClientParentDirectory(string destination) { // Create the parent directory. var existingParentDirectory = this.systemInfo.SystemFileLocation; Directory.CreateDirectory(destination); foreach (var manifestEntry in this.Patcher.Manifest.Manifest) { manifestEntry.EntryDirectory = manifestEntry.EntryDirectory.Replace(existingParentDirectory.Replace("\\", "/"), destination.Replace("\\", "/")); } this.Patcher.Manifest.Save(); // Set the parent directory. this.systemInfo.Settings.ClientParentLocation = destination; this.systemInfo.SaveSettings(); // Move the clients. foreach (var clientDirectory in Directory.GetDirectories(existingParentDirectory)) { var clientDirectoryName = new DirectoryInfo(clientDirectory).Name; if (File.Exists(Path.Combine(clientDirectory, "legouniverse.exe"))) { DirectoryExtensions.Move(clientDirectory, Path.Combine(destination, clientDirectoryName)); } } // Reload the patches. this.Patcher = new ClientPatcher(systemInfo); }
public void Load(string path) { var fileNameNotValid = false; var files = Directory.GetFiles(SpecialFolder.BlueprintThumbnails.GetPath(), "*.png"); for (int i = 0; i < files.Length; i++) { var texture = DirectoryExtensions.LoadPNG(files[i], WIDTH, HEIGHT); int hashKey; var name = Path.GetFileNameWithoutExtension(files[i]); var valid = int.TryParse(name, out hashKey); if (valid) { base[hashKey] = Sprite.Create( texture, new Rect(0f, 0f, 800, 800), new Vector2(0.5f, 0.5f)); } else { Debug.LogError($"file name not valid"); } } if (fileNameNotValid) { NoticeManager.Instance.Prompt("Incorrect files found in thumbnails folder. Stay the f**k away :)"); } Loaded?.Invoke(); }
/// <summary> /// Attempt to extract a file from an archive /// </summary> /// <param name="entryName">Name of the entry to be extracted</param> /// <param name="outDir">Output directory for archive extraction</param> /// <returns>Name of the extracted file, null on error</returns> public virtual string CopyToFile(string entryName, string outDir) { string realentry = null; // Copy single file from the current folder to the output directory, if exists try { // Make sure the folders exist Directory.CreateDirectory(this.Filename); Directory.CreateDirectory(outDir); // Get all files from the input directory List <string> files = DirectoryExtensions.GetFilesOrdered(this.Filename); // Now sort through to find the first file that matches string match = files.Where(s => s.EndsWith(entryName)).FirstOrDefault(); // If we had a file, copy that over to the new name if (!string.IsNullOrWhiteSpace(match)) { realentry = match; File.Copy(match, Path.Combine(outDir, entryName)); } } catch (Exception ex) { logger.Error(ex); return(realentry); } return(realentry); }
private static void SaveProblem(byte[] Data, out int ProblemID, out DateTime LastModifiedTime) { Int32 FileNameLength = BitConverter.ToInt32(Data, 8); string FileName = Encoding.ASCII.GetString(Data, 12, FileNameLength); int id; Int32.TryParse(Path.GetFileNameWithoutExtension(FileName), out id); ProblemID = id; LastModifiedTime = DateTime.MinValue; try { if (!Directory.Exists(LocalPath.ProblemsDirectory)) { Directory.CreateDirectory(LocalPath.ProblemsDirectory); } if (File.Exists(LocalPath.ProblemsDirectory + FileName + ".zip")) { File.Delete(LocalPath.ProblemsDirectory + FileName + ".zip"); } if (Directory.Exists(LocalPath.ProblemsDirectory + ProblemID.ToString())) { DirectoryExtensions.Delete(LocalPath.ProblemsDirectory + ProblemID.ToString()); } using (BinaryWriter bw = new BinaryWriter( File.Open(LocalPath.ProblemsDirectory + FileName + ".zip", FileMode.Create))) { bw.Write(Data, FileNameLength + 12, Data.Length - FileNameLength - 12); } ZipFile.ExtractToDirectory( LocalPath.ProblemsDirectory + FileName + ".zip", LocalPath.ProblemsDirectory + ProblemID.ToString()); File.Delete(LocalPath.ProblemsDirectory + FileName + ".zip"); double timeLimit; int memoryLimit; string name; DateTime lastModifiedTime; ProblemLegend.Read(LocalPath.ProblemsDirectory + ProblemID.ToString(), out name, out timeLimit, out memoryLimit, out lastModifiedTime); LastModifiedTime = lastModifiedTime; logger.Debug("Problem {0} saved", ProblemID); if (logger.IsDebugEnabled) { Console.WriteLine(DateTime.Now.ToString(culture) + " - Problem {0} saved", ProblemID); } } catch (Exception ex) { logger.Error("Error occurred on problem {0} saving: {1}", ProblemID, ex.Message); Console.WriteLine(DateTime.Now.ToString(culture) + " - Error occurred on problem {0} saving: {1}", ProblemID, ex.Message); throw; } }
public void SafeEnumerateDirectories_PathIsNull() { //Act var actual = DirectoryExtensions.SafeEnumerateDirectories(null); //Assert actual.Should().BeEmpty(); }
static void PurgeDialectDirs(string scriptPath) { foreach (var dialect in Enum.GetNames(typeof(BuildSqlDialect))) { var dialectDirectory = Path.Combine(scriptPath, dialect); DirectoryExtensions.Delete(dialectDirectory); } }
public void SafeEnumerateFiles_PathIsEmpty() { //Act var actual = DirectoryExtensions.SafeEnumerateFiles(""); //Assert actual.Should().BeEmpty(); }
public void CreateDirectoryIfDoesntExistsDoesNotFailWithExistingDirectoryTest() { string directory = Directory.GetCurrentDirectory(); Assert.IsTrue(Directory.Exists(directory)); DirectoryExtensions.CreateDirectoryIfDoesntExists(directory); Assert.IsTrue(Directory.Exists(directory)); }
public void Execute(string solutionFile, string pattern, bool overwrite, bool inSolutionProjectsOnly = false) { var solutionDirectory = Path.GetDirectoryName(solutionFile); if (string.IsNullOrEmpty(solutionDirectory)) { solutionDirectory = Directory.GetCurrentDirectory(); } // Load solution file var solution = SolutionFile.Parse(Path.GetFullPath(solutionFile)); // Include only projects in solution file List <string> projectFiles; if (inSolutionProjectsOnly) { projectFiles = solution.ProjectsInOrder .Where(item => item.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat) .Select(item => item.RelativePath) .ToList(); } else { // Search glob file patterns projectFiles = DirectoryExtensions.LoadFiles(solutionDirectory, pattern); } foreach (var item in projectFiles) { // Load project file var projectDirectory = Path.Combine(solutionDirectory, item); var project = MsBuildExtensions.LoadProject(projectDirectory); try { var isDirty = UpdateProjectReference(solution, project); if (isDirty) { if (overwrite) { Logger.Info($"Project reference for {item} updated"); project.Save(); } else { Logger.Info($"Project reference for {item} can be updated with --write flag"); } } } catch (Exception e) { // output some error message Logger.Error($"Error updating project reference for project {item}"); Logger.Error(e.Message); } } }
/// <summary> /// Detect header skipper compliance and create an output file /// </summary> /// <param name="file">Name of the file to be parsed</param> /// <param name="outDir">Output directory to write the file to, empty means the same directory as the input file</param> /// <param name="nostore">True if headers should not be stored in the database, false otherwise</param> /// <returns>True if the output file was created, false otherwise</returns> public static bool DetectTransformStore(string file, string outDir, bool nostore) { // Create the output directory if it doesn't exist DirectoryExtensions.Ensure(outDir, create: true); logger.User($"\nGetting skipper information for '{file}'"); // Get the skipper rule that matches the file, if any SkipperRule rule = GetMatchingRule(file, string.Empty); // If we have an empty rule, return false if (rule.Tests == null || rule.Tests.Count == 0 || rule.Operation != HeaderSkipOperation.None) return false; logger.User("File has a valid copier header"); // Get the header bytes from the file first string hstr; try { // Extract the header as a string for the database #if NET_FRAMEWORK using (var fs = FileExtensions.TryOpenRead(file)) { #else using var fs = FileExtensions.TryOpenRead(file); #endif byte[] hbin = new byte[(int)rule.StartOffset]; fs.Read(hbin, 0, (int)rule.StartOffset); hstr = Utilities.ByteArrayToString(hbin); #if NET_FRAMEWORK } #endif } catch { return false; } // Apply the rule to the file string newfile = (string.IsNullOrWhiteSpace(outDir) ? Path.GetFullPath(file) + ".new" : Path.Combine(outDir, Path.GetFileName(file))); rule.TransformFile(file, newfile); // If the output file doesn't exist, return false if (!File.Exists(newfile)) return false; // Now add the information to the database if it's not already there if (!nostore) { BaseFile baseFile = FileExtensions.GetInfo(newfile, hashes: Hash.SHA1, asFiles: TreatAsFile.NonArchive); DatabaseTools.AddHeaderToDatabase(hstr, Utilities.ByteArrayToString(baseFile.SHA1), rule.SourceFile); } return true; }
public async Task Unsubscribe(string path, string pattern = null) { string filter; var normalizedFolder = PathExtensions.NormalizePath(path); using (new UpgradeableReadLockCookie(_subscriptionLock)) { if (!_watchers.TryGetValue(normalizedFolder, out var watcher)) { Debug.WriteLine($"No subscribed watchers for \"{path}\". Thread = {Thread.CurrentThread.ManagedThreadId}"); return; } filter = string.IsNullOrWhiteSpace(pattern) ? DefaultFilePattern : watcher.Filters.FirstOrDefault(x => x.Equals(pattern, StringComparison.InvariantCultureIgnoreCase)); using (new WriteLockCookie(_subscriptionLock)) { if (filter != null) { watcher.Filters.Remove(filter); } if (string.IsNullOrWhiteSpace(pattern) || !watcher.Filters.Any()) { _watchers.Remove(normalizedFolder); UnsubscribeWatcher(watcher); } } } if (!string.IsNullOrWhiteSpace(filter)) { var tasks = new List <Task>(); using (new WriteLockCookie(_queueLock)) { tasks.AddRange(DirectoryExtensions .GetFilesSafe(normalizedFolder, filter) .Select(x => { var normalizedFile = PathExtensions.NormalizePath(x); _backgroundTaskQueue.CancelTasks(normalizedFile); return(_backgroundTaskQueue.QueueTask(normalizedFolder, () => { Debug.WriteLine($"Removing index for \"{x}\". Thread = {Thread.CurrentThread.ManagedThreadId}"); Indexer.Remove(normalizedFile); })); })); } await Task.WhenAll(tasks).IgnoreExceptions(); await Task.Yield(); } }
public void SafeEnumerateDirectories_WithSearchOptions() { var basePath = GetTempTestDirectory(); var expected = CreateTestDirectories(basePath, "Temp1", "Tmp2", @"Tmp3\Temp3_1", @"Tmp3\Temp3_2"); //Act var actual = DirectoryExtensions.SafeEnumerateDirectories(basePath, SearchOption.AllDirectories).ToList(); //Assert actual.Should().Contain(expected); }
public void SafeEnumerateFiles_WithSearchOptions() { var basePath = GetTempTestDirectory(); var expected = CreateTestFiles(basePath, new TestFile("abc.sef"), new TestFile("def.def"), new TestFile(@"Temp1\ghi.def"), new TestFile(@"Temp2\jkl.sef")); //Act var actual = DirectoryExtensions.SafeEnumerateFiles(basePath, SearchOption.AllDirectories); //Assert actual.ToList().Should().Contain(expected); }
static void Promote(string replicationPath, string scriptPath) { try { PurgeDialectDirs(replicationPath); DirectoryExtensions.DuplicateDirectory(scriptPath, replicationPath); } catch (Exception exception) { throw new ErrorsException($"Failed to promote scripts to '{replicationPath}'. Error: {exception.Message}"); } }
public override void ProcessFeatures(Dictionary <string, Feature> features) { base.ProcessFeatures(features); // Get only files from the inputs List <ParentablePath> files = DirectoryExtensions.GetFilesOnly(Inputs); foreach (ParentablePath file in files) { Transform.RestoreHeader(file.CurrentPath, OutputDir); } }
public async Task <ActionResult> PublishCalendars() { string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value; // Get a token for calling the Windows Azure Active Directory Graph AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, LoginUrl, tenantId)); ClientCredential credential = new ClientCredential(AppPrincipalId, AppKey); AuthenticationResult assertionCredential = authContext.AcquireToken(GraphUrl, credential); string authHeader = assertionCredential.CreateAuthorizationHeader(); string requestUrl = String.Format( CultureInfo.InvariantCulture, GraphUsersByTenantUrl, HttpUtility.UrlEncode(tenantId)); HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl); request.Headers.TryAddWithoutValidation("Authorization", authHeader); HttpResponseMessage response = await client.SendAsync(request); string responseString = await response.Content.ReadAsStringAsync(); UserContext userCtx = JsonConvert.DeserializeObject <UserContext>(responseString); List <UserDetails> usersInTenant = new List <UserDetails>(userCtx.value); List <UserDetails> usersWithCalendar = new List <UserDetails>(); //Since the extension name isn't known in advance it's not included in the default serialization, //so we extract it manually after looking up the name. string appObjectId = await DirectoryExtensions.getAppObjectId(tenantId, authHeader); string extensionName = string.Empty; extensionName = await DirectoryExtensions.checkExtensionRegistered(tenantId, authHeader, appObjectId, "PublishedCalendarUrl"); foreach (var user in usersInTenant) { //If a user doesn't have an Office 365 plan we can't use their calendar so we exclude them from the list if (user.assignedPlans.Count > 0) { //If a user isn't assigned to the "Exchange" plan they don't have a calendar either var exchangePlan = user.assignedPlans.Exists(e => e.service.Contains("exchange")); if (exchangePlan) { user.PublishedCalendarUrl = await DirectoryExtensions.getExtensionValue(tenantId, authHeader, user.userPrincipalName, extensionName); usersWithCalendar.Add(user); } } } return(View(usersWithCalendar)); }
public static bool CopyDirectory(string source, string target, bool overwrite = false, bool recursive = true) { _logger.Trace($"CopyDirectory({source}, {target}, {overwrite}, {recursive}"); if (string.IsNullOrEmpty(source)) { throw new ArgumentNullException(nameof(source)); } if (string.IsNullOrEmpty(target)) { throw new ArgumentNullException(nameof(target)); } if (!Path.IsPathRooted(source)) { source = Path.Combine(DeploymentEnvironmentVariables.FilesDirectory, source); _logger.Trace($"Source path was a non absolute path. Changed path to '{source}'"); } if (!Path.IsPathRooted(target)) { target = Path.GetFullPath(target); _logger.Trace($"Target path was a non absolute path. Changed path to '{target}'"); } if (!Directory.Exists(source)) { _logger.Warn($"Source directory was not found in '{source}' or is not a directory"); return(false); } if (!overwrite && Directory.Exists(target)) { _logger.Info($"Overwrite not specified but target directory exists. Not copying '{source}' to '{target}'"); return(false); } else if (overwrite && Directory.Exists(target)) { _logger.Info($"Target directory exists. Deleting '{target}'"); try { Directory.Delete(target, recursive); } catch (IOException ex) { // If recursive is set to false and the directory has subfolders, then this exception is thrown. Therefor exit ... _logger.Warn(ex, $"Target directory exists and has subfolder or files. Recursive parameter was not specified. Aborting ..."); return(false); } } DirectoryExtensions.Copy(source, target); return(true); }