public static IDirectoryInfo Create(IFileSystem fileSystem, string path) {
            var di = Substitute.For<IDirectoryInfo>();
            di.FullName.Returns(path);
            di.Exists.Returns(true);
            di.Parent.Returns((IDirectoryInfo)null);
            di.EnumerateFileSystemInfos().Returns(new List<IFileSystemInfo>());

            fileSystem.GetDirectoryInfo(path).Returns(di);
            fileSystem.DirectoryExists(path).Returns(true);

            fileSystem.GetDirectoryInfo(path + Path.DirectorySeparatorChar).Returns(di);
            fileSystem.DirectoryExists(path + Path.DirectorySeparatorChar).Returns(true);

            return di;
        }
        public static IDirectoryInfo Delete(IFileSystem fileSystem, string path) {
            var di = Substitute.For<IDirectoryInfo>();
            di.FullName.Returns(path);
            di.Exists.Returns(false);
            di.Parent.Returns((IDirectoryInfo)null);
            di.EnumerateFileSystemInfos().ThrowsForAnyArgs<DirectoryNotFoundException>();

            fileSystem.GetDirectoryInfo(path).Returns(di);
            fileSystem.DirectoryExists(path).Returns(false);

            fileSystem.GetDirectoryInfo(path + Path.DirectorySeparatorChar).Returns(di);
            fileSystem.DirectoryExists(path + Path.DirectorySeparatorChar).Returns(false);

            return di;
        }
        internal static void Deploy(Application application, string sourceDir, IFileSystem fileSystem, string relativePathUnderVDir = "")
        {
            if (!fileSystem.DirectoryExists(sourceDir))
            {
                throw new Exception(string.Format("Failed to deploy files to application, source directory does not exist: '{0}'.", sourceDir));
            }

            if (application.VirtualDirectories.Count <= 0)
            {
                throw new Exception(string.Format("Application '{0}' does not have a virtual directory.", application.Path));
            }

            var physicalPath = application.VirtualDirectories[0].PhysicalPath;
            if (!fileSystem.DirectoryExists(physicalPath))
            {
                fileSystem.DirectoryCreate(physicalPath);
            }

            var relativeDirectoryPath = Path.Combine(physicalPath, relativePathUnderVDir);
            if (!fileSystem.DirectoryExists(relativeDirectoryPath))
            {
                fileSystem.DirectoryCreate(relativeDirectoryPath);
            }

            fileSystem.DirectoryCopy(sourceDir, relativeDirectoryPath);
            if (string.IsNullOrEmpty(relativeDirectoryPath))
            {
                fileSystem.DirectorySetAttribute(relativeDirectoryPath, FileAttributes.Normal);
            }
        }
Example #4
0
        public static string CreateNewDirectoryWithRenameAttempts(string directoryName, IFileSystem fileSystem, int maxRenameAttempts)
        {
            for (int directoryCreationAttempt = 1; directoryCreationAttempt < maxRenameAttempts; directoryCreationAttempt++)
            {
                string numberedDirectoryName;
                if (directoryCreationAttempt == 1)
                {
                    numberedDirectoryName = directoryName;
                }
                else
                {
                    string fullPath = Path.GetFullPath(directoryName);
                    string noTrailingSlash;
                    if (fullPath.EndsWith("\\"))
                    {
                        noTrailingSlash = fullPath.Substring(0, fullPath.Length - 1);
                    }
                    else
                    {
                        noTrailingSlash = fullPath;
                    }
                    numberedDirectoryName = string.Format("{0} ({1})", noTrailingSlash, directoryCreationAttempt.ToString());
                }

                if (fileSystem.DirectoryExists(numberedDirectoryName))
                {
                    continue;
                }

                fileSystem.CreateDirectory(numberedDirectoryName);
                return numberedDirectoryName;
            }

            throw new Exception(string.Format("Could not create directory: {0}. Exceeded {1} attempts.", directoryName, maxRenameAttempts));
        }
Example #5
0
        /// <summary>
        /// Adds an additional mediaPath to an existing virtual folder, within either the default view or a user view
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="virtualFolderName">Name of the virtual folder.</param>
        /// <param name="path">The path.</param>
        /// <param name="appPaths">The app paths.</param>
        public static void AddMediaPath(IFileSystem fileSystem, string virtualFolderName, string path, IServerApplicationPaths appPaths)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException("path");
            }

			if (!fileSystem.DirectoryExists(path))
            {
                throw new DirectoryNotFoundException("The path does not exist.");
            }

            var rootFolderPath = appPaths.DefaultUserViewsPath;
            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);

            var shortcutFilename = fileSystem.GetFileNameWithoutExtension(path);

            var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);

			while (fileSystem.FileExists(lnk))
            {
                shortcutFilename += "1";
                lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
            }

            fileSystem.CreateShortcut(lnk, path);
        }
        public void Import(IFileSystem fs, Attachment a)
        {
            if (a.HasContents)
            {
                string path = a.Url;

                if(!fs.DirectoryExists(Path.GetDirectoryName(path)))
                {
                    fs.CreateDirectory(Path.GetDirectoryName(path));
                }

                var memoryStream = new MemoryStream(a.FileContents);
                fs.WriteFile(path, memoryStream);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RepositoryGroupManager"/> class.  Provides nested operations over RepositoryManager instances.
 /// </summary>
 /// <param name="repository">The repository.</param>
 /// <param name="fileSystem"> </param>
 /// <example>Can be a direct path to a repository.config file</example>
 ///   
 /// <example>Can be a path to a directory, which will recursively locate all contained repository.config files</example>
 public RepositoryGroupManager(string repository, IFileSystem fileSystem)
 {
     Contract.Requires(fileSystem != null);
     this.fileSystem = fileSystem;
     
     if (fileSystem.DirectoryExists(repository))
     {
         // we're dealing with a directory
         //TODO Does this by default do a recursive???
         RepositoryManagers = new ConcurrentBag<RepositoryManager>(fileSystem.GetFiles(repository, "repositories.config", SearchOption.AllDirectories).Select(file => new RepositoryManager(file, new RepositoryEnumerator(fileSystem), fileSystem)).ToList());
     }
     else if (fileSystem.FileExists(repository) && Path.GetFileName(repository) == "repositories.config")
         RepositoryManagers = new ConcurrentBag<RepositoryManager>(new List<RepositoryManager> { new RepositoryManager(repository, new RepositoryEnumerator(fileSystem), fileSystem) });
     else
         throw new ArgumentOutOfRangeException("repository");
 }
Example #8
0
        /// <summary>
        /// Deletes a shortcut from within a virtual folder, within either the default view or a user view
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="virtualFolderName">Name of the virtual folder.</param>
        /// <param name="mediaPath">The media path.</param>
        /// <param name="appPaths">The app paths.</param>
        /// <exception cref="System.IO.DirectoryNotFoundException">The media folder does not exist</exception>
        public static void RemoveMediaPath(IFileSystem fileSystem, string virtualFolderName, string mediaPath, IServerApplicationPaths appPaths)
        {
            var rootFolderPath = appPaths.DefaultUserViewsPath;
            var path = Path.Combine(rootFolderPath, virtualFolderName);

			if (!fileSystem.DirectoryExists(path))
            {
                throw new DirectoryNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName));
            }
            
            var shortcut = Directory.EnumerateFiles(path, ShortcutFileSearch, SearchOption.AllDirectories).FirstOrDefault(f => fileSystem.ResolveShortcut(f).Equals(mediaPath, StringComparison.OrdinalIgnoreCase));

            if (!string.IsNullOrEmpty(shortcut))
            {
                fileSystem.DeleteFile(shortcut);
            }
        }
Example #9
0
        private IRInterpreterInfo TryFindRInProgramFiles(ISupportedRVersionRange supportedVersions)
        {
            // Force 64-bit PF
            var programFiles = Environment.GetEnvironmentVariable("ProgramW6432");
            var baseRFolder  = Path.Combine(programFiles, @"R");
            var versions     = new List <Version>();

            try {
                if (_fileSystem.DirectoryExists(baseRFolder))
                {
                    IEnumerable <IFileSystemInfo> directories = _fileSystem.GetDirectoryInfo(baseRFolder)
                                                                .EnumerateFileSystemInfos()
                                                                .Where(x => (x.Attributes & FileAttributes.Directory) != 0);
                    foreach (IFileSystemInfo fsi in directories)
                    {
                        string  subFolderName = fsi.FullName.Substring(baseRFolder.Length + 1);
                        Version v             = GetRVersionFromFolderName(subFolderName);
                        if (supportedVersions.IsCompatibleVersion(v))
                        {
                            versions.Add(v);
                        }
                    }
                }
            } catch (IOException) {
                // Don't do anything if there is no RRO installed
            }

            if (versions.Count > 0)
            {
                versions.Sort();
                Version highest = versions[versions.Count - 1];
                var     name    = string.Format(CultureInfo.InvariantCulture, "R-{0}.{1}.{2}", highest.Major, highest.Minor, highest.Build);
                var     path    = Path.Combine(baseRFolder, name);
                var     ri      = new RInterpreterInfo(name, path);
                if (ri.VerifyInstallation(supportedVersions))
                {
                    return(ri);
                }
            }

            return(null);
        }
Example #10
0
        private IEnumerable <Interpreter> GetInterpreters()
        {
            if (_options.AutoDetect)
            {
                _logger.LogTrace(Resources.Trace_AutoDetectingR);

                var engines = _installationService.GetCompatibleEngines().AsList();
                if (engines.Any())
                {
                    var interpreterId = 0;
                    foreach (var e in engines)
                    {
                        var detected = new Interpreter(this, Invariant($"{interpreterId++}"), e);
                        _logger.LogTrace(Resources.Trace_DetectedR, detected.Version, detected.Path);
                        yield return(detected);
                    }
                }
                else
                {
                    _logger.LogWarning(Resources.Error_NoRInterpreters);
                }
            }

            foreach (var kv in _options.Interpreters)
            {
                string             id      = kv.Key;
                InterpreterOptions options = kv.Value;

                if (!string.IsNullOrEmpty(options.BasePath) && _fs.DirectoryExists(options.BasePath))
                {
                    var interpInfo = _installationService.CreateInfo(string.Empty, options.BasePath);
                    if (interpInfo != null && interpInfo.VerifyInstallation())
                    {
                        yield return(new Interpreter(this, id, options.Name, interpInfo));

                        continue;
                    }
                }

                _logger.LogError(Resources.Error_FailedRInstallationData, options.Name ?? id, options.BasePath);
            }
        }
        protected override Assembly LoadAssembly(byte[] exeBytes, byte[] pdbBytes)
        {
            throw new NotImplementedException("todo, app domains need to be rethought");
            _log.DebugFormat("Writing assembly to {0}.", FileName);

            if (!_fileSystem.DirectoryExists(CacheDirectory))
            {
                _fileSystem.CreateDirectory(CacheDirectory, true);
            }

            var dllPath = GetDllTargetPath();

            _fileSystem.WriteAllBytes(dllPath, exeBytes);

            _log.DebugFormat("Loading assembly {0}.", dllPath);

            // the assembly is automatically loaded into the AppDomain when compiled
            // just need to find and return it
            //return AppDomain.CurrentDomain.GetAssemblies().LastOrDefault(x => x.FullName.StartsWith(RoslynAssemblyNameCharacter));
        }
        protected override Assembly LoadAssembly(byte[] exeBytes, byte[] pdbBytes)
        {
            this.Logger.DebugFormat("Writing assembly to {0}.", FileName);

            if (!_fileSystem.DirectoryExists(BaseDirectory))
            {
                _fileSystem.CreateDirectory(BaseDirectory);
            }

            var dllName = FileName.Replace(Path.GetExtension(FileName), ".dll");
            var dllPath = Path.Combine(BaseDirectory, dllName);

            _fileSystem.WriteAllBytes(dllPath, exeBytes);

            this.Logger.DebugFormat("Loading assembly {0}.", dllPath);

            // the assembly is automatically loaded into the AppDomain when compiled
            // just need to find and return it
            return(AppDomain.CurrentDomain.GetAssemblies().LastOrDefault(x => x.FullName.StartsWith(RoslynAssemblyNameCharacter)));
        }
Example #13
0
        public async Task OpenFile(string filename, IFileSystem fileSystem)
        {
            CurrentFileSystem = fileSystem;

            if (fileSystem.FileExists(filename))
            {
                RawData = new BinaryFile(filename, CurrentFileSystem);

                await OpenFile(RawData);
            }
            else if (fileSystem.DirectoryExists(filename))
            {
                VirtualPath        = filename;
                DisposeVirtualPath = false;
            }
            else
            {
                throw new FileNotFoundException("Could not find file or directory at the given path", filename);
            }
        }
Example #14
0
        /// <summary>
        /// Terminates the created mongod.exe instance and deletes the created temp folder if the instance is
        /// created through <see cref="Start(ushort)" /> or <see cref="Start(ushort, IMongoExeLocator)"/>. If the instance
        /// is created through <see cref="Setup" />, the initialized <see cref="IRandomMongoDatabase" />
        /// implementation instance will be dropped.
        /// </summary>
        public void Dispose()
        {
            if (_disposed == false)
            {
                _randomDatabase.Dispose();

                if (_mode == MongoTestServerMode.WithOwnedProcess)
                {
                    _process.Kill();
                    _process.WaitForExit();

                    if (_fileSystem.DirectoryExists(_dataPath))
                    {
                        _fileSystem.DeleteDirectory(_dataPath, true);
                    }
                }

                _disposed = true;
            }
        }
        public void MarkPackageDirectoryForDeletion(IPackage package)
        {
            IFileSystem          repositoryFileSystem = _repositoryFileSystemFactory();
            IPackagePathResolver pathResolver         = _packagePathResolverFactory();
            string packageDirectoryName = pathResolver.GetPackageDirectory(package);

            try
            {
                if (repositoryFileSystem.DirectoryExists(packageDirectoryName))
                {
                    // NOTE: The repository should always be a PhysicalFileSystem, except during testing, so the
                    // .deleteme marker file doesn't get checked into version control
                    repositoryFileSystem.AddFile(packageDirectoryName + DeletionMarkerSuffix, Stream.Null);
                }
            }
            catch (Exception e)
            {
                repositoryFileSystem.Logger.Log(MessageLevel.Warning, String.Format(Resources.VsResources.Warning_FailedToMarkPackageDirectoryForDeletion, packageDirectoryName, e.Message));
            }
        }
        public void OpenContainingFolder(string path)
        {
            Requires.NotNullOrEmpty(path, nameof(path));

            // When 'path' doesn't exist, Explorer just opens the default
            // "Quick Access" page, so try to something better than that.
            if (_fileSystem.PathExists(path))
            {
                // Tell Explorer to open the parent folder of the item, selecting the item
                ShellExecute(string.Empty, "explorer.exe", parameters: $"/select,\"{path}\"");
            }
            else
            {
                string?parentPath = GetParentPath(path);
                if (parentPath != null && _fileSystem.DirectoryExists(parentPath))
                {
                    OpenFolder(parentPath);
                }
            }
        }
 /// <summary>
 /// Event on TabItem clicked - it open root;
 /// </summary>
 /// <param name="sender">TabItem</param>
 /// <param name="e">RoutedEventArgs</param>
 private void DriveTabDriveSelected(object sender, DriveEventArgs e)
 {
     if (_fileSystem.DirectoryExists(e.DriveName))
     {
         CurrentPath = e.DriveName;
     }
     else
     if (Windows.Dialogs.MessageBox.ShowDialog(
             String.Format(
                 "Диск {0,3} не найден.\n\nПерейти на системный диск {1} ?",
                 CurrentDrive,
                 Environment.SystemDirectory.Substring(0, 3)
                 ),
             "Ultimate Commander - Подсистема доступа",
             MessageBoxButton.YesNo) == true)
     {
         CurrentPath  = Environment.SystemDirectory.Substring(0, 3);
         CurrentDrive = CurrentPath;
     }
 }
        private static string MockFileSystem(IFileSystem fileSystem, IPackage package, string framework = "net45")
        {
            var path   = package.Id;
            var libDir = Path.Combine(path, Constants.LibDirectory);

            fileSystem.DirectoryExists(libDir).Returns(true);

            var assemblies = new[] { $"{package.Id}.dll" };

            fileSystem.GetFiles(libDir, "*.dll", false).Returns(assemblies);

            if (!string.IsNullOrWhiteSpace(framework))
            {
                var folders = new[] { framework };
                fileSystem.GetDirectories(libDir).Returns(folders);
                return(Path.Combine(path, Constants.LibDirectory, framework));
            }

            return(Path.Combine(path, Constants.LibDirectory));
        }
        public IEnumerable <T> GetAll()
        {
            var path = getDataPathForType.GetPathForDataByType(typeof(T));

            if (!fileSystem.DirectoryExists(path))
            {
                return new T[] { }
            }
            ;

            var set       = new List <T>();
            var filePaths = fileSystem.GetFiles(path, "*.xml");

            foreach (var filePath in filePaths)
            {
                set.Add(xmlFileSerializationHelper.DeserializeFromPath <T>(filePath));
            }

            return(set);
        }
Example #20
0
        public CommandResult Execute(IEnumerable <string> inputParams)
        {
            var inputParamsArray = inputParams.ToArray();
            var projectName      = inputParamsArray.ElementAtOrDefault(0);
            var outputMessages   = new MessageLines();

            if (string.IsNullOrEmpty(projectName) || !_fileSystem.DirectoryExists(projectName))
            {
                AppioLogger.Info(Resources.text.logging.LoggingText.CleanFailure);
                outputMessages.Add(Resources.text.output.OutputText.OpcuaappCleanFailure, string.Empty);
                return(new CommandResult(false, outputMessages));
            }

            var buildDirectory = _fileSystem.CombinePaths(projectName, Constants.DirectoryName.MesonBuild);

            _fileSystem.DeleteDirectory(buildDirectory);
            AppioLogger.Info(Resources.text.logging.LoggingText.CleanSuccess);
            outputMessages.Add(string.Format(Resources.text.output.OutputText.OpcuaappCleanSuccess, projectName), string.Empty);
            return(new CommandResult(true, outputMessages));
        }
Example #21
0
        private IEnumerable <Interpreter> GetInterpreters()
        {
            if (_options.AutoDetect)
            {
                _logger.LogTrace(Resources.Trace_AutoDetectingR);

                var engines = new RInstallation().GetCompatibleEngines();
                if (engines.Any())
                {
                    foreach (var e in engines)
                    {
                        var detected = new Interpreter(this, Guid.NewGuid().ToString(), e.Name, e.InstallPath, e.BinPath, e.Version);
                        _logger.LogTrace(Resources.Trace_DetectedR, detected.Version, detected.Path);
                        yield return(detected);
                    }
                }
                else
                {
                    _logger.LogWarning(Resources.Error_NoRInterpreters);
                }
            }

            foreach (var kv in _options.Interpreters)
            {
                string             id      = kv.Key;
                InterpreterOptions options = kv.Value;

                if (!string.IsNullOrEmpty(options.BasePath) && _fs.DirectoryExists(options.BasePath))
                {
                    var interpInfo = new RInterpreterInfo(string.Empty, options.BasePath);
                    if (interpInfo.VerifyInstallation())
                    {
                        yield return(new Interpreter(this, id, options.Name, interpInfo.InstallPath, interpInfo.BinPath, interpInfo.Version));

                        continue;
                    }
                }

                _logger.LogError(Resources.Error_FailedRInstallationData, id, options.BasePath);
            }
        }
Example #22
0
        public IHttpActionResult PostDeleteItem(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return(NotFound());
            }

            id = HttpUtility.UrlDecode(id);
            var parts = id.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var part in parts)
            {
                if (Path.GetInvalidFileNameChars().ContainsAny(part.ToCharArray()))
                {
                    return(NotFound());
                }
            }

            if (Path.GetExtension(id).IsNullOrWhiteSpace())
            {
                //delete folder
                if (!_themesFileSystem.DirectoryExists(id))
                {
                    return(NotFound());
                }

                _themesFileSystem.DeleteDirectory(id, true);
            }
            else
            {
                //delete file
                if (!_themesFileSystem.FileExists(id))
                {
                    return(NotFound());
                }

                _themesFileSystem.DeleteFile(id);
            }

            return(Ok());
        }
        public void Compose(string workingDirectory, StringBuilder builder = null)
        {
            if (string.IsNullOrWhiteSpace(ScriptLibrariesFile))
            {
                return;
            }

            var packagesPath       = Path.Combine(workingDirectory, _fileSystem.PackagesFolder);
            var packageScriptsPath = Path.Combine(packagesPath, ScriptLibrariesFile);

            if (!_fileSystem.DirectoryExists(packagesPath) || _fileSystem.FileExists(packageScriptsPath))
            {
                return;
            }

            if (builder == null)
            {
                builder = new StringBuilder();
            }

            var namespaces        = new List <string>();
            var references        = new List <string>();
            var packageReferences = _packageAssemblyResolver.GetPackages(workingDirectory);

            foreach (var reference in packageReferences)
            {
                ProcessPackage(packagesPath, reference, builder, references, namespaces);
            }

            foreach (var ns in namespaces)
            {
                builder.Insert(0, String.Format("using {0};{1}", ns, Environment.NewLine));
            }

            foreach (var reference in references)
            {
                builder.Insert(0, String.Format("#r {0}{1}", reference, Environment.NewLine));
            }

            _fileSystem.WriteToFile(packageScriptsPath, builder.ToString());
        }
Example #24
0
        public string GetFilePath(
            string fileName,
            IEnumerable <string> searchPaths)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException(nameof(fileName));
            }

            if (searchPaths == null)
            {
                throw new ArgumentNullException(nameof(searchPaths));
            }

            foreach (var searchPath in searchPaths)
            {
                if (_fileSystem.DirectoryExists(searchPath))
                {
                    var matchingFiles = _fileSystem.EnumerateFiles(searchPath,
                                                                   searchPattern: fileName,
                                                                   searchOption: SearchOption.AllDirectories).ToList();

                    if (matchingFiles.Count > 1)
                    {
                        throw new InvalidOperationException(string.Format(
                                                                MessageStrings.MultipleFilesFound,
                                                                fileName,
                                                                searchPath));
                    }
                    if (matchingFiles.Count == 1)
                    {
                        return(matchingFiles.Single());
                    }
                }
            }

            throw new InvalidOperationException(string.Format(
                                                    MessageStrings.FileNotFoundInFolders,
                                                    fileName,
                                                    string.Join(";", searchPaths)));
        }
Example #25
0
        private IProject GetProjectWorker(FullPath filepath)
        {
            var directory = filepath.Parent;

            if (_fileSystem.DirectoryExists(directory))
            {
                var project = filepath
                              .EnumerateParents()
                              .Select(CreateProject)
                              .FirstOrDefault(x => x != null);
                if (project != null)
                {
                    _knownProjectRootDirectories.Add(project.RootPath, project);
                    return(project);
                }
            }

            // No one in the parent chain is a Chromium directory.
            filepath.EnumerateParents().ForAll(x => _knownNonProjectDirectories.Add(x, null));
            return(null);
        }
Example #26
0
        public Importer(
            IFileSystem fileSystem, 
            ITweetDataFileParser tweetDataFileParser,
            IClientProvider clientProvider, 
            IElasticConnectionSettings elasticConnectionSettings, 
            string sourceDirectory)
        {
            if (fileSystem == null) throw new ArgumentNullException("fileSystem");
            if (tweetDataFileParser == null) throw new ArgumentNullException("tweetDataFileParser");
            if (clientProvider == null) throw new ArgumentNullException("clientProvider");
            if (elasticConnectionSettings == null) throw new ArgumentNullException("elasticConnectionSettings");

            if (!fileSystem.DirectoryExists(sourceDirectory))
                throw new DirectoryNotFoundException("Source directory does not exist");

            _fileSystem = fileSystem;
            _parser = tweetDataFileParser;
            _clientProvider = clientProvider;
            _elasticConnectionSettings = elasticConnectionSettings;
            _sourceDirectory = sourceDirectory;
        }
Example #27
0
        private IEnumerable <string> GetAssemblyPaths(string workingDirectory)
        {
            var binFolder = Path.Combine(workingDirectory, "bin");

            if (!_fileSystem.DirectoryExists(binFolder))
            {
                _fileSystem.CreateDirectory(binFolder);
            }

            var assemblyPaths =
                _fileSystem.EnumerateFiles(binFolder, "*.dll")
                .Union(_fileSystem.EnumerateFiles(binFolder, "*.exe"))
                .ToList();

            foreach (var path in assemblyPaths.Select(Path.GetFileName))
            {
                _logger.DebugFormat("Found assembly reference: {0}", path);
            }

            return(assemblyPaths);
        }
Example #28
0
        private IEnumerable <Interpreter> GetInterpreters()
        {
            foreach (var kv in _options.Interpreters)
            {
                var id      = kv.Key;
                var options = kv.Value;

                if (!string.IsNullOrEmpty(options.BasePath) && _fs.DirectoryExists(options.BasePath))
                {
                    var interpInfo = _installationService.CreateInfo(string.Empty, options.BasePath);
                    if (interpInfo != null && interpInfo.VerifyInstallation())
                    {
                        yield return(new Interpreter(id, options.Name, interpInfo));

                        continue;
                    }
                }

                _logger.LogError(Resources.Error_FailedRInstallationData, options.Name ?? id, options.BasePath);
            }
        }
Example #29
0
        private void CheckLogFiles(string logFilesNamePrefix, Regex logFilesRegex, ref HealthStatus status,
                                   IDictionary <string, object> data, string datePattern)
        {
            var logFilesDirectoryName = _pathHelper.GetDirectoryName(logFilesNamePrefix);

            if (!_fileSystem.DirectoryExists(logFilesDirectoryName))
            {
                status = HealthStatus.Unhealthy;
                data.Add($"Could not find log files for {logFilesNamePrefix}", $"Folder for {logFilesNamePrefix} does not exist");
                //var keyValue = new KeyValuePair<string, object>("State", $"Could not find log files for {logFilesNamePrefix}: Folder for {logFilesNamePrefix} does not exist");
                //data.Add(keyValue);
            }
            else if (logFilesDirectoryName == null)
            {
                status = HealthStatus.Unhealthy;
                data.Add($"Argument {nameof(logFilesDirectoryName)} is null or is a root directory {DateTime.Now}", "");
            }
            else
            {
                var logFilesDirectory = new DirectoryInfo(logFilesDirectoryName);
                var orderedLogFiles   = logFilesDirectory.GetFiles().OrderByDescending(f => f.LastWriteTime)
                                        .Where(n => logFilesRegex.IsMatch(n.Name));
                var logFiles = orderedLogFiles.ToList();
                if (!logFiles.Any()) // No log files
                {
                    status = HealthStatus.Unhealthy;
                    data.Add($"No log files for {logFilesNamePrefix}", "");
                }
                else // No log files today
                {
                    var today        = DateTime.Today.ToString(datePattern);
                    var fileForToday = logFiles.First().Name.Contains(today);
                    if (!fileForToday)
                    {
                        status = HealthStatus.Unhealthy;
                        data.Add($"No log file for today {logFilesNamePrefix}", "");
                    }
                }
            }
        }
Example #30
0
        public IPackageInfo LoadFromFolder(string folder)
        {
            folder = Path.GetFullPath(folder);

            var manifest = _fileSystem.LoadFromFile <PackageManifest>(folder, PackageManifest.FILE);
            var package  = new PackageInfo(manifest.Name)
            {
                Description = "{0} ({1})".ToFormat(manifest.Name, folder),
            };


            // Right here, this needs to be different
            package.RegisterFolder(BottleFiles.WebContentFolder, _getContentFolderFromPackageFolder(folder));
            package.RegisterFolder(BottleFiles.DataFolder, FileSystem.Combine(folder, BottleFiles.DataFolder));
            package.RegisterFolder(BottleFiles.ConfigFolder, FileSystem.Combine(folder, BottleFiles.ConfigFolder));

            var binPath   = FileSystem.Combine(_applicationFolder, folder, "bin");
            var debugPath = FileSystem.Combine(binPath, "debug");

            if (_fileSystem.DirectoryExists(debugPath))
            {
                binPath = debugPath;
            }

            //REVIEW: I feel this whole section is left-hand / right-hand code
            package.Role = manifest.Role;

            var assemblyPaths = findCandidateAssemblyFiles(binPath);

            assemblyPaths.Each(path =>
            {
                var assemblyName = Path.GetFileNameWithoutExtension(path);
                if (manifest.Assemblies.Contains(assemblyName))
                {
                    package.RegisterAssemblyLocation(assemblyName, path);
                }
            });

            return(package);
        }
Example #31
0
        /// <summary>
        /// Copies a directory from a source filesystem to a destination filesystem and folder.
        /// </summary>
        /// <param name="fs">The source filesystem.</param>
        /// <param name="srcFolder">The source folder.</param>
        /// <param name="destFileSystem">The destination filesystem.</param>
        /// <param name="dstFolder">The destination folder in the destination filesystem.</param>
        /// <param name="overwrite"><c>true</c> to overwrite files.</param>
        public static void CopyDirectory(this IFileSystem fs, UPath srcFolder, IFileSystem destFileSystem, UPath dstFolder, bool overwrite)
        {
            if (destFileSystem is null)
            {
                throw new ArgumentNullException(nameof(destFileSystem));
            }

            if (!fs.DirectoryExists(srcFolder))
            {
                throw new DirectoryNotFoundException($"{srcFolder} folder not found from source file system.");
            }

            if (dstFolder != UPath.Root)
            {
                destFileSystem.CreateDirectory(dstFolder);
            }

            var srcFolderFullName = srcFolder.FullName;

            int deltaSubString = srcFolder == UPath.Root ? 0 : 1;

            // Copy the files for the folder
            foreach (var file in fs.EnumerateFiles(srcFolder))
            {
                var relativeFile = file.FullName.Substring(srcFolderFullName.Length + deltaSubString);
                var destFile     = UPath.Combine(dstFolder, relativeFile);

                fs.CopyFileCross(file, destFileSystem, destFile, overwrite);
            }

            // Then copy the folder structure recursively
            foreach (var srcSubFolder in fs.EnumerateDirectories(srcFolder))
            {
                var relativeDestFolder = srcSubFolder.FullName.Substring(srcFolderFullName.Length + deltaSubString);

                var destSubFolder = UPath.Combine(dstFolder, relativeDestFolder);
                CopyDirectory(fs, srcSubFolder, destFileSystem, destSubFolder, overwrite);
            }
        }
Example #32
0
        public SFMDirectoryParser(string filepath, IFileSystem fs)
        {
            Path = filepath;
            _fs  = fs;

            if (_fs.DirectoryExists(Path))
            {
                foreach (var dir in fs.GetDirectories(Path))
                {
                    if (dir.Name.ToLower() != "game")
                    {
                        continue;
                    }

                    Path = dir.Path;
                    break;
                }
            }

            GameinfoPath     = System.IO.Path.Combine(Path, "usermod", "gameinfo.txt");
            InstallationPath = System.IO.Path.Combine(Path, "ponysfm");
        }
Example #33
0
        public async void Run()
        {
            if (!_config.Configuration.CollectionsUpgraded && _config.Configuration.IsStartupWizardCompleted)
            {
                var path = _collectionManager.GetCollectionsFolderPath();

                if (_fileSystem.DirectoryExists(path))
                {
                    try
                    {
                        await _collectionManager.EnsureLibraryFolder(path, true).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorException("Error creating camera uploads library", ex);
                    }

                    _config.Configuration.CollectionsUpgraded = true;
                    _config.SaveConfiguration();
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RepositoryGroupManager"/> class.  Provides nested operations over RepositoryManager instances.
        /// </summary>
        /// <param name="repository">The repository.</param>
        /// <param name="fileSystem"> </param>
        /// <example>Can be a direct path to a repository.config file</example>
        ///
        /// <example>Can be a path to a directory, which will recursively locate all contained repository.config files</example>
        public RepositoryGroupManager(string repository, IFileSystem fileSystem)
        {
            Contract.Requires(fileSystem != null);
            this.fileSystem = fileSystem;

            if (fileSystem.DirectoryExists(repository))
            {
                // we're dealing with a directory
                //TODO Does this by default do a recursive???
                RepositoryManagers = new ConcurrentBag <RepositoryManager>(fileSystem.GetFiles(repository, "repositories.config", SearchOption.AllDirectories).Select(file => new RepositoryManager(file, new RepositoryEnumerator(fileSystem), fileSystem)).ToList());
            }
            else if (fileSystem.FileExists(repository) && Path.GetFileName(repository) == "repositories.config")
            {
                RepositoryManagers = new ConcurrentBag <RepositoryManager>(new List <RepositoryManager> {
                    new RepositoryManager(repository, new RepositoryEnumerator(fileSystem), fileSystem)
                });
            }
            else
            {
                throw new ArgumentOutOfRangeException("repository");
            }
        }
Example #35
0
        /// <summary>
        /// Adds an additional mediaPath to an existing virtual folder, within either the default view or a user view
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="virtualFolderName">Name of the virtual folder.</param>
        /// <param name="path">The path.</param>
        /// <param name="appPaths">The app paths.</param>
        public static void AddMediaPath(IFileSystem fileSystem, string virtualFolderName, string path, IServerApplicationPaths appPaths)
        {
            if (!fileSystem.DirectoryExists(path))
            {
                throw new DirectoryNotFoundException("The path does not exist.");
            }

            var rootFolderPath    = appPaths.DefaultUserViewsPath;
            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);

            var shortcutFilename = fileSystem.GetFileNameWithoutExtension(path);

            var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);

            while (fileSystem.FileExists(lnk))
            {
                shortcutFilename += "1";
                lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
            }

            fileSystem.CreateShortcut(lnk, path);
        }
Example #36
0
        /// <summary>
        /// Saves all files in the executable file system to the specified file system
        /// </summary>
        /// <param name="directoryName">Directory on the specified file system to which the files should be saved.</param>
        /// <param name="fileSystem">File system to which the files should be saved.</param>
        /// <param name="progressReportToken">Optional token to be used to track the progress of the extraction.</param>
        public async Task ExtractFiles(string directoryName, IFileSystem fileSystem, ProcessingProgressedToken?progressReportToken = null)
        {
            if (progressReportToken != null)
            {
                progressReportToken.TotalFileCount = Files.Count;
            }

            if (!fileSystem.DirectoryExists(directoryName))
            {
                fileSystem.CreateDirectory(directoryName);
            }

            await Files.RunAsyncForEach((KeyValuePair <string, ExeFsEntry> file) =>
            {
                fileSystem.WriteAllBytes(Path.Combine(directoryName, file.Key), file.Value.RawData);

                if (progressReportToken != null)
                {
                    progressReportToken.IncrementProcessedFileCount();
                }
            }).ConfigureAwait(false);
        }
        /// <summary>
        /// Safely enumerates all files under a given root. If a subdirectory is
        /// inaccessible, its files will not be returned (compare and contrast
        /// with Directory.GetFiles, which will crash without returning any
        /// files at all).
        /// </summary>
        /// <param name="fileSystem">
        /// File system.
        /// </param>
        /// <param name="root">
        /// Directory to enumerate.
        /// </param>
        /// <param name="pattern">
        /// File pattern to return. You may use wildcards * and ?.
        /// </param>
        /// <param name="recurse">
        /// <c>true</c> to return files within subdirectories.
        /// </param>
        /// <param name="fullPaths">
        /// <c>true</c> to return full paths for all subdirectories. Otherwise,
        /// the relative path from <paramref name="root"/> is returned.
        /// </param>
        public static IEnumerable <IFileInfo> EnumerateFiles(IFileSystem fileSystem, string root, string pattern = "*", bool recurse = true)
        {
            root = EnsureEndSeparator(root);

            var dirs = Enumerable.Repeat(root, 1);

            if (recurse)
            {
                dirs = dirs.Concat(EnumerateDirectories(fileSystem, root, true, false));
            }

            foreach (var dir in dirs)
            {
                var         fullDir = Path.IsPathRooted(dir) ? dir : root + dir;
                IFileInfo[] files   = null;
                try {
                    if (fileSystem.DirectoryExists(fullDir))
                    {
                        files = fileSystem.GetDirectoryInfo(fullDir)
                                .EnumerateFileSystemInfos(pattern, SearchOption.TopDirectoryOnly)
                                .Where(f => !f.Attributes.HasFlag(FileAttributes.Directory))
                                .OfType <IFileInfo>()
                                .ToArray();
                    }
                } catch (UnauthorizedAccessException) {
                } catch (IOException) {
                }

                if (files == null)
                {
                    continue;
                }

                foreach (var f in files)
                {
                    yield return(f);
                }
            }
        }
Example #38
0
        /// <summary>
        /// Deletes a shortcut from within a virtual folder, within either the default view or a user view
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="virtualFolderName">Name of the virtual folder.</param>
        /// <param name="mediaPath">The media path.</param>
        /// <param name="appPaths">The app paths.</param>
        /// <exception cref="System.IO.DirectoryNotFoundException">The media folder does not exist</exception>
        public static void RemoveMediaPath(IFileSystem fileSystem, string virtualFolderName, string mediaPath, IServerApplicationPaths appPaths)
        {
            if (string.IsNullOrWhiteSpace(mediaPath))
            {
                throw new ArgumentNullException("mediaPath");
            }

            var rootFolderPath = appPaths.DefaultUserViewsPath;
            var path           = Path.Combine(rootFolderPath, virtualFolderName);

            if (!fileSystem.DirectoryExists(path))
            {
                throw new DirectoryNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName));
            }

            var shortcut = Directory.EnumerateFiles(path, ShortcutFileSearch, SearchOption.AllDirectories).FirstOrDefault(f => fileSystem.ResolveShortcut(f).Equals(mediaPath, StringComparison.OrdinalIgnoreCase));

            if (!string.IsNullOrEmpty(shortcut))
            {
                fileSystem.DeleteFile(shortcut);
            }
        }
Example #39
0
        public async void Run()
        {
            if (!_config.Configuration.CameraUploadUpgraded && _config.Configuration.IsStartupWizardCompleted)
            {
                var path = _deviceManager.GetUploadsPath();

                if (_fileSystem.DirectoryExists(path))
                {
                    try
                    {
                        await _deviceManager.EnsureLibraryFolder(path, null).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error creating camera uploads library");
                    }

                    _config.Configuration.CameraUploadUpgraded = true;
                    _config.SaveConfiguration();
                }
            }
        }
Example #40
0
        internal static void DeleteFiles(IFileSystem fileSystem, IEnumerable<IPackageFile> files, string rootDir)
        {
            // First get all directories that contain files
            var directoryLookup = files.ToLookup(p => Path.GetDirectoryName(p.Path));


            // Get all directories that this package may have added
            var directories = from grouping in directoryLookup
                              from directory in GetDirectories(grouping.Key)
                              orderby directory.Length descending
                              select directory;

            // Remove files from every directory
            foreach (var directory in directories)
            {
                var directoryFiles = directoryLookup.Contains(directory) ? directoryLookup[directory] : Enumerable.Empty<IPackageFile>();
                string dirPath = Path.Combine(rootDir, directory);

                if (!fileSystem.DirectoryExists(dirPath))
                {
                    continue;
                }

                foreach (var file in directoryFiles)
                {
                    string path = Path.Combine(rootDir, file.Path);

                    fileSystem.DeleteFileSafe(path, file.GetStream);
                }

                // If the directory is empty then delete it
                if (!fileSystem.GetFilesSafe(dirPath).Any() &&
                    !fileSystem.GetDirectoriesSafe(dirPath).Any())
                {
                    fileSystem.DeleteDirectorySafe(dirPath, recursive: false);
                }
            }
        }
Example #41
0
        private static Config LoadConfig(IConfigLoader configLoader, IFileSystem fileSystem)
        {
            var config = configLoader.Load<Config>("ChatLog/Config.json") ?? new Config();

            if (string.IsNullOrWhiteSpace(config.Path))
            {
                config.Path = "ChatLogs";
                Log.Info("No path specified, using 'ChatLogs'");
            }
            else
            {
                config.Path = config.Path;
            }

            try
            {
                if (fileSystem.DirectoryExists(config.Path))
                {
                    Log.Info("Path exists, skipping creation");
                }
                else
                {
                    Log.Info("Path does not exist, creating it..");
                    fileSystem.CreateDirectory(config.Path);
                }

                Log.Info($"Path is '{config.Path}'");
            }
            catch (Exception e)
            {
                Log.Error($"Error creating '{config.Path}': {e.Message}");
                Log.Error("Path not set");
            }

            return config;
        }
			public void SetUp()
			{
				pathThatAlreadyExists = Path.Combine("path", "that", "already", "exists");
				
				log = Substitute.For<ILog>();
				fileSystem = Substitute.For<IFileSystem>();
				dataSource = Substitute.For<IDataSource>();
				
				fileSystem.DirectoryExists(pathThatAlreadyExists).Returns(true);
				
				createSiteCommand = new CreateSiteCommand(log, fileSystem, dataSource);
			}
        internal static void Deploy(Application application, string[] filePaths, string relativePathUnderVDir, IFileSystem fileSystem)
        {
            if (filePaths == null)
            {
                throw new ArgumentNullException("filePaths");
            }

            if (application.VirtualDirectories.Count <= 0)
            {
                throw new Exception(string.Format("Application '{0}' does not have a virtual directory.", application.Path));
            }

            var physicalPath = application.VirtualDirectories[0].PhysicalPath;
            if (!fileSystem.DirectoryExists(physicalPath))
            {
                fileSystem.DirectoryCreate(physicalPath);
            }

            var relativeDirectoryPath = Path.Combine(physicalPath, relativePathUnderVDir);
            if (!fileSystem.DirectoryExists(relativeDirectoryPath))
            {
                fileSystem.DirectoryCreate(relativeDirectoryPath);
            }

            foreach (var sourceFilePath in filePaths)
            {
                if (fileSystem.FileExists(sourceFilePath))
                {
                    var sourceFileName = Path.GetFileName(sourceFilePath) ?? sourceFilePath;
                    var destinationFileName = Path.Combine(relativeDirectoryPath, sourceFileName);
                    fileSystem.FileCopy(sourceFilePath, destinationFileName, true);
                }
            }
        }
Example #44
0
 private void PretendRFilesAvailable(IFileSystem fs, string dir) {
     string dir64 = dir + @"\bin\x64\";
     fs.DirectoryExists(dir).Returns(true);
     fs.DirectoryExists(dir64).Returns(true);
     fs.FileExists(dir64 + "R.dll").Returns(true);
     fs.FileExists(dir64 + "Rgraphapp.dll").Returns(true);
     fs.FileExists(dir64 + "RTerm.exe").Returns(true);
     fs.FileExists(dir64 + "RScript.exe").Returns(true);
     fs.FileExists(dir64 + "RGui.exe").Returns(true);
 }
 private static string DeleteTempTestDir(IFileSystem fileSystem)
 {
     if (fileSystem.DirectoryExists(TestConstants.TempDirectory)) {
         fileSystem.DeleteDirectory(TestConstants.TempDirectory);
     }
     return TestConstants.TempDirectory;
 }
 private string CreateTempTestDir(IFileSystem fileSystem)
 {
     if (!fileSystem.DirectoryExists(TestConstants.TempDirectory)) {
         fileSystem.CreateDirectory(TestConstants.TempDirectory);
     }
     return TestConstants.TempDirectory;
 }
Example #47
0
        private string ResolvePackagesDirectory(IFileSystem fileSystem, string parentPath)
        {
            var possiblePackagesPath = Path.Combine(parentPath, "packages");
            if (fileSystem.DirectoryExists(possiblePackagesPath))
                return possiblePackagesPath;

            if (Path.GetPathRoot(parentPath) == parentPath)
                return null;

            return ResolvePackagesDirectory(fileSystem, Directory.GetParent(parentPath).FullName);
        }
Example #48
0
        private void GetByDirectoryPath(IFileSystem baseFileSystem, string target)
        {
            if (baseFileSystem.DirectoryExists(target))
            {
                var repositoryGroupManager = new RepositoryGroupManager(target, baseFileSystem);
                var repositoryManagers = new ConcurrentBag<RepositoryManager>(repositoryGroupManager.RepositoryManagers);

                var totalTime = new Stopwatch();
                totalTime.Start();

                int totalPackageUpdates = 0;

                bool exitWithFailure = false;
                Array.ForEach(repositoryManagers.ToArray(), (repositoryManager) =>
                    {
                        string packagesConfigDiretory = null;

                        if (repositoryManager.RepositoryConfig.Directory != null)
                            packagesConfigDiretory = repositoryManager.RepositoryConfig.Directory.FullName;
                        
                        using (var packageAggregator = new PackageAggregator(baseFileSystem, repositoryManager, new PackageEnumerator()))
                        {
                            packageAggregator.Compute((min, max) =>
                                {
                                    totalPackageUpdates += Convert.ToInt16(min);
                                    Console.WriteLine("Getting {0} distinct packages from a total of {1} from {2}",min, max,repositoryManager.RepositoryConfig.FullName);
                                },
                                Latest ? PackageReferenceEqualityComparer.IdAndAllowedVersions : PackageReferenceEqualityComparer.IdVersionAndAllowedVersions , new PackageReferenceSetResolver());

                            if (packageAggregator.PackageResolveFailures.Any())
                            {
                                LogAllPackageConstraintSatisfactionErrors(repositoryGroupManager, packageAggregator);
                                exitWithFailure = true;
                            }
                            else
                            {
                                var tempPackageConfig = packageAggregator.Save(packagesConfigDiretory);
                                InstallPackagesFromConfigFile(packagesConfigDiretory, GetPackageReferenceFile(baseFileSystem, tempPackageConfig.FullName), target);
                            }
                        }
                    });

                totalTime.Stop();

                if (exitWithFailure)
                {
                    var errorMessage = string.Format("Failed : {0} package directories, {1} packages in {2} seconds",
                                                     repositoryManagers.Count, totalPackageUpdates,
                                                     totalTime.Elapsed.TotalSeconds);
                    throw new CommandLineException(errorMessage);
                }

                Console.WriteLine(string.Format("Updated : {0} package directories, {1} packages in {2} seconds",
                                                    repositoryManagers.Count, totalPackageUpdates,
                                                    totalTime.Elapsed.TotalSeconds));
            }
        }
		protected void SetUp()
		{
			projectSerializerMock = new DynamicMock(typeof (IProjectSerializer));

			integratorMock1 = new DynamicMock(typeof (IProjectIntegrator));
			integratorMock2 = new DynamicMock(typeof (IProjectIntegrator));
			integratorMock3 = new DynamicMock(typeof (IProjectIntegrator));
			integrator1 = (IProjectIntegrator) integratorMock1.MockInstance;
			integrator2 = (IProjectIntegrator) integratorMock2.MockInstance;
			integrator3 = (IProjectIntegrator) integratorMock3.MockInstance;
            integratorMock1.SetupResult("Name", "Project 1");
			integratorMock2.SetupResult("Name", "Project 2");
			integratorMock3.SetupResult("Name", "Project 3");

			fileSystem = mocks.DynamicMock<IFileSystem>();
			executionEnvironment = mocks.DynamicMock<IExecutionEnvironment>();

			SetupResult.For(executionEnvironment.IsRunningOnWindows).Return(true);
			SetupResult.For(executionEnvironment.GetDefaultProgramDataFolder(ApplicationType.Server)).Return(applicationDataPath);
			SetupResult.For(fileSystem.DirectoryExists(applicationDataPath)).Return(true);
			mocks.ReplayAll();

			integrationQueue = null; // We have no way of injecting currently.

			configuration = new Configuration();
			project1 = new Project();
			project1.Name = "Project 1";
            integratorMock1.SetupResult("Project", project1);
			
			project2 = new Project();
			project2.Name = "Project 2";
            integratorMock2.SetupResult("Project", project1);

			mockProject = new DynamicMock(typeof(IProject));
			mockProject.SetupResult("Name", "Project 3");
            mockProject.SetupResult("QueueName", "Project 3");
            mockProject.SetupResult("QueueName", "Project 3");
            mockProjectInstance = (IProject)mockProject.MockInstance;
			mockProject.SetupResult("Name", "Project 3");
            mockProject.SetupResult("StartupMode", ProjectStartupMode.UseLastState);
            integratorMock3.SetupResult("Project", mockProjectInstance);

			configuration.AddProject(project1);
			configuration.AddProject(project2);
			configuration.AddProject(mockProjectInstance);

			integratorList = new ProjectIntegratorList();
			integratorList.Add(integrator1);
			integratorList.Add(integrator2);
			integratorList.Add(integrator3);
            
			configServiceMock = new DynamicMock(typeof (IConfigurationService));
			configServiceMock.ExpectAndReturn("Load", configuration);

			projectIntegratorListFactoryMock = new DynamicMock(typeof (IProjectIntegratorListFactory));
			projectIntegratorListFactoryMock.ExpectAndReturn("CreateProjectIntegrators", integratorList, configuration.Projects, integrationQueue);

            stateManagerMock = new DynamicMock(typeof(IProjectStateManager));
            stateManagerMock.SetupResult("CheckIfProjectCanStart", true, typeof(string));

			server = new CruiseServer((IConfigurationService) configServiceMock.MockInstance,
			                          (IProjectIntegratorListFactory) projectIntegratorListFactoryMock.MockInstance,
			                          (IProjectSerializer) projectSerializerMock.MockInstance,
                                      (IProjectStateManager)stateManagerMock.MockInstance,
									  fileSystem,
									  executionEnvironment,
                                      null);
		}
			public void SetUp()
			{
				validPath = Path.Combine("some", "valid", "path");
				
				log = Substitute.For<ILog>();
				fileSystem = Substitute.For<IFileSystem>();
				dataSource = Substitute.For<IDataSource>();
				
				fileSystem.DirectoryExists(validPath).Returns(false);
				fileSystem.ChangeDirectory(validPath, Arg.Invoke());
				
				createSiteCommand = new CreateSiteCommand(log, fileSystem, dataSource);
			}
Example #51
0
 public static void Close(IFileSystem fileSystem) {
     var folder = GetTempCsvFilesFolder();
     if (fileSystem.DirectoryExists(folder)) {
         // Note: some files may still be locked if they are opened in Excel
         try {
             fileSystem.DeleteDirectory(folder, recursive: true);
         } catch (IOException) { } catch (UnauthorizedAccessException) { }
     }
 }
Example #52
0
        // prepare NuGet dependencies, download them if required
        private static IEnumerable<string> PreparePackages(
														string scriptPath,
														IFileSystem fileSystem, IPackageAssemblyResolver packageAssemblyResolver,
														IPackageInstaller packageInstaller)
        {
            var workingDirectory = Path.GetDirectoryName(scriptPath);
            var binDirectory = Path.Combine(workingDirectory, @"bin\debug"); //TODO : ScriptCs.Constants.BinFolder

            var packages = packageAssemblyResolver.GetPackages(workingDirectory);

            packageInstaller.InstallPackages(
                                                    packages,
                                                    allowPreRelease: true);

            // current implementeation of RoslynCTP required dependencies to be in 'bin' folder
            if (!fileSystem.DirectoryExists(binDirectory))
            {
                fileSystem.CreateDirectory(binDirectory);
            }

            // copy dependencies one by one from 'packages' to 'bin'
            foreach (var assemblyName
                                    in packageAssemblyResolver.GetAssemblyNames(workingDirectory))
            {
                var assemblyFileName = Path.GetFileName(assemblyName);
                var destFile = Path.Combine(binDirectory, assemblyFileName);

                var sourceFileLastWriteTime = fileSystem.GetLastWriteTime(assemblyName);
                var destFileLastWriteTime = fileSystem.GetLastWriteTime(destFile);

                if (sourceFileLastWriteTime == destFileLastWriteTime)
                {
                    //outputCallback(string.Format("Skipped: '{0}' because it is already exists", assemblyName));
                }
                else
                {
                    fileSystem.Copy(assemblyName, destFile, overwrite: true);

                    //if (outputCallback != null)
                    //{
                    //	outputCallback(string.Format("Copy: '{0}' to '{1}'", assemblyName, destFile));
                    //}
                }

                yield return destFile;
            }
        }
Example #53
0
        private void CopyNativeBinaries(IProjectSystem projectSystem, IFileSystem packagesFileSystem, PackageName packageName)
        {
            const string nativeBinariesFolder = "NativeBinaries";

            string nativeBinariesPath = Path.Combine(packageName.Name, nativeBinariesFolder);
            if (packagesFileSystem.DirectoryExists(nativeBinariesPath))
            {
                IEnumerable<string> nativeFiles = packagesFileSystem.GetFiles(nativeBinariesPath, "*.*", recursive: true);
                foreach (string file in nativeFiles)
                {
                    string targetPath = Path.Combine(Constants.BinDirectory, file.Substring(nativeBinariesPath.Length + 1));  // skip over NativeBinaries/ word
                    using (Stream stream = packagesFileSystem.OpenFile(file)) 
                    {
                        projectSystem.AddFile(targetPath, stream);
                    }
                }
            }
        }
Example #54
0
        /// <summary>
        /// Gets all assembly references for a package
        /// </summary>
        private IEnumerable<IPackageAssemblyReference> GetAssemblyReferences(
            IFileSystem fileSystem, string packageId, SemanticVersion version, out string packageDirectory)
        {
            // REVIEW: do we need to search for all variations of versions here? (e.g. 1.0, 1.0.0, 1.0.0.0)
            string packageName = packageId + "." + version.ToString();
            if (fileSystem.DirectoryExists(packageName))
            {
                string libFolderPath = Path.Combine(packageName, Constants.LibDirectory);
                if (fileSystem.DirectoryExists(libFolderPath))
                {
                    packageDirectory = fileSystem.GetFullPath(packageName);
                    // TODO: SearchFilesWithinOneSubFolders seems fragile. In the event conventions in the lib directory change to allow more than one level of nesting, it would 
                    // not work. We should let VS perform a regular install instead of doing this. 
                    return Constants.AssemblyReferencesExtensions
                                    .Select(extension => "*" + extension)
                                    .SelectMany(extension => SearchFilesWithinOneSubFolders(fileSystem, libFolderPath, extension))
                                    .Select(assembly => new FileAssemblyReference(assembly.Substring(packageName.Length).Trim(Path.DirectorySeparatorChar)));
                }
            }

            packageDirectory = null;
            return Enumerable.Empty<IPackageAssemblyReference>();
        }
        static bool EnsureVersionAssemblyInfoFile(Arguments arguments, IFileSystem fileSystem, string fullPath)
        {
            if (fileSystem.Exists(fullPath)) return true;

            if (!arguments.EnsureAssemblyInfo) return false;

            var assemblyInfoSource = AssemblyVersionInfoTemplates.GetAssemblyInfoTemplateFor(fullPath);
            if (!string.IsNullOrWhiteSpace(assemblyInfoSource))
            {
                var fileInfo = new FileInfo(fullPath);
                if (!fileSystem.DirectoryExists(fileInfo.Directory.FullName))
                {
                    fileSystem.CreateDirectory(fileInfo.Directory.FullName);
                }
                fileSystem.WriteAllText(fullPath, assemblyInfoSource);
                return true;
            }
            Logger.WriteWarning(string.Format("No version assembly info template available to create source file '{0}'", arguments.UpdateAssemblyInfoFileName));
            return false;
        }