private static void LaunchRecursionDemo() { //Inserire il percorso di partenza Console.Write("Percorso base da cui partire per la ricerca dei file: "); string basePath = Console.ReadLine(); Console.Write("Estensione dei file da cercare (es. 'cs'): "); string extension = Console.ReadLine(); Console.Write("Seconda estensione dei file da cercare (es. 'csproj'): "); string secondExtension = Console.ReadLine(); //Creo istanza di FileSystemHandler FileSystemHandler handler = new FileSystemHandler(); //Evento da gestire // - "+=" è l'aggiunta della gestione dell'evento // - dopo il "+=" c'è il DELEGATO handler.FileWithSecondExtensionFound += Handler_FileWithSecondExtensionFound; //Evento di inizio ricerca in directory handler.SearchInDirectoryStarted += Handler_SearchInDirectoryStarted; //Avvio la procedura sul percorso base handler.ListAllFilesWithProvidedExtension( basePath, new string[] { extension, secondExtension }); }
/// <summary> /// Process the files. /// </summary> /// <param name="options">The parsed options.</param> private static void ProcessFiles(Options options) { WorkflowWriter.WriteLine(options.ToString()); IFileSystem fileSystem = new FileSystemHandler(); IWorkflow parse = new ParseWorkflow(fileSystem); IWorkflow validation = new ValidateWorkflow(fileSystem); IWorkflow filterWorkflow = new FilterWorkflow(); IWorkflow process = new ProcessWorkflow(filterWorkflow); IWorkflow target = new TargetWorkflow(); IWorkflow copy = new CopyWorkflow(fileSystem); IWorkflow mainworkflow = new MainWorkflow( parse, validation, process, target, copy); try { var result = mainworkflow.Process(options, Array.Empty <AstroFile>()); } catch (Exception ex) { WorkflowWriter.WriteLine($"Error encountered: {ex.Message}."); } return; }
// 登入消息处理 public static bool login(string account, string password, string ip, string port) { try { string homeFolder = CommonStaticVariables.homePath + account; string selectCmdStr = "SELECT * FROM tb_accounts WHERE account = '" + account + "' And password = '******'"; string updateCmdStr = "UPDATE tb_accounts SET ip = '" + ip + "', port = '" + port + "', status = '" + CommonStaticVariables.statusOnline + "', home = '" + homeFolder + "', lastTime = '" + DateTime.Now + "' WHERE account = '" + account + "' AND password = '******'"; if (SQLHandler.DrRead(selectCmdStr)) { SQLHandler.OperateRecord(updateCmdStr); if (!Directory.Exists(homeFolder)) { FileSystemHandler.CreateDirectory(homeFolder, DateTime.Now); } return(true); } else { return(false); } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); return(false); } }
static int Main(string[] args) { if (args.Length == 0) { Console.Error.WriteLine("Usage: AlphaNumericFS <mount point>"); return -1; } AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); string mountPoint; if (!Directory.Exists(mountPoint = Path.GetFullPath(args[0]))) Directory.CreateDirectory(mountPoint); Console.WriteLine("Mount point:{0}", mountPoint); string[] actualArgs = { "-s", "-f", mountPoint }; int status = -1; using (FileSystem fs = new AlphaNumericFileSystem()) using (FileSystemHandler fsh = new FileSystemHandler(fs, actualArgs, OperationsFlags.All)) { status = fsh.Start(); } Console.WriteLine(status); return status; }
private static int Analyze(string settings, string projectPath, string[] ignoredPaths) { var fileSystemHandler = new FileSystemHandler(); var outputWriter = new StandardOutputWriter(); if (false == fileSystemHandler.Exists(settings)) { outputWriter.WriteLineWithSeparator("Given settings file does not exist. Exiting...", string.Empty); return(SettingsFileDoesNotExistErrorCode); } if (false == fileSystemHandler.Exists(projectPath)) { outputWriter.WriteLineWithSeparator("Given path to analyze does not exist. Exiting...", string.Empty); return(InvalidPathToAnalyzeErrorCode); } var analyzer = new StyleCopAnalyzer(); var projectFactory = new ProjectFactory(new FileSystemHandler()); var project = projectFactory.CreateFromPathWithCustomSettings(projectPath, settings, ignoredPaths); var violations = analyzer.GetViolationsFromProject(project); var renderer = new ConsoleRenderer(outputWriter); renderer.RenderViolationList(violations); if (violations.Empty) { return(NoViolationsFound); } return(ViolationsFound); }
public DistributeFileResult DistributeFile(DistributionFile distributionFile) { string errorMessage = null; try { Configuration configuration = Configuration.Read(); Group group = configuration.Groups.FirstOrDefault(x => x.ID == distributionFile.DestinationGroupID); if (group == null) { Logger.AddAndThrow <DistributeFileException>(LogType.Error, $"Could not find group with ID {distributionFile.DestinationGroupID}"); } string filePath = Path.Combine(group.Path, distributionFile.RelativePath.Trim(Path.DirectorySeparatorChar)); try { FileSystemHandler.PutFileContent(filePath, distributionFile.Content); } catch (Exception ex) { Logger.AddAndThrow <DistributeFileException>($"Failed to persist file content of {filePath}", ex); } } catch (DistributeFileException ex) { errorMessage = ex.Message; } return(new DistributeFileResult(distributionFile.RelativePath, distributionFile.DestinationGroupID, errorMessage)); }
public void OpenMediaFile(MediaFile mediaFile, bool preview = false) { string filePath = string.Empty; if (mediaFile is ImageFile || !preview) { filePath = Path.Combine(mediaFile.Source.RootedPath, mediaFile.RelativePathName); } else if (mediaFile is VideoFile) { FileSystemHandler.ClearWorkingDirectory(); using (GalleryDatabase database = GalleryDatabase.Open(Gallery.FilePath, Gallery.EncryptionAlgorithm, Gallery.Password, false)) { filePath = database.ExtractEntry(mediaFile.DatabasePreviewPathName, ObjectPool.CompleteWorkingDirectory); } } if (File.Exists(filePath)) { Process process = new Process() { StartInfo = { FileName = filePath, Verb = "Open" } }; process.Start(); } }
public static void Write(Configuration configuration) { lock (_serializationLock) { FileSystemHandler.Serialize(_configFilePath, configuration); } }
public void UpdateVolumeLetter() { try { VolumeLetter = FileSystemHandler.GetVolumeLetter(VolumeSerial); } catch (Exception) {; } }
static Configuration() { _appDataFolder = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), Settings.Service.Defaults.COMPANY_NAME), Settings.Service.Defaults.APPLICATION_NAME); FileSystemHandler.CreateDirectory(_appDataFolder); _configFilePath = Path.Combine(_appDataFolder, Settings.Service.Read("ConfigurationFileName")); }
public async Task InitializeAppStateAsync() { DownloadHandler = new AppDownloadHandler(UpdatePath); FileHandler = new FileSystemHandler(UpdatePath); Revit2018AppInstalled = await CheckIf2018AppIsInstalledAsync().ConfigureAwait(false); Revit2018AppUpdateAvailable = await CheckForUpdateTo2018AppAsync().ConfigureAwait(false); }
/// <summary> /// Registers all http request handlers to be served by the web interface. Override to register /// own handlers (via <see cref="Resolver.Add"/>) or pages (via <see cref="RegisterPage"/>), /// but remember to call the base method to register some shared handlers. /// </summary> public virtual void RegisterHandlers(FileSystemOptions fsOptions) { if (fsOptions == null) { throw new ArgumentException("FileSystemOptions can't be null"); } var fileHandler = new FileSystemHandler(PathUtil.AppPathCombine("Static"), fsOptions); Resolver.Add(new UrlMapping(fileHandler.Handle, path: "/Static")); }
// default to local filesystem public static IBlobHandler GetHandler(UrlType urlType, string url) { if (DebugMode) { Console.WriteLine("GetHandler start"); } IBlobHandler blobHandler; switch (urlType) { case UrlType.Azure: blobHandler = new AzureHandler(url); break; case UrlType.AzureFile: blobHandler = new AzureFileHandler(url); break; case UrlType.S3: blobHandler = new S3Handler(url); break; case UrlType.SkyDrive: blobHandler = new SkyDriveHandler(url); break; case UrlType.Local: blobHandler = new FileSystemHandler(url); break; //case UrlType.Sharepoint: // blobHandler = new SharepointHandler(url); // break; case UrlType.Dropbox: blobHandler = new DropboxHandler(url); break; default: blobHandler = new FileSystemHandler(url); break; } if (DebugMode) { Console.WriteLine("GetHandler retrieved " + blobHandler.GetType().ToString()); } return(blobHandler); }
// 客户端做了删除操作 public static bool delete(string deletePath) { if (Directory.Exists(deletePath)) { FileSystemHandler.DeleteDirectory(deletePath); } if (File.Exists(deletePath)) { FileSystemHandler.DeleteFile(deletePath); } return(true); }
private void LoadSourcesThread() { try { RaiseStatusUpdatedEvent("Loading sources..."); FileSystemHandler.LoadMetaDatabases(ObjectPool.Sources); RaiseDatabaseOperationCompletedEvent(OperationType.LoadSources); } catch (Exception ex) { CommonWorker.ShowError(ex); } }
public static Configuration Read() { if (!File.Exists(_configFilePath)) { return(new Configuration()); } lock (_serializationLock) { Configuration configuration = FileSystemHandler.Deserialize <Configuration>(_configFilePath); configuration.UpdateHash(); return(configuration); } }
public void ShouldNotAutoDownloadResources() { var handler = new FileSystemHandler(false); var client = new HttpClient(handler); var browser = new Browser(client) { AutoDownloadResources = false }; var page = browser.Open("http://example.com/simple_resources.html").Result; page.Resources.Count().Is(4); handler.Requests.Count.Is(1); }
private void Initialize(string path, Gallery gallery) { ID = null; string volumeLetter, volumeName, volumeSerial; FileSystemHandler.GetVolumeInfo(path, out volumeLetter, out volumeName, out volumeSerial); VolumeLetter = volumeLetter; VolumeName = volumeName; VolumeSerial = volumeSerial; Path = path.Substring(2); CreateID(); Gallery = gallery; RootFolder = new MediaFolder(Path, null, null, this); MediaCount = new MediaCount(); ScanDate = DateTime.MinValue; }
private void LoadThumbnailsThread(object data) { try { RaiseStatusUpdatedEvent("Loading thumbnails..."); MediaFolder folder = (data as MediaFolder); if (folder != null) { FileSystemHandler.LoadThumbnails(folder); } RaiseDatabaseOperationCompletedEvent(OperationType.LoadThumbnails); } catch (Exception ex) { CommonWorker.ShowError(ex); } }
private void AddWorkThread(DistributionWork work) { try { switch (work.Type) { case ActionType.Distribute: { var sourceFiles = work.Application.Sources .Select(source => new { Source = source, FullPath = Path.Combine(work.Group.Path, source.Path.Trim(Path.DirectorySeparatorChar)) }) .Select(x => new { x.Source, Files = FileSystemHandler.IsFile(x.FullPath) ? new List <DistributionFile>() { new DistributionFile(x.Source.Path) } : FileSystemHandler.GetFileSystemEntries(x.FullPath, x.Source.Filter, x.Source.Recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) .Where(entry => !entry.IsFolder) .Select(entry => new DistributionFile(Path.Combine(x.Source.Path, entry.Name))) .ToList() }) .ToList(); IEnumerable <DistributionFile> inclusiveSourceFiles = sourceFiles.Where(x => x.Source.Inclusive).SelectMany(x => x.Files); IEnumerable <DistributionFile> exclusiveSourceFiles = sourceFiles.Where(x => !x.Source.Inclusive).SelectMany(x => x.Files); work.Files = inclusiveSourceFiles.Except(exclusiveSourceFiles, new DistributionFileEqualityComparer()).ToList(); } break; } Logger.Add(LogType.Verbose, $"Adding distribution work to queue: destination machine = {work.DestinationMachine}, files = {work.Files.Count}"); lock (_pendingDistributionWork) _pendingDistributionWork.Add(work); } catch (ThreadAbortException) { } catch (Exception ex) { Logger.Add("An unexpected error occurred while preparing to add distribution work, aborting..", ex); } }
private FileSystemHandler CreateFileSystemHandler() { var fileSystemHandler = new FileSystemHandler(); fileSystemHandler.FileSystemAccess = Substitute.For <IFileSystemAccess>(); fileSystemHandler.FileSystemAccess.GetDirectories(Arg.Any <string>()).Returns(GetDirectoriesPathCollection()); fileSystemHandler.FileSystemAccess.GetFiles(Arg.Any <string>()).Returns(GetFilesPathCollection()); var directoryParser = Substitute.For <IDirectoryParser>(); var driveParser = Substitute.For <IDriveParser>(); var fileParser = Substitute.For <IFileParser>(); fileSystemHandler.DirectoryParser = directoryParser; fileSystemHandler.DriveParser = driveParser; fileSystemHandler.FileParser = fileParser; return(fileSystemHandler); }
static int Main(string[] args) { if (args.Length == 0) { Console.Error.WriteLine("Usage: AlphaNumericFS <mount point>"); return(-1); } AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); string mountPoint; if (!Directory.Exists(mountPoint = Path.GetFullPath(args[0]))) { Directory.CreateDirectory(mountPoint); } Console.WriteLine("Mount point:{0}", mountPoint); var dbname = EnsemblConfig.DatabaseConfig.Host; string[] actualArgs = { "-s", "-f",mountPoint, "-r", "-o",$"fsname=EnsemblFS-{dbname}", "-o",$"volname=EnsemblFS-{dbname}", "-o","nolocalcaches", "-o","noappledouble", }; int status = -1; using (FileSystem fs = new EnsemblFileSystem()) using (FileSystemHandler fsh = new FileSystemHandler(fs, actualArgs)) { status = fsh.Start(); } Console.WriteLine(status); return(status); }
private void ScanSourceThread(GallerySource source, bool reScan) { try { using (GalleryDatabase database = GalleryDatabase.Open(Gallery.FilePath, Gallery.EncryptionAlgorithm, Gallery.Password, true)) { database.RegisterStreamProvider <Gallery>(GalleryMetadataStreamProvider); database.RegisterStreamProvider <MediaFile>(MediaFileStreamProvider); FileSystemHandler.ScanFolders(database, source, reScan); source.ScanDate = DateTime.Now; source.UpdateMediaCount(); database.UpdateEntry(GALLERY_FILE_NAME, string.Empty, Gallery, true); database.Save(); } RaiseDatabaseOperationCompletedEvent(OperationType.ScanSource); } catch (Exception ex) { CommonWorker.ShowError(ex); } }
public void ShouldGuessMimeTypesWithoutDownloading() { var handler = new FileSystemHandler(false); var client = new HttpClient(handler); var browser = new Browser(client) { AutoDownloadResources = false }; var page = browser.Open("http://example.com/simple_resources.html").Result; var resources = page.Resources.ToArray(); resources.Length.Is(4); resources[0].GuessMimeType.Is("text/css"); resources[1].GuessMimeType.Is("image/png"); resources[2].GuessMimeType.Is("text/html"); resources[3].GuessMimeType.Is("application/javascript"); handler.Requests.Count.Is(1); }
private void ScanSourceThread(object data) { try { object[] parameters = data as object[]; if (parameters != null && parameters.Length == 2) { GallerySource source = (parameters[0] as GallerySource); if (source != null && parameters[1] is bool) { FileSystemHandler.PrepareDirectories(); FileSystemHandler.InitializeImageProcessor(90L); FileSystemHandler.ScanFolders(source, (bool)parameters[1]); } } RaiseDatabaseOperationCompletedEvent(OperationType.ScanSource); } catch (Exception ex) { CommonWorker.ShowError(ex); } }
public void ShouldOnlyDownloadResourcesOnce() { var handler = new FileSystemHandler(false); var client = new HttpClient(handler); var browser = new Browser(client) { AutoDownloadResources = false }; var page = browser.Open("http://example.com/simple_resources.html").Result; var css = page.Resources.First(); handler.Requests.Count.Is(1); var bytes = css.ReadAsBytes().Result; var str = css.ReadAsString().Result; handler.Requests.Count.Is(2); str.Is(File.ReadAllText("Content/demo_style.css")); }
// 注册消息处理 public static bool registration(string account, string password, string ip, string port) { try { string homeFolder = CommonStaticVariables.homePath + account; string selectCmdStr = "SELECT account FROM tb_accounts WHERE account = '" + account + "'"; if (SQLHandler.DrRead(selectCmdStr)) { return(false); } else { string insertCmdStr = "INSERT INTO tb_accounts (account, password, ip, port, status, home, registerTime) VALUES ( '" + account + "','" + password + "', '" + ip + "', '" + port + "', '" + CommonStaticVariables.statusOffline + "', '" + homeFolder + "', '" + DateTime.Now + "')"; SQLHandler.OperateRecord(insertCmdStr); FileSystemHandler.CreateDirectory(homeFolder, DateTime.Now); return(true); } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); return(false); } }
private static void GenerateMemoryLeak() { //Totake oggetti creati IList <FileSystemHandler> collezione = new List <FileSystemHandler>(); long totalCreatedObjects = 0; while (true) { //Inizializzo un oggetto FileSystemHandler handler = new FileSystemHandler(); totalCreatedObjects++; handler.FileWithSecondExtensionFound += Handler_FileWithSecondExtensionFound; //Aggiunta a lista //collezione.Add(handler); //Ogni 1000 elementi scrivo if (totalCreatedObjects % 1000 == 0) { Console.WriteLine($"Creati {totalCreatedObjects} elementi..."); } } }
private void DistributeSourceFilesThread(Machine machine) { List <DistributionWork> processedDistributionWork = new List <DistributionWork>(); while (ConnectionStore.ConnectionCreated(machine)) { DistributionWork work; lock (_pendingDistributionWork) { work = _pendingDistributionWork .Where(pendingWork => Comparer.MachinesEqual(pendingWork.DestinationMachine, machine)) .FirstOrDefault(pendingWork => !processedDistributionWork.Contains(pendingWork)); } if (work == null) { Thread.Sleep(10); continue; } processedDistributionWork.Add(work); Task.Run(() => { try { try { Group destinationGroup = ConnectionStore.Connections[work.DestinationMachine].Configuration.Groups .FirstOrDefault(group => Comparer.GroupsEqual(group, work.Group)); if (destinationGroup == null) { Logger.AddAndThrow <DistributionActionException>(LogType.Warning, $"Could not distribute application {work.Application.Name} in group {work.Group.Name}" + $" to destination machine {work.DestinationMachine.HostName}. Destination machine does not contain a matching group."); } List <string> errorMessages = new List <string>(); foreach (DistributionFile file in work.Files) { file.DestinationGroupID = destinationGroup.ID; file.Content = FileSystemHandler.GetFileContent(Path.Combine(work.Group.Path, file.RelativePath.Trim(Path.DirectorySeparatorChar))); DistributeFileResult result = ConnectionStore.Connections[work.DestinationMachine].ServiceHandler.Service.DistributeFile(new DTODistributionFile(file)).FromDTO(); try { if (result.Success) { Logger.Add(LogType.Verbose, $"Distribution of file to {work.DestinationMachine.HostName} succeeded: {file.RelativePath}, {file.Content.Length} bytes"); } else { Logger.AddAndThrow <DistributionActionException>(LogType.Error, $"Distribution of file to {work.DestinationMachine.HostName} failed: {Path.GetFileName(file.RelativePath)} | {result.ErrorMessage}"); } } catch (DistributionActionException ex) { errorMessages.Add(ex.Message); } file.IsDistributed = true; } if (errorMessages.Any()) { throw new DistributionActionException(string.Join(Environment.NewLine, errorMessages.Select(x => x.Replace(" | ", Environment.NewLine + "\t")))); } RaiseDistributionCompletedEvent(new DistributionResult(work, DistributionResultValue.Success), work.ClientId); } catch (DistributionActionException) { throw; } catch (ThreadAbortException) { } catch (Exception ex) { Logger.AddAndThrow <DistributionActionException>("An unexpected error occurred while distributing source files, aborting..", ex); } finally { lock (_pendingDistributionWork) _pendingDistributionWork.Remove(work); } } catch (DistributionActionException ex) { RaiseDistributionCompletedEvent(new DistributionResult(work, DistributionResultValue.Failure, ex.Message), work.ClientId); } }); } }
/// <summary> /// Constructor /// </summary> /// <param name="config">Web Server configuration</param> public MicroWebServer(MicroWebServerConfig config) { // check HTTP port if (config.HttpPort <= 0) throw new ArgumentException("Wrong HTTP port in configuration"); // check backlog if (config.Backlog <= 0) throw new ArgumentException("Wrong Backlog in configuration"); // if not defined, set WebRoot default directory if ((config.WebRoot == null) || (config.WebRoot == String.Empty)) this.config.WebRoot = WEBROOT_DEFAULT; // set Web Server configuration this.config = config; // create Web Root directory if it doesn't exist if (!Directory.Exists(this.config.WebRoot)) Directory.CreateDirectory(this.config.WebRoot); // listener thread not yet running this.isRunning = false; // create thread pool for request processing and request queue this.workerThreadPool = new ArrayList(); this.requestQueue = new Queue(); // create handlers collection and set defaults handler this.handlers = new Hashtable(); this.fileSystemHandler = new FileSystemHandler(); this.cgiHandler = new CgiHandler(); }
// 客户端重命名了文件 public static bool renameFile(string sourceFilePath, string destFilePath, DateTime lastWriteTime) { FileSystemHandler.RenameFile(sourceFilePath, destFilePath, lastWriteTime); return(true); }