Example #1
0
			public void SetUp()
			{
				string nestedDependencyFilename = Path.Combine("a", "b", "variables.less");
				string nestedDependencyText = "@import \"dependency.less\";";
				
				dependencyFilename = Path.Combine("a", "b", "dependency.less");
				var dependencyText = "@color: #4D926F;";
				
				source = "@import \"variables.less\";#header {color: @color;}h2 {color: @color;}";
				expected = "#header{color:#4d926f}h2{color:#4d926f}";
				
				arguments = new Dictionary<string, object> {
					{
						"item",
						new Dictionary<string, object> {
							{ "filename", Path.Combine("a", "b", "c.less") }
						}
					}
				};
				
				fileSystem = Substitute.For<IFileSystem>();
				fileSystem.FileExists(nestedDependencyFilename).Returns(true);
				fileSystem.ReadStringFromFile(nestedDependencyFilename).Returns(nestedDependencyText);
				fileSystem.FileExists(dependencyFilename).Returns(true);
				fileSystem.ReadStringFromFile(dependencyFilename).Returns(dependencyText);
				
				lessFilter = new LessFilter(fileSystem);
			}
Example #2
0
    private void SetVirtualPath(ITemplate template)
    {
        var path = template.OriginalPath;

        if (string.IsNullOrWhiteSpace(path))
        {
            // we need to discover the path
            path = string.Concat(template.Alias, ".cshtml");
            if (_viewsFileSystem?.FileExists(path) ?? false)
            {
                template.VirtualPath = _viewsFileSystem.GetUrl(path);
                return;
            }

            path = string.Concat(template.Alias, ".vbhtml");
            if (_viewsFileSystem?.FileExists(path) ?? false)
            {
                template.VirtualPath = _viewsFileSystem.GetUrl(path);
                return;
            }
        }
        else
        {
            // we know the path already
            template.VirtualPath = _viewsFileSystem?.GetUrl(path);
        }

        template.VirtualPath = string.Empty; // file not found...
    }
        public static string Execute(string fileParameterValue, IFileSystem fileSystem)
        {
            if (string.IsNullOrEmpty(fileParameterValue))
            {
                throw new ArgumentException(Resources.FileParameterMustBeSpecified);
            }

            if (!fileParameterValue.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
            {
                var error = string.Format(CultureInfo.CurrentCulture,
                    Resources.PowerShellScriptFileMustBeSpecifiedFormat,
                    fileParameterValue);

                throw new ArgumentException(error);
            }

            var filePath = fileSystem.GetFullPath(fileParameterValue);
            if (!fileSystem.FileExists(filePath))
            {
                var error = string.Format(CultureInfo.CurrentCulture,
                    Resources.PowerShellScriptFileDoesNotExistFormat,
                    fileParameterValue);

                throw new ArgumentException(error);
            }

            return filePath;
        }
        public string WriteSolution(IFileSystem fs, string script, IVisualStudioSolution solution, IList<ProjectItem> nestedItems = null)
        {
            if (nestedItems == null)
            {
                nestedItems = new List<ProjectItem>();
            }

            var launcher = Path.Combine(fs.TempPath, "launcher-" + Guid.NewGuid().ToString() + ".sln");

            if (fs.FileExists(launcher))
            {
                fs.FileDelete(launcher);
            }

            var currentDir = fs.CurrentDirectory;
            var scriptcsPath = Path.Combine(fs.HostBin, "scriptcs.exe");
            var scriptcsArgs = string.Format("{0} -debug -loglevel info", script);
            _root = new DirectoryInfo { Name = "Solution Items", FullPath = currentDir};
            var projectGuid = Guid.NewGuid();

            solution.AddScriptcsProject(scriptcsPath, currentDir, scriptcsArgs, false, projectGuid);
            GetDirectoryInfo(fs, currentDir, _root);
            AddDirectoryProject(solution, fs, _root, _nullGuid, nestedItems);
            solution.AddGlobal(projectGuid, nestedItems);
            fs.WriteToFile(launcher, solution.ToString());
            return launcher;
        }
        /// <summary>
        /// Create a new instance of PackageReferenceFile, taking into account the project name.
        /// </summary>
        /// <remarks>
        /// If projectName is not empty and the file packages.&lt;projectName&gt;.config 
        /// exists, use it. Otherwise, use the value specified by 'path' for the config file name.
        /// </remarks>
        public PackageReferenceFile(IFileSystem fileSystem, string path, string projectName)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException("fileSystem");
            }

            if (String.IsNullOrEmpty(path))
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "path");
            }

            _fileSystem = fileSystem;

            if (!String.IsNullOrEmpty(projectName))
            {
                string pathWithProjectName = ConstructPackagesConfigFromProjectName(projectName);
                if (_fileSystem.FileExists(pathWithProjectName))
                {
                    _path = pathWithProjectName;
                }
            }

            if (_path == null)
            {
                _path = path;
            }
        }
Example #6
0
File: Teaser.cs Project: Davgus/El
 private string GetReizedUrl(IFileSystem fs, string imageSize)
 {
     string resizedUrl = ImagesUtility.GetResizedPath(ImageUrl, imageSize);
     if (fs.FileExists(resizedUrl))
         return resizedUrl;
     return ImageUrl;
 }
Example #7
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);
        }
		internal static string ExtractFont(string name, IApplicationPaths paths, IFileSystem fileSystem)
        {
            var filePath = Path.Combine(paths.ProgramDataPath, "fonts", name);

			if (fileSystem.FileExists(filePath))
            {
                return filePath;
            }

            var namespacePath = typeof(PlayedIndicatorDrawer).Namespace + ".fonts." + name;
            var tempPath = Path.Combine(paths.TempDirectory, Guid.NewGuid().ToString("N") + ".ttf");
			fileSystem.CreateDirectory(Path.GetDirectoryName(tempPath));

            using (var stream = typeof(PlayedIndicatorDrawer).Assembly.GetManifestResourceStream(namespacePath))
            {
                using (var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    stream.CopyTo(fileStream);
                }
            }

			fileSystem.CreateDirectory(Path.GetDirectoryName(filePath));

            try
            {
				fileSystem.CopyFile(tempPath, filePath, false);
            }
            catch (IOException)
            {

            }

            return tempPath;
        }
Example #9
0
        public static Assignment FillAssignmentDetailsFromXml(Assignment a, IFileSystem fileSystem, bool includeServerFiles)
        {
            if (a == null)
            {
                return null;    //no active assignment
            }

            string path = Path.Combine(a.Path, "assignment.xml");

            if (fileSystem.FileExists(path))
            {
                XmlDocument doc = fileSystem.LoadXml(path);

                a.FriendlyName = GetNodeValue(doc, "Assignment/DisplayName");
                //a.Tagline = GetNodeValue(doc, "Assignment/Hint");

                a.Difficulty = int.Parse(GetNodeValue(doc, "Assignment/Difficulty"));
                a.Author = GetNodeValue(doc, "Assignment/Author");
                a.Category = GetNodeValue(doc, "Assignment/Category");

                a.InterfaceNameToImplement = GetNodeValue(doc, "Assignment/Rules/InterfaceNameToImplement");
                a.ClassNameToImplement = GetNodeValue(doc, "Assignment/Rules/ClassNameToImplement");

                //a.ClassFileName = GetNodeValue(doc, "Assignment/Files/ClassFile");
                //a.InterfaceFileName = GetNodeValue(doc, "Assignment/Files/InterfaceFile");

                //a.UnitTestClientFileName = GetNodeValue(doc, "Assignment/Files/NunitTestFileClient");
                //a.UnitTestServerFileName = GetNodeValue(doc, "Assignment/Files/NunitTestFileServer");

                //a.CaseFileName = GetNodeValue(doc, "Assignment/Files/Case");
                a.AssignmentFiles = new List<AssignmentFile>();
                XmlNode fileNode = doc.SelectSingleNode("Assignment/Files");
                foreach (XmlNode fileChildNode in fileNode.ChildNodes)
                {
                    string nodeName = fileChildNode.Name;
                    string fileName = fileChildNode.InnerText;

                    string filepath = Path.Combine(a.Path, fileName);
                    if (File.Exists(filepath))
                    {
                        if (includeServerFiles || (nodeName != "NunitTestFileServer" && nodeName != "ServerFileToCopy"))
                        {
                            AssignmentFile assignmentFile = new AssignmentFile();
                            assignmentFile.Name = nodeName;
                            assignmentFile.FileName = fileName;
                            assignmentFile.Data = FacadeHelpers.ReadByteArrayFromFile(filepath);
                            a.AssignmentFiles.Add(assignmentFile);
                        }
                    }
                }
            }
            else
            {
                throw new ApplicationException("Details for the assignment could not be found");
            }
            return a;
        }
Example #10
0
 public void StartUp()
 {
     if (FileSystem == null)
     {
         FileSystem = IsolatedStorageFileSystem.GetForApplication();
         if (FileSystem.FileExists(_LOG_FILE_PATH))
             FileSystem.DeleteFile(_LOG_FILE_PATH);
     }
 }
Example #11
0
        public StreamFile(IFileSystem fileSystem, string path, bool readOnly)
        {
            file = fileSystem.FileExists(path) ? fileSystem.OpenFile(path, readOnly) : fileSystem.CreateFile(path);

            endPointer = file.Length;
            fileStream = new StreamFileStream(this);

            ownsFile = true;
        }
 public static IFileInfo Delete(IFileSystem fileSystem, string path) {
     var fi = Substitute.For<IFileInfo>();
     fi.FullName.Returns(path);
     fi.Exists.Returns(false);
     fi.Directory.Returns((IDirectoryInfo)null);
     fileSystem.FileExists(path).Returns(false);
     try {
         fileSystem.GetFileAttributes(path).Throws<FileNotFoundException>();
     } catch (IOException) { }
     return fi;
 }
Example #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FileTaskResult"/> class from a <see cref="FileInfo"/>.
        /// </summary>
        /// <param name="file">The <see cref="FileInfo"/>.</param>
        /// <param name="deleteAfterMerge">Delete file after merging.</param>
        /// <param name="fileSystem">IFileSystem instance, allows this task to interact with the file system in a testable way.</param>
        public FileTaskResult(FileInfo file, bool deleteAfterMerge, IFileSystem fileSystem)
        {
            this.deleteAfterMerge = deleteAfterMerge;
            this.dataSource = file;
            this.fileSystem = fileSystem;

            if (!fileSystem.FileExists(file.FullName))
            {
                throw new CruiseControlException("File not found: " + file.FullName);
            }
        }
		public DefaultPackagePathResolver(IFileSystem fileSystem, bool useSideBySidePaths)
		{
			if (fileSystem == null) {
				throw new ArgumentNullException("fileSystem");
			}
			_fileSystem = fileSystem;
			bool excludeVersionMarkerDoesntExist = !_fileSystem.FileExists("ExcludeVersion");
			_useSideBySidePaths = excludeVersionMarkerDoesntExist && useSideBySidePaths;
			if (!useSideBySidePaths)
				_fileSystem.AddFileWithCheck("ExcludeVersion", (Stream st) => { st.WriteByte(49); st.Flush(); });
		}
Example #15
0
        protected WritableXapFile(string inputPath, string outputPath, IFileSystem fileSystem)
            : base(inputPath, fileSystem)
        {
            FileSystem = fileSystem;
            OutputPath = outputPath;

            if (fileSystem.FileExists(outputPath))
                fileSystem.FileDelete(outputPath);

            OutputArchive = fileSystem.OpenArchive(OutputPath, ZipArchiveMode.Create);
            Debug.Assert(OutputArchive != null);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RepositoryManager"/> class.
        /// </summary>
        /// <param name="repositoryConfig">The repository.config file to parse.</param>
        /// <param name="repositoryEnumerator">The repository enumerator.</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 RepositoryManager(string repositoryConfig, IRepositoryEnumerator repositoryEnumerator, IFileSystem fileSystem)
        {
            Contract.Requires(fileSystem != null);
            this.fileSystem = fileSystem;

            if (fileSystem.FileExists(repositoryConfig) && repositoryConfig.EndsWith("repositories.config"))
                RepositoryConfig = new FileInfo(fileSystem.GetFullPath(repositoryConfig));
            else
                throw new ArgumentOutOfRangeException("repository");

            PackageReferenceFiles = repositoryEnumerator.GetPackageReferenceFiles(RepositoryConfig);// GetPackageReferenceFiles();
        }
        public ContentFolderService(IFileSystem fileSystem)
        {
            _fileSystem = fileSystem;

            _fileNames.OnMissing =
                name =>
                {
                    return
                        _directories.FirstValue(
                            dir => { return _fileSystem.FileExists(dir, name) ? FileSystem.Combine(dir, name) : null; });
                };
        }
Example #18
0
			public void SetUp()
			{
				string fakeConfigFile = @"property_one: one";

				string fakeRulesFile = @"Compile(""*"", (context) => {
	// Do Nothing
});
Route(""*"", (context) => {
	return string.Empty;
});
Layout(""*"", ""layout-filter"");";
				
				log = Substitute.For<ILog>();
				fileSystem = Substitute.For<IFileSystem>();
				fileSystem.FileExists("config.yaml").Returns(true);
				fileSystem.ReadStringFromFile("config.yaml").Returns(fakeConfigFile);
				fileSystem.FileExists("Rules").Returns(true);
				fileSystem.ReadStringFromFile("Rules").Returns(fakeRulesFile);
				
				loader = new Loader(log, fileSystem);
			}
Example #19
0
        public bool VerifyInstallation(ISupportedRVersionRange svr = null, IFileSystem fs = null, ICoreShell coreShell = null) {
            if (_isValid.HasValue) {
                return _isValid.Value;
            }

            _isValid = false;

            svr = svr ?? new SupportedRVersionRange();
            fs = fs ?? new FileSystem();

            // Normalize path so it points to R root and not to bin or bin\x64
            string rDllPath = Path.Combine(BinPath, "R.dll");
            string rGraphAppPath = Path.Combine(BinPath, "Rgraphapp.dll");
            string rTermPath = Path.Combine(BinPath, "RTerm.exe");
            string rScriptPath = Path.Combine(BinPath, "RScript.exe");
            string rGuiPath = Path.Combine(BinPath, "RGui.exe");

            try {
                if (fs.FileExists(rDllPath) && fs.FileExists(rTermPath) &&
                    fs.FileExists(rScriptPath) && fs.FileExists(rGraphAppPath) &&
                    fs.FileExists(rGuiPath)) {

                    var fileVersion = GetRVersionFromBinary(fs, rDllPath);
                    _isValid = IsSameVersion(fileVersion, Version) && svr.IsCompatibleVersion(Version);
                    if (!_isValid.Value) {
                        coreShell?.ShowMessage(
                            string.Format(CultureInfo.InvariantCulture, Resources.Error_UnsupportedRVersion,
                            Version.Major, Version.Minor, Version.Build, svr.MinMajorVersion, svr.MinMinorVersion, "*",
                            svr.MaxMajorVersion, svr.MaxMinorVersion, "*"), MessageButtons.OK);
                    }
                } else {
                    coreShell?.ShowMessage(string.Format(CultureInfo.InvariantCulture, Resources.Error_CannotFindRBinariesFormat, InstallPath), MessageButtons.OK);
                }
            } catch (Exception ex) when (ex is IOException || ex is ArgumentException || ex is UnauthorizedAccessException) {
                coreShell?.ShowErrorMessage(
                    string.Format(CultureInfo.InvariantCulture, Resources.Error_ExceptionAccessingPath, InstallPath, ex.Message));
            }

            return _isValid.Value;
        }
Example #20
0
        internal static int CheckCommandLineOptions(Options options, IFileSystem fileSystem)
        {
            if (!fileSystem.FileExists(options.Input))
            {
                Console.WriteLine(Res.Errors.InputFileDoesNotExist, options.Input);
                return 2;
            }

            if (options.Sources == null || options.Sources.Length == 0)
            {
                Console.WriteLine(Res.Errors.AtLeastOneSourceFileRequired);
                return 1;
            }

            var missingFiles = options.Sources.Where(f => !fileSystem.FileExists(f)).ToList();
            if (missingFiles.Count > 0 && !options.IgnoreMissing)
            {
                Console.WriteLine(Res.Errors.SourceFilesMissing, @"  " + String.Join("  \r\n", missingFiles));
                return 3;
            }

            return 0;
        }
Example #21
0
 internal static XDocument GetOrCreateDocument(XName rootName, IFileSystem fileSystem, string path)
 {
     if (fileSystem.FileExists(path)) {
         try {
             using (Stream configSream = fileSystem.OpenFile(path)) {
                 return XDocument.Load(configSream);
             }
         }
         catch (FileNotFoundException) {
             return CreateDocument(rootName, fileSystem, path);
         }
     }
     return CreateDocument(rootName, fileSystem, path);
 }
        public static IFileInfo Create(IFileSystem fileSystem, string path) {
            var fi = Substitute.For<IFileInfo>();
            fi.FullName.Returns(path);
            fi.Exists.Returns(true);
            fi.Directory.Returns((IDirectoryInfo)null);
            fileSystem.FileExists(path).Returns(true);

            try {
                fileSystem.GetFileAttributes(path);
            } catch (IOException) {
                default(FileAttributes).Returns(FileAttributes.Normal);
            }

            return fi;
        }
Example #23
0
        public AttachmentModel(IFileSystem fileSytem, IMessageAttachment attachment)
        {
            _fileSystem = fileSytem;

            BackupPath = attachment.Path;

            if (string.IsNullOrEmpty(BackupPath) || !_fileSystem.FileExists(BackupPath))
            {
                throw new AttachmentOpenException("Can't find expected attachment file: " + BackupPath);
            }

            OrignalFilename = attachment.OriginalFilename;

            _tempCopyPath = null;
        }
    public static bool ApplyCodingStyle(this IChromiumSourceFiles chromiumSourceFiles, IFileSystem fileSystem, ITextSnapshotLine line) {
      // Check document is part of a Chromium source repository
      ITextDocument document;
      if (!line.Snapshot.TextBuffer.Properties.TryGetProperty<ITextDocument>(typeof(ITextDocument), out document))
        return false;

      var path = document.FilePath;
      if (!PathHelpers.IsAbsolutePath(path))
        return false;

      if (!fileSystem.FileExists(new FullPath(path)))
        return false;

      return chromiumSourceFiles.ApplyCodingStyle(document.FilePath);
    }
Example #25
0
 internal static XDocument GetOrCreateDocument(XName rootName, IFileSystem fileSystem, string path)
 {
     if (fileSystem.FileExists(path))
     {
         try
         {
             return GetDocument(fileSystem, path);
         }
         catch (FileNotFoundException)
         {
             return CreateDocument(rootName, fileSystem, path);
         }
     }
     return CreateDocument(rootName, fileSystem, path);
 }
Example #26
0
        /// <summary>
        /// An internal constructor MAINLY INTENDED FOR TESTING THE CLASS. But, the product code is only expected to use the static Instance property
        /// Only catches FileNotFoundException. Will throw all exceptions including other IOExceptions and XmlExceptions for invalid xml and so on
        /// </summary>
        /// <param name="fileSystem"></param>
        /// <param name="path"></param>
        internal ConfigurationDefaults(IFileSystem fileSystem, string path)
        {
            try
            {
                if (fileSystem.FileExists(path))
                {
                    _settingsManager = new Settings(fileSystem, path);
                }
            }
            catch (FileNotFoundException)
            {
            }

            // Intentionally, we don't catch all IOExceptions, XmlException or other file related exceptions like UnAuthorizedAccessException
            // This way, administrator will become aware of the failures when the ConfigurationDefaults file is not valid or permissions are not set properly
        }
 /// <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 #28
0
        public async Task TransferFile(string source, string destinationFile, Action <ProgressUpdatedEvent> progressCallback)
        {
            using (var resp = await _httpClient.GetAsync(new Uri(source), Timeout.InfiniteTimeSpan, HttpCompletionOption.ResponseHeadersRead))
            {
                var contentType = resp.Content.Headers.ContentType;

                if (contentType != null && contentType.MediaType.Contains("text"))
                {
                    throw new InvalidDownloadUrlException(source, $"[ContentType={contentType.MediaType}]");
                }

                if (_fileSystem.FileExists(destinationFile))
                {
                    _fileSystem.DeleteFile(destinationFile);
                }

                var maxValue = resp.Content.Headers.ContentLength ?? 0;

                var progress = new ProgressUpdatedEvent
                {
                    MaxValue = maxValue
                };

                using (var httpStream = await resp.Content.ReadAsStreamAsync())
                {
                    var tempFile = $"{destinationFile}.APPGET_DOWNLOAD";

                    using (var tempFileStream = _fileSystem.Open(tempFile, FileMode.Create, FileAccess.ReadWrite))
                    {
                        var buffer = new byte[BUFFER_LENGTH];
                        int len;
                        while ((len = httpStream.Read(buffer, 0, BUFFER_LENGTH)) > 0)
                        {
                            tempFileStream.Write(buffer, 0, len);
                            progress.Value += len;
                            progressCallback(progress);
                        }
                    }

                    progress.IsCompleted = true;
                    progressCallback(progress);
                    _fileSystem.Move(tempFile, destinationFile);
                }
            }
        }
Example #29
0
        private void LoadExeFs(IFileSystem codeFs, out Npdm metaData)
        {
            if (codeFs.FileExists("/main.npdm"))
            {
                Logger.PrintInfo(LogClass.Loader, "Loading main.npdm...");

                metaData = new Npdm(codeFs.OpenFile("/main.npdm", OpenMode.Read).AsStream());
            }
            else
            {
                Logger.PrintWarning(LogClass.Loader, "NPDM file not found, using default values!");

                metaData = GetDefaultNpdm();
            }

            List <IExecutable> staticObjects = new List <IExecutable>();

            void LoadNso(string filename)
            {
                foreach (DirectoryEntry file in codeFs.EnumerateEntries($"{filename}*"))
                {
                    if (Path.GetExtension(file.Name) != string.Empty)
                    {
                        continue;
                    }

                    Logger.PrintInfo(LogClass.Loader, $"Loading {file.Name}...");

                    NxStaticObject staticObject = new NxStaticObject(codeFs.OpenFile(file.FullPath, OpenMode.Read).AsStream());

                    staticObjects.Add(staticObject);
                }
            }

            TitleID = CurrentTitle = metaData.Aci0.TitleId.ToString("x16");

            LoadNso("rtld");
            LoadNso("main");
            LoadNso("subsdk");
            LoadNso("sdk");

            ContentManager.LoadEntries();

            ProgramLoader.LoadStaticObjects(this, metaData, staticObjects.ToArray());
        }
Example #30
0
        /// <summary>
        /// Determines whether [is saver enabled for item] [the specified saver].
        /// </summary>
        /// <param name="saver">The saver.</param>
        /// <param name="item">The item.</param>
        /// <param name="updateType">Type of the update.</param>
        /// <param name="includeDisabled">if set to <c>true</c> [include disabled].</param>
        /// <returns><c>true</c> if [is saver enabled for item] [the specified saver]; otherwise, <c>false</c>.</returns>
        private bool IsSaverEnabledForItem(IMetadataSaver saver, IHasMetadata item, ItemUpdateType updateType, bool includeDisabled)
        {
            var options = GetMetadataOptions(item);

            try
            {
                var isEnabledFor = saver.IsEnabledFor(item, updateType);

                if (!includeDisabled)
                {
                    if (options.DisabledMetadataSavers.Contains(saver.Name, StringComparer.OrdinalIgnoreCase))
                    {
                        return(false);
                    }

                    if (!item.IsSaveLocalMetadataEnabled())
                    {
                        if (updateType >= ItemUpdateType.MetadataEdit)
                        {
                            var fileSaver = saver as IMetadataFileSaver;

                            // Manual edit occurred
                            // Even if save local is off, save locally anyway if the metadata file already exists
                            if (fileSaver == null || !isEnabledFor || !_fileSystem.FileExists(fileSaver.GetSavePath(item)))
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            // Manual edit did not occur
                            // Since local metadata saving is disabled, consider it disabled
                            return(false);
                        }
                    }
                }

                return(isEnabledFor);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error in {0}.IsEnabledFor", ex, saver.Name);
                return(false);
            }
        }
Example #31
0
        protected bool ExecuteCommon(IEnumerable <string> inputParams)
        {
            var resolver = new ParameterResolver <ParamId>(Constants.CommandName.Reference + " " + Name, new []
            {
                new StringParameterSpecification <ParamId>
                {
                    Identifier = ParamId.ClientName,
                    Short      = Constants.ReferenceCommandOptions.Client,
                    Verbose    = Constants.ReferenceCommandOptions.VerboseClient
                },
                new StringParameterSpecification <ParamId>
                {
                    Identifier = ParamId.ServerName,
                    Short      = Constants.ReferenceCommandOptions.Server,
                    Verbose    = Constants.ReferenceCommandOptions.VerboseServer
                }
            });

            var(error, stringParams, _) = resolver.ResolveParams(inputParams);

            if (error != null)
            {
                _outputMessages = new MessageLines {
                    { error, string.Empty }
                };
                return(false);
            }

            _serverName = stringParams[ParamId.ServerName];
            _clientName = stringParams[ParamId.ClientName];

            _outputMessages = new MessageLines();

            // check if client appioproj file exists
            _clientFullName = _fileSystem.CombinePaths(_clientName, _clientName + Constants.FileExtension.Appioproject);
            if (!_fileSystem.FileExists(_clientFullName))
            {
                AppioLogger.Warn(LoggingText.ReferenceClientAppioprojFileNotFound);
                _outputMessages.Add(string.Format(OutputText.ReferenceClientAppioprojFileNotFound, _clientFullName), string.Empty);
                return(false);
            }

            // exit with success
            return(true);
        }
Example #32
0
    public Stream GetFileContentStream(string filepath)
    {
        IFileSystem?fileSystem = GetFileSystem(filepath);

        if (fileSystem?.FileExists(filepath) == false)
        {
            return(Stream.Null);
        }

        try
        {
            return(fileSystem !.OpenFile(filepath));
        }
        catch
        {
            return(Stream.Null); // deal with race conds
        }
    }
        public IEnumerable <string> ReadFile(
            RelativePath relativePath,
            Func <FullPath, IEnumerable <string>, IEnumerable <string> > postProcessing)
        {
            foreach (var directoryName in PossibleDirectoryNames())
            {
                var path = directoryName.Combine(relativePath);
                if (_fileSystem.FileExists(path))
                {
                    Logger.LogInfo("Using configuration file at \"{0}\"", path);
                    return(postProcessing(path, _fileSystem.ReadAllLines(path)).ToReadOnlyCollection());
                }
            }

            throw new FileLoadException(
                      string.Format("Could not load configuration file \"{0}\" from the following locations:{1}", relativePath,
                                    PossibleDirectoryNames().Aggregate("", (x, y) => x + "\n" + y)));
        }
Example #34
0
 private void OpenDocument(VsHierarchy hierarchy, NodeViewModel node, bool openWith = false)
 {
     Logger.WrapActionInvocation(
         () => {
         if (!_fileSystem.FileExists(new FullPath(node.FullPathString)))
         {
             return;
         }
         if (openWith)
         {
             _openDocumentHelper.OpenDocumentWith(node.FullPathString, hierarchy, node.ItemId, view => null);
         }
         else
         {
             _openDocumentHelper.OpenDocument(node.FullPathString, view => null);
         }
     });
 }
Example #35
0
        private static string GetCurrentDataString(IFileSystem fs)
        {
            string dbFilePath = Path.Combine(fs.GetCurrentDirectory(), DatabaseFileName);

            if (!fs.FileExists(dbFilePath))
            {
                return(null);
            }

            FileStream file = fs.OpenFile(dbFilePath, FileMode.Open);

            file.Position = 0;

            using (StreamReader reader = new StreamReader(file, Encoding.UTF8))
            {
                return(reader.ReadToEnd());
            }
        }
Example #36
0
        public static void WriteAllText(this IFileSystem fileSystem, string path, string contents)
        {
            Guard.NotEmpty(path, nameof(path));
            Guard.NotEmpty(contents, nameof(contents));

            if (fileSystem.FileExists(path))
            {
                fileSystem.DeleteFile(path);
            }

            var file = fileSystem.CreateFile(path);

            using (var stream = file.OpenWrite())
                using (var streamWriter = new StreamWriter(stream))
                {
                    streamWriter.Write(contents);
                }
        }
Example #37
0
        public IEnumerable <string> GetAssemblyNames(string workingDirectory)
        {
            var packages = GetPackages(workingDirectory).ToList();

            if (!packages.Any())
            {
                return(Enumerable.Empty <string>());
            }

            var packageFile = Path.Combine(workingDirectory, _fileSystem.PackagesFile);
            var packageDir  = Path.Combine(workingDirectory, _fileSystem.PackagesFolder);

            var foundAssemblyPaths = new List <string>();

            LoadFiles(packageDir, packages, foundAssemblyPaths, _fileSystem.FileExists(packageFile));

            return(foundAssemblyPaths);
        }
Example #38
0
        /// <summary>
        /// Tries to save a stream in the storage provider.
        /// </summary>
        /// <param name="path">The relative path to the file to be created.</param>
        /// <param name="inputStream">The stream to be saved.</param>
        /// <returns>True if success; False otherwise.</returns>
        public static bool TrySaveStream(this IFileSystem fileSystem, string path, Stream inputStream)
        {
            try
            {
                if (fileSystem.FileExists(path))
                {
                    return(false);
                }

                fileSystem.SaveStream(path, inputStream);
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Example #39
0
    public long GetFileSize(string filename)
    {
        IFileSystem?fileSystem = GetFileSystem(filename);

        if (fileSystem?.FileExists(filename) == false)
        {
            return(-1);
        }

        try
        {
            return(fileSystem !.GetSize(filename));
        }
        catch
        {
            return(-1); // deal with race conds
        }
    }
Example #40
0
        /// <summary>
        /// Asynchronously tries to save a stream in the storage provider.
        /// </summary>
        /// <param name="path">The relative path to the file to be created.</param>
        /// <param name="inputStream">The stream to be saved.</param>
        /// <returns>True if success; False otherwise.</returns>
        public static async Task <bool> TrySaveStreamAsync(this IFileSystem fileSystem, string path, Stream inputStream)
        {
            try
            {
                if (fileSystem.FileExists(path))
                {
                    return(false);
                }

                await fileSystem.SaveStreamAsync(path, inputStream);
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Example #41
0
        public static async Task WriteAllTextAsync(this IFileSystem fileSystem, string path, string contents, Encoding encoding = null)
        {
            Guard.NotEmpty(path, nameof(path));
            Guard.NotEmpty(contents, nameof(contents));

            if (fileSystem.FileExists(path))
            {
                fileSystem.DeleteFile(path);
            }

            var file = fileSystem.CreateFile(path);

            using (var stream = file.OpenWrite())
                using (var streamWriter = new StreamWriter(stream, encoding ?? new UTF8Encoding(false, true)))
                {
                    await streamWriter.WriteAsync(contents);
                }
        }
Example #42
0
        private static async Task CreateCsvAndStartProcess(IREvaluationResultInfo result, IRSession session, string fileName, IFileSystem fileSystem, IProcessServices processServices)
        {
            await TaskUtilities.SwitchToBackgroundThread();

            var sep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
            var dec = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

            using (var e = await session.BeginEvaluationAsync()) {
                var csvData = await e.EvaluateAsync <byte[]>($"rtvs:::export_to_csv({result.Expression}, sep={sep.ToRStringLiteral()}, dec={dec.ToRStringLiteral()})", REvaluationKind.Normal);

                fileSystem.FileWriteAllBytes(fileName, csvData);
            }

            if (fileSystem.FileExists(fileName))
            {
                processServices.Start(fileName);
            }
        }
Example #43
0
 public static IEnumerable <DiscFileInfo> GetFilesFromPath(this IFileSystem system, string path)
 {
     if (system.FileExists(path))
     {
         yield return(system.GetFileInfo(path));
     }
     else if (system.DirectoryExists(path))
     {
         foreach (var fileInfo in system.GetDirectoryInfo(path).GetFiles())
         {
             yield return(fileInfo);
         }
     }
     else
     {
         Console.WriteLine($"File or folder '{path}' does not exist.");
     }
 }
        private void ShowHtml(string url)
        {
            const uint REUSE_EXISTING_BROWSER_IF_AVAILABLE = 0;

            if (!_fileSystem.FileExists(url))
            {
                _output.WriteLine(LocalizedStrings.CannotSaveReport, url);
            }
            else if (_browserService == null)
            {
                _output.WriteLine(LocalizedStrings.CannotViewReport);
            }
            else
            {
                IVsWindowFrame browserFrame;
                var            errCode = _browserService.Navigate(url, REUSE_EXISTING_BROWSER_IF_AVAILABLE, out browserFrame);
            }
        }
Example #45
0
        private string GetMsBuildPath(IFileSystem fileSystem, IEnvironmentSystem environmentSystem)
        {
            var msBuildPaths = new[]
            {
                environmentSystem.ExpandEnvironmentVariables(@"%ProgramFiles%\MSBuild\12.0\bin\msbuild.exe"),
                environmentSystem.ExpandEnvironmentVariables(@"%SystemDrive%\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe")
            };

            foreach (var path in msBuildPaths)
            {
                if (fileSystem.FileExists(path))
                {
                    return(path);
                }
            }

            throw new Exception("MsBuild.exe was not found on the machine.");
        }
        private IList <string> GetValidFiles(IProgressMonitor progressMonitor, IEnumerable <string> files)
        {
            var validFiles = new List <string>();

            foreach (string file in files)
            {
                var filePath = Path.GetFullPath(file);

                if (fileSystem.FileExists(filePath))
                {
                    validFiles.Add(filePath);
                }

                progressMonitor.Worked(1);
            }

            return(validFiles);
        }
Example #47
0
        public bool Execute(CreateBottleInput input, IFileSystem fileSystem)
        {
            if (fileSystem.FileExists(input.ZipFileFlag) && !input.ForceFlag)
            {
                WriteZipFileAlreadyExists(input.ZipFileFlag);
                return(true);
            }

            // Delete the file if it exists?
            if (fileSystem.PackageManifestExists(input.PackageFolder))
            {
                fileSystem.DeleteFile(input.ZipFileFlag);
                return(CreatePackage(input, fileSystem));
            }

            WritePackageManifestDoesNotExist(input.PackageFolder);
            return(false);
        }
Example #48
0
        private static string FindTemplateAssertExists(Project project, IFileSystem fileSystem, string template)
        {
            string templateFullPath = template;

            if (!Path.IsPathRooted(templateFullPath))
            {
                var templateProjectItem = project.GetProjectItem(templateFullPath);
                if (templateProjectItem != null)
                {
                    templateFullPath = templateProjectItem.GetFullPath();
                }
            }
            if (!fileSystem.FileExists(templateFullPath))
            {
                throw new FileNotFoundException(string.Format("Cannot find template at '{0}'", templateFullPath));
            }
            return(templateFullPath);
        }
Example #49
0
 internal static XDocument GetOrCreateDocument(XName rootName, IFileSystem fileSystem, string path)
 {
     if (fileSystem.FileExists(path))
     {
         try
         {
             using (var configSream = fileSystem.OpenFile(path))
             {
                 return(XDocument.Load(configSream));
             }
         }
         catch (Exception)
         {
             return(CreateDocument(rootName, fileSystem, path));
         }
     }
     return(CreateDocument(rootName, fileSystem, path));
 }
Example #50
0
        public static void OpenLogFile(this IFileSystem fileSystem, string filename)
        {
            if (!filename.EndsWith(".log"))
            {
                filename += ".log";
            }

            var path = filename.ToLogPath();

            if (fileSystem.FileExists(path))
            {
                fileSystem.LaunchEditor(path);
            }
            else
            {
                Console.WriteLine("File {0} does not exist", path);
            }
        }
Example #51
0
        private static string GetGitPath(IEnvironment environment, IFileSystem fileSystem)
        {
            string programName = PlatformUtils.IsWindows() ? "git.exe" : "git";

            // Use the GIT_EXEC_PATH environment variable if set
            if (environment.Variables.TryGetValue(Constants.EnvironmentVariables.GitExecutablePath,
                                                  out string gitExecPath))
            {
                string candidatePath = Path.Combine(gitExecPath, programName);
                if (fileSystem.FileExists(candidatePath))
                {
                    return(candidatePath);
                }
            }

            // Otherwise try to locate the git(.exe) on the current PATH
            return(environment.LocateExecutable(programName));
        }
        public static ITerrificNetConfig LoadTerrificConfiguration(string basePath, string fileName, IFileSystem fileSystem)
        {
            if (basePath == null)
            {
                throw new ArgumentNullException("basePath");
            }

            //if (!fileSystem.DirectoryExists(null))
            //	throw new ConfigurationException(string.Format("The base path for the configuration doesn't exist in {0}.", fileSystem.BasePath));

            var basePathInfo = PathInfo.Create(basePath);
            var configFile   = fileSystem.Path.Combine(basePathInfo, PathInfo.Create(fileName));

            if (!fileSystem.FileExists(configFile.RemoveStartSlash()))
            {
                throw new ConfigurationException(string.Format("Could not find configuration in path '{0}' in {1}.", configFile, fileSystem.BasePath));
            }

            TerrificNetConfig config;

            using (var reader = new JsonTextReader(new StreamReader(fileSystem.OpenRead(configFile))))
            {
                config = new JsonSerializer().Deserialize <TerrificNetConfig>(reader);
            }

            return(new TerrificNetPathInfo
            {
                Assets = config.Assets,
                ViewPath =
                    fileSystem.Path.Combine(basePathInfo,
                                            GetDefaultValueIfNotSet(config.ViewPath, fileSystem, basePathInfo, PathInfo.Create("views"))),
                ModulePath = fileSystem.Path.Combine(basePathInfo,
                                                     GetDefaultValueIfNotSet(config.ModulePath, fileSystem, basePathInfo, PathInfo.Create("components"),
                                                                             PathInfo.Create("modules"))),
                AssetPath =
                    fileSystem.Path.Combine(basePathInfo,
                                            GetDefaultValueIfNotSet(config.AssetPath, fileSystem, basePathInfo, PathInfo.Create("assets"))),
                DataPath =
                    fileSystem.Path.Combine(basePathInfo,
                                            GetDefaultValueIfNotSet(config.DataPath, fileSystem, basePathInfo, PathInfo.Create("project"),
                                                                    PathInfo.Create("data"))),
                Minify = config.Minify
            });
        }
Example #53
0
        public static bool EnableForItem(Video item, IFileSystem fileSystem)
        {
            var container = item.Container;

            if (string.Equals(container, MediaContainer.Iso, StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (string.Equals(container, MediaContainer.Bluray, StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }
            if (string.Equals(container, MediaContainer.Dvd, StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (string.Equals(container, MediaContainer.BlurayIso, StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }
            if (string.Equals(container, MediaContainer.DvdIso, StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (item.IsShortcut)
            {
                return(false);
            }

            if (!item.IsCompleteMedia)
            {
                return(false);
            }

            if (item.IsFileProtocol && !fileSystem.FileExists(item.Path))
            {
                return(false);
            }

            return(true);
        }
Example #54
0
        private bool ValidateModel(string modelPath)
        {
            // model path validation
            if (modelPath == string.Empty)
            {
                AppioLogger.Warn(LoggingText.InvalidInformationModelMissingModelFile);
                _outputMessages.Add(OutputText.ImportInformationModelCommandMissingModelPath, string.Empty);
                return(false);
            }

            if (_fileSystem.GetInvalidPathChars().Any(modelPath.Contains))
            {
                AppioLogger.Warn(string.Format(LoggingText.InvalidInformationModelPath, modelPath));
                _outputMessages.Add(string.Format(OutputText.ImportInformationModelCommandInvalidModelPath, modelPath), string.Empty);
                return(false);
            }

            if (!_fileSystem.FileExists(modelPath))
            {
                AppioLogger.Warn(string.Format(LoggingText.InvalidInformationModelNotExistingPath, modelPath));
                _outputMessages.Add(string.Format(OutputText.ImportInformationModelCommandNotExistingModelPath, modelPath), string.Empty);
                return(false);
            }

            // model file name/extension validation
            var modelFileName = _fileSystem.GetFileName(modelPath);

            if (_fileSystem.GetExtension(modelPath) != Constants.FileExtension.InformationModel)
            {
                AppioLogger.Warn(string.Format(LoggingText.InvalidInformationModelExtension, modelFileName));
                _outputMessages.Add(string.Format(OutputText.ImportInformationModelCommandInvalidModelExtension, modelFileName), string.Empty);
                return(false);
            }

            // validate model against UANodeSet xsd file
            if (!_modelValidator.Validate(modelPath, Resources.Resources.UANodeSetXsdFileName))
            {
                AppioLogger.Warn(string.Format(LoggingText.NodesetValidationFailure, modelPath));
                _outputMessages.Add(string.Format(OutputText.NodesetValidationFailure, modelPath), string.Empty);
                return(false);
            }

            return(true);
        }
        protected HttpResponseMessage GetInternal(string path)
        {
            var pathInfo = PathInfo.Create(path);

            var filePath = _fileSystem.Path.Combine(this.FilePath, pathInfo);

            if (!_fileSystem.FileExists(filePath))
            {
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }

            var eTag = new EntityTagHeaderValue(string.Concat("\"", _fileSystem.GetFileInfo(filePath).Etag, "\""));

            if (Request.Headers.IfNoneMatch != null)
            {
                foreach (var noneMatch in Request.Headers.IfNoneMatch)
                {
                    if (eTag.Equals(noneMatch))
                    {
                        return(new HttpResponseMessage(HttpStatusCode.NotModified));
                    }
                }
            }

            var stream  = _fileSystem.OpenRead(filePath);
            var message = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(stream)
            };

            message.Content.Headers.ContentType = new MediaTypeHeaderValue(GetMimeType(_fileSystem.Path.GetExtension(pathInfo).ToLower()));
            message.Headers.ETag = eTag;

            // remove Pragma
            message.Headers.Remove("Pragma");

            message.Headers.CacheControl = new CacheControlHeaderValue {
                Private = true, MaxAge = TimeSpan.Zero
            };
            message.Content.Headers.Expires = DateTimeOffset.Now.Subtract(TimeSpan.FromSeconds(1));
            //message.Content.Headers.LastModified

            return(message);
        }
Example #56
0
        public virtual void CreateSize(Url virtualPath, byte[] image, ImageSizeElement size)
        {
            if (!size.ResizeOnUpload)
            {
                return;
            }

            string resizedPath = ImagesUtility.GetResizedPath(virtualPath, size.Name);

            using (var sourceStream = new MemoryStream(image))
            {
                if (size.Width <= 0 && size.Height <= 0)
                {
                    using (var destinationStream = files.OpenFile(resizedPath))
                    {
                        int b;
                        while ((b = sourceStream.ReadByte()) != -1)
                        {
                            destinationStream.WriteByte((byte)b);
                        }
                    }
                }
                else
                {
                    if (!files.FileExists(resizedPath) || size.Replace)
                    {
                        // Delete the image before writing.
                        // Fixes a weird bug where overwriting the original file while it still exists
                        //  leaves the resized image the with the exact same file size as the original even
                        //  though it should be smaller.
                        if (files.FileExists(resizedPath))
                        {
                            files.DeleteFile(resizedPath);
                        }

                        using (var destinationStream = files.OpenFile(resizedPath))
                        {
                            resizer.Resize(sourceStream, new ImageResizeParameters(size.Width, size.Height, size.Mode)
                            {
                                Quality = size.Quality
                            }, destinationStream);
                        }
                    }
                }
            }
        }
Example #57
0
        public Logger(IFileSystem fileSystem)
        {
            //Create the StreamWriter which the logger will use for outputting to file
            _fileSystem = fileSystem;

            if (!fileSystem.FileExists(_LOG_FILE_PATH))
            {
                _logFileStream = fileSystem.CreateFile(_LOG_FILE_PATH);
            }
            else
            {
                _logFileStream = fileSystem.OpenFile(_LOG_FILE_PATH, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            }

            _logFileStreamWriter = new StreamWriter(_logFileStream);
            //Since we are logging, set autoflush to true for immediate writes
            _logFileStreamWriter.AutoFlush = true;
            _logFileStreamWriter.WriteLine("------------ New Buttercup Session (" + DateTime.Now + ") ------------" + Environment.NewLine);
        }
Example #58
0
        public void Write(IFileSystem fs, ContentItem item, XmlTextWriter writer)
        {
            string url = item[Name] as string;
            if(!string.IsNullOrEmpty(url))
            {
                string path = url;
                if(fs.FileExists(path))
                {
                    using(ElementWriter ew = new ElementWriter("file", writer))
                    {
                        ew.WriteAttribute("url", url);

                        byte[] fileContents = ReadFully(fs.OpenFile(path));
                        string base64representation = Convert.ToBase64String(fileContents);
                        ew.Write(base64representation);
                    }
                }
            }
        }
Example #59
0
        public static async Task OpenDataCsvApp(IREvaluationResultInfo result, IApplicationShell appShell, IFileSystem fileSystem, IProcessServices processServices) {
            await appShell.SwitchToMainThreadAsync();

            if (Interlocked.Exchange(ref _busy, 1) > 0) {
                return;
            }

            var workflow = appShell.ExportProvider.GetExportedValue<IRInteractiveWorkflowProvider>().GetOrCreate();
            var session = workflow.RSession;

            var folder = GetTempCsvFilesFolder();
            if (!Directory.Exists(folder)) {
                Directory.CreateDirectory(folder);
            }

            var pss = appShell.ExportProvider.GetExportedValue<IProjectSystemServices>();
            var variableName = result.Name ?? _variableNameReplacement;
            var csvFileName = MakeCsvFileName(appShell, pss, variableName);

            var file = pss.GetUniqueFileName(folder, csvFileName, "csv", appendUnderscore: true);

            string currentStatusText;
            var statusBar = appShell.GetGlobalService<IVsStatusbar>(typeof(SVsStatusbar));
            statusBar.GetText(out currentStatusText);

            try {
                statusBar.SetText(Resources.Status_WritingCSV);
                appShell.ProgressDialog.Show(async (p, ct) => await CreateCsvAndStartProcess(result, session, file, fileSystem, p, ct), Resources.Status_WritingCSV, 100, 500);
                if (fileSystem.FileExists(file)) {
                    processServices.Start(file);
                }
            } catch (Exception ex) when (ex is Win32Exception || ex is IOException || ex is UnauthorizedAccessException) {
                appShell.ShowErrorMessage(string.Format(CultureInfo.InvariantCulture, Resources.Error_CannotOpenCsv, ex.Message));
            } finally {
                statusBar.SetText(currentStatusText);
            }

            Interlocked.Exchange(ref _busy, 0);
        }
Example #60
0
        public static ITerrificNetConfig LoadTerrificConfiguration(string basePath, string fileName, IFileSystem fileSystem)
        {
            if (basePath == null)
                throw new ArgumentNullException("basePath");

			//if (!fileSystem.DirectoryExists(null))
			//	throw new ConfigurationException(string.Format("The base path for the configuration doesn't exist in {0}.", fileSystem.BasePath));

            var basePathInfo = PathInfo.Create(basePath);
            var configFile = fileSystem.Path.Combine(basePathInfo, PathInfo.Create(fileName));

            if (!fileSystem.FileExists(configFile.RemoveStartSlash()))
                throw new ConfigurationException(string.Format("Could not find configuration in path '{0}' in {1}.", configFile, fileSystem.BasePath));

            TerrificNetConfig config;
            using (var reader = new JsonTextReader(new StreamReader(fileSystem.OpenRead(configFile))))
            {
                config = new JsonSerializer().Deserialize<TerrificNetConfig>(reader);
            }

            return new TerrificNetPathInfo
            {
                Assets = config.Assets,
                ViewPath =
                    fileSystem.Path.Combine(basePathInfo,
                        GetDefaultValueIfNotSet(config.ViewPath, fileSystem, basePathInfo, PathInfo.Create("views"))),
                ModulePath = fileSystem.Path.Combine(basePathInfo,
                    GetDefaultValueIfNotSet(config.ModulePath, fileSystem, basePathInfo, PathInfo.Create("components"),
                        PathInfo.Create("modules"))),
                AssetPath =
                    fileSystem.Path.Combine(basePathInfo,
                        GetDefaultValueIfNotSet(config.AssetPath, fileSystem, basePathInfo, PathInfo.Create("assets"))),
                DataPath =
                    fileSystem.Path.Combine(basePathInfo,
                        GetDefaultValueIfNotSet(config.DataPath, fileSystem, basePathInfo, PathInfo.Create("project"),
                            PathInfo.Create("data"))),
				Minify = config.Minify
            };
        }