IsPathRooted() public static méthode

public static IsPathRooted ( string path ) : bool
path string
Résultat bool
Exemple #1
0
        // ExternalTokenHelperPath takes the configured path to a helper and expands it to
        // a full absolute path that can be executed. As of 0.5, the default token
        // helper is internal, to avoid problems running in dev mode (see GH-850 and
        // GH-783), so special assumptions of prepending "vault token-" no longer
        // apply.
        //
        // As an additional result, only absolute paths are now allowed. Looking in the
        // path or a current directory for an arbitrary executable could allow someone
        // to switch the expected binary for one further up the path (or in the current
        // directory), potentially opening up execution of an arbitrary binary.
        //~ func ExternalTokenHelperPath(path string) (string, error) {
        public static string ExternalTokenHelperPath(string path)
        {
            //~ if !filepath.IsAbs(path) {
            //~     var err error
            //~     path, err = filepath.Abs(path)
            //~     if err != nil {
            //~         return "", err
            //~     }
            //~ }
            if (!IOPath.IsPathRooted(path))
            {
                path = IOPath.GetFullPath(path);
            }

            //~ if _, err := os.Stat(path); err != nil {
            //~     return "", fmt.Errorf("unknown error getting the external helper path")
            //~ }
            //~
            //~ return path, nil
            if (File.Exists(path))
            {
                new FileInfo(path);
            }
            else if (Directory.Exists(path))
            {
                new DirectoryInfo(path);
            }
            else
            {
                throw new System.IO.FileNotFoundException();
            }

            return(path);
        }
Exemple #2
0
        public static string GetPath(string name)
        {
            var key = name.ToLower();

            if (UserPaths.ContainsKey(key))
            {
                if (Path.IsPathRooted(UserPaths[key]))
                {
                    return(UserPaths[key]);
                }
                return(Path.GetFullPath(RootPath + Path.DirectorySeparatorChar + UserPaths[key]));
            }

            if (Paths.ContainsKey(key))
            {
                if (Path.IsPathRooted(Paths[key]))
                {
                    return(Paths[key]);
                }
                return(Path.GetFullPath(RootPath + Path.DirectorySeparatorChar + Paths[key]));
            }

            var stackTrace = new StackTrace();
            var method     = stackTrace.GetFrame(1).GetMethod();

            Debug.Log("Configuration", "Path \"" + name + "\" is not present. (called by: " + method.DeclaringType.FullName + "::" + method.Name + ")", Debug.Type.Warning);
            return("");
        }
Exemple #3
0
        public static string GetPath(string res)
        {
            if (IOPath.IsPathRooted(res))
            {
                return(res);
            }

            foreach (AppFW.ResourceManager.Category category in Enum.GetValues(typeof(AppFW.ResourceManager.Category)))
            {
                var path = AppFW.ResourceManager.TryGetPath(category, res);

                if (path != null)
                {
                    return(path);
                }
            }

            AppFW.Application app = AppFW.Application.Current;
            if (app != null)
            {
                string resPath = app.DirectoryInfo.Resource + res;
                if (File.Exists(resPath))
                {
                    return(resPath);
                }
            }

            return(res);
        }
Exemple #4
0
        /// <summary>If the <paramref name="fileName "/> value points to a file in %windir%\system32 and the equivalent file exists in SysWow64 it will return the path to that file, otherwise null.</summary>
        public static String GetSysWow64File(String fileName)
        {
            if (_resolvedSystem32Path == null)
            {
                _resolvedSystem32Path = ResolvePath(@"%windir%\system32");
                _resolvedSysWow64Path = ResolvePath(@"%windir%\SysWow64");

                _resolvedProgFilePath = ResolvePath(@"%programfiles%");                 // this also covers %commonprogramfiles% and %commonprogramfiles(x86)%
                _resolvedPrgFle32Path = ResolvePath(@"%programfiles(x86)%");
            }

            if (!Path.IsPathRooted(fileName))
            {
                return(null);
            }

            ///////////////////////////////////////

            if (fileName.StartsWith(_resolvedSystem32Path, StringComparison.OrdinalIgnoreCase))
            {
                String relativePath = fileName.Substring(_resolvedSystem32Path.Length);

                if (relativePath.StartsWith("\\", StringComparison.OrdinalIgnoreCase))
                {
                    relativePath = relativePath.Substring(1);
                }

                fileName = Path.Combine(_resolvedSysWow64Path, relativePath);

                if (File.Exists(fileName))
                {
                    return(fileName);
                }
            }

            ///////////////////////////////////////

            if (fileName.StartsWith(_resolvedProgFilePath, StringComparison.OrdinalIgnoreCase))
            {
                String relativePath = fileName.Substring(_resolvedProgFilePath.Length);

                if (relativePath.StartsWith("\\"))
                {
                    relativePath = relativePath.Substring(1);
                }

                fileName = Path.Combine(_resolvedPrgFle32Path, relativePath);

                if (File.Exists(fileName))
                {
                    return(fileName);
                }
            }

            ///////////////////////////////////////

            return(null);
        }
        private string GetFullPath(string path)
        {
            if (!IOPath.IsPathRooted(path) && _options.FileSystem.CurrentDirectory != null)
            {
                path = IOPath.Combine(_options.FileSystem.CurrentDirectory, path);
            }

            return(IOPath.GetFullPath(path));
        }
        internal string GetAbsolutePath(string path)
        {
            if (Path.IsPathRooted(path))
            {
                return(path);
            }

            return(Path.Combine(_workingDirectory, path));
        }
Exemple #7
0
        private static string GetFullPath(string path)
        {
            if (!IOPath.IsPathRooted(path) && AppDomain.CurrentDomain.BaseDirectory != null)
            {
                path = IOPath.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
            }

            return IOPath.GetFullPath(path).ToUpperInvariant();
        }
Exemple #8
0
        private static string GetPath(bool makeAbsolute, string filePath, string absBasePath)
        {
            string absFilePath = Path.IsPathRooted(filePath)
                ? filePath
                : new FileInfo(Path.Combine(absBasePath, filePath)).FullName;

            return(makeAbsolute
                ? absFilePath
                : Path.GetRelativePath(absBasePath, absFilePath));
        }
Exemple #9
0
        /// <summary>Resolves environment variables inside a path</summary>
        /// <param name="root">If the resolved path is not rooted, this parameter will be intelligently prepended</param>
        public static String ResolvePath(String path, String root)
        {
            String resolved = Environment.ExpandEnvironmentVariables(path);

            if (Path.IsPathRooted(resolved))
            {
                return(resolved);
            }

            return(Path.Combine(root, resolved));

/*
 *
 *                      if( path.IndexOf('%') == -1 ) return path;
 *
 *                      StringBuilder retval = new StringBuilder();
 *                      StringBuilder currentEnvVar = new StringBuilder();
 *
 *                      Boolean inEnvVar = false;
 *                      for(int i=0;i<path.Length;i++) {
 *                              Char c = path[i];
 *
 *                              if(c == '%') inEnvVar = !inEnvVar;
 *                              if(c == '%' && inEnvVar) {
 *                                      inEnvVar = path.IndexOf('%', i) > -1; // it doesn't count if there isn't another % in the string later on
 *                                      if(inEnvVar) continue; // no point logging the % character
 *                              }
 *                              if(c == '%' && !inEnvVar) {
 *                                      continue;
 *                              }
 *
 *                              if(!inEnvVar) retval.Append( c );
 *                              else {
 *
 *                                      currentEnvVar.Append( c );
 *
 *                                      if( path[i+1] == '%' ) { // if we're at the end of an envvar; // TODO: How do I avoid an indexoutofrange?
 *                                              // actually, I don't think this will happen since the check above means we won't be inEnvVar if there isn't another one in the string
 *
 *                                              String envVar = currentEnvVar.ToString(); currentEnvVar.Length = 0;
 *                                              retval.Append( Environment.GetEnvironmentVariable( envVar ) );
 *
 *                                      }
 *                              }
 *                      }
 *
 *                      String ret = retval.ToString();
 *
 *                      if( !Path.IsPathRooted( ret ) ) {
 *
 *                              ret = Path.Combine( root, ret );
 *                      }
 *
 *                      return ret; */
        }
        private void SelectFfmpeg_Click(object sender, RoutedEventArgs e)
        {
            var output = UserSettings.All.FfmpegLocation ?? "";

            if (output.ToCharArray().Any(x => Path.GetInvalidPathChars().Contains(x)))
            {
                output = "";
            }

            //It's only a relative path if not null/empty and there's no root folder declared.
            var isRelative = !string.IsNullOrWhiteSpace(output) && !Path.IsPathRooted(output);
            var notAlt     = !string.IsNullOrWhiteSpace(output) && (UserSettings.All.FfmpegLocation ?? "").Contains(Path.DirectorySeparatorChar);

            //Gets the current directory folder, where the file is located. If empty, it means that the path is relative.
            var directory = !string.IsNullOrWhiteSpace(output) ? Path.GetDirectoryName(output) : "";

            if (!string.IsNullOrWhiteSpace(output) && string.IsNullOrWhiteSpace(directory))
            {
                directory = AppDomain.CurrentDomain.BaseDirectory;
            }

            var initial = Directory.Exists(directory) ? directory : Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            var ofd = new OpenFileDialog
            {
                FileName         = "ffmpeg",
                Filter           = "FFmpeg executable (*.exe)|*.exe", //TODO: Localize.
                Title            = LocalizationHelper.Get("Extras.FfmpegLocation.Select"),
                InitialDirectory = isRelative ? Path.GetFullPath(initial) : initial,
                DefaultExt       = ".exe"
            };

            var result = ofd.ShowDialog();

            if (!result.HasValue || !result.Value)
            {
                return;
            }

            UserSettings.All.FfmpegLocation = ofd.FileName;

            //Converts to a relative path again.
            if (isRelative && !string.IsNullOrWhiteSpace(UserSettings.All.FfmpegLocation))
            {
                var selected       = new Uri(UserSettings.All.FfmpegLocation);
                var baseFolder     = new Uri(AppDomain.CurrentDomain.BaseDirectory);
                var relativeFolder = Uri.UnescapeDataString(baseFolder.MakeRelativeUri(selected).ToString());

                //This app even returns you the correct slashes/backslashes.
                UserSettings.All.FfmpegLocation = notAlt ? relativeFolder : relativeFolder.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
            }

            CheckTools();
        }
Exemple #11
0
        private void NavigateFile(string file)
        {
            if (!Path.IsPathRooted(file))
            {
                file = Path.GetFullPath(Path.Combine(((App)Application.Current).RootPath,
                                                     this.ViewModel.Profile.ProjectName,
                                                     "Config",
                                                     file));
            }

            if (!File.Exists(file))
            {
                return;
            }

            Process.Start("explorer.exe", $"/select, \"{file}\"");
        }
 public void OpenFiles(string[] fileNames)
 {
     foreach (var f in fileNames)
     {
         try
         {
             WaitingVisible = Visibility.Visible;
             string file = f;
             if (!Path.IsPathRooted(f))
             {
                 file = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + f;
             }
             var t = _epubService.OpenFileAsync(file);
             t.ContinueWith(t1 =>
             {
                 try
                 {
                     if (t1.Result != null)
                     {
                         int index = (int)t1.Result;
                         Nodes.Add(_epubService.EpubList[index].TocNode);
                         for (int i = 0; i < Nodes.Count; i++)
                         {
                             Nodes[i].IsExpanded = false;
                         }
                         Nodes[index].IsExpanded = true;
                         Nodes[index].IsSelected = true;
                         TocSelectedItemChanged(new RoutedPropertyChangedEventArgs <object>(null, Nodes[index]));
                         //Nodes[0].Icon = ItemNode.ExpandedIcon;
                         if (_epubService.EpubList.Count > 0 && _epubService.EpubList[0].IsSpine)
                         {
                             ((ContentTabItemViewModel)ActiveItem).UseDocumentTitle = true;
                         }
                     }
                 }
                 catch (Exception) { }
                 finally { WaitingVisible = Visibility.Collapsed; }
             }, TaskScheduler.Default);// TaskScheduler.FromCurrentSynchronizationContext());
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message); WaitingVisible = Visibility.Collapsed;
         }
     }
 }
        /// <summary>
        /// Takes the picture.
        /// </summary>
        /// <param name="options">The storage options.</param>
        /// <returns>Task representing the asynchronous operation.</returns>
        /// <exception cref="NotSupportedException">No camera is present on the current device.</exception>
        public override Task <MediaFile> TakePhotoAsync(CameraMediaStorageOptions options)
        {
            // If no camera available
            if (!this.IsCameraAvailable)
            {
                throw new NotSupportedException();
            }

            // Validate options
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            // If path is rooted
            if (Path.IsPathRooted(options.Directory))
            {
                throw new ArgumentException("options.Directory must be a relative folder");
            }

            // Take the photo
            return(this.TakeMediaAsync("image/*", MediaStore.ActionImageCapture, options));
        }
Exemple #14
0
 /// <summary>
 /// Gets the size of the image from file
 /// </summary>
 /// <param name="file">The path of the file containing image</param>
 /// <returns></returns>
 public static Size GetImageSize(string file)
 {
     if (!Path.IsPathRooted(file))
     {
         file = System.Web.HttpContext.Current.Request.MapPath(file);
     }
     if (File.Exists(file))
     {
         Bitmap b = null;
         try
         {
             b = new Bitmap(file);
             return(b.Size);
         }
         finally
         {
             if (b != null)
             {
                 b.Dispose();
             }
         }
     }
     return(Size.Empty);
 }
Exemple #15
0
        public static string AbsolutePath(string path, string hintPath = null)
        {
            //If the path is absolute path no need to transform.
            if (Path.IsPathRooted(path))
            {
                return(path);
            }

            var session = Dynamo.Events.ExecutionEvents.ActiveSession;

            if (session != null && !string.IsNullOrEmpty(session.CurrentWorkspacePath))
            {
                var parent   = Path.GetDirectoryName(session.CurrentWorkspacePath);
                var filepath = Path.Combine(parent, path);
                //If hint path is null or file exists at this location return the computed path
                //If hint path doesn't exist then the relative path might be for write operation.
                if (FileSystem.FileExists(filepath) || string.IsNullOrEmpty(hintPath) || !FileSystem.FileExists(hintPath))
                {
                    return(Path.GetFullPath(filepath));
                }
            }

            return(string.IsNullOrEmpty(hintPath) ? path : hintPath);
        }
Exemple #16
0
        public static List <DropMatch> FromDropData(string rootPath, string targetPath, FileBrowserManager fileBrowserManager, FilesDragEventArgs e)
        {
            if (rootPath == null)
            {
                throw new ArgumentNullException(nameof(rootPath));
            }
            if (targetPath == null)
            {
                throw new ArgumentNullException(nameof(targetPath));
            }
            if (e == null)
            {
                throw new ArgumentNullException(nameof(e));
            }

            FilesDropData dropData = e.DropData;

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

            var matches = new List <DropMatch>();

            for (int i = 0; i < dropData.FileNames.Length; i++)
            {
                string fileName = dropData.FileNames[i];

                if (!IOPath.IsPathRooted(fileName))
                {
                    // Normal drag/drop operations have the full path. Drag/drop operations
                    // without a full path generally are Ole objects that don't point to
                    // physical files, like drag/dropping from an Outlook email or a Windows
                    // compressed folder. To get the data,
                    matches.Add(new DropMatch(fileName, i, DropMatchKind.FileVirtual));
                    continue;
                }

                var fileInfo = new FileInfo(fileName);

                if (fileInfo.Attributes.IsHidden())
                {
                    continue;
                }

                bool contained       = PathUtil.ContainsPath(rootPath, fileInfo.FullName) != PathContains.Not;
                bool ctrlKeyPressed  = (e.KeyState & 8) != 0;
                bool shiftKeyPressed = (e.KeyState & 4) != 0;

                if (PathUtil.ContainsPath(targetPath, fileInfo.DirectoryName) == PathContains.Equals)
                {
                    continue;
                }

                if (fileInfo.Attributes.IsDirectory())
                {
                    if (Directory.Exists(IOPath.Combine(targetPath, fileInfo.Name)))
                    {
                        continue;
                    }
                    if (PathUtil.ContainsPath(fileInfo.FullName, targetPath) != PathContains.Not)
                    {
                        continue;
                    }

                    var kind = contained ? DropMatchKind.DirectoryMove : DropMatchKind.DirectoryCopy;
                    if (ctrlKeyPressed && kind == DropMatchKind.DirectoryMove)
                    {
                        kind = DropMatchKind.DirectoryCopy;
                    }
                    else if (shiftKeyPressed && kind == DropMatchKind.DirectoryCopy)
                    {
                        kind = DropMatchKind.DirectoryMove;
                    }
                    matches.Add(new DropMatch(fileInfo.FullName, i, kind));
                }
                else if (fileBrowserManager != null && fileBrowserManager.Matches(fileInfo.FullName))
                {
                    var kind = contained ? DropMatchKind.FileMove : DropMatchKind.FileCopy;
                    if (ctrlKeyPressed && kind == DropMatchKind.FileMove)
                    {
                        kind = DropMatchKind.FileCopy;
                    }
                    else if (shiftKeyPressed && kind == DropMatchKind.FileCopy)
                    {
                        kind = DropMatchKind.FileMove;
                    }
                    matches.Add(new DropMatch(fileInfo.FullName, i, kind));
                }
            }

            return(matches);
        }
        static bool IsEmbeddedResourcePath(string path)
        {
            var separatorIndex = path.IndexOf(AssemblySeparator);

            return(separatorIndex >= 0 && !SystemPath.IsPathRooted(path));
        }
Exemple #18
0
        /// <summary>
        /// This helper method can be used to convert a relative path to an absolute path based on the given base
        /// path.
        /// </summary>
        /// <param name="basePath">The base path</param>
        /// <param name="relativePath">A relative path</param>
        /// <returns>An absolute path</returns>
        /// <remarks>If the base path is null or empty, the current working folder is used.</remarks>
        /// <example>
        /// <code lang="cs">
        /// string basePath = @"E:\DotNet\CS\TestProject\Source";
        /// string relativePath = @"..\Doc\Help.html";
        ///
        /// string absolutePath = FilePath.RelativeToAbsolutePath(basePath,
        ///     relativePath);
        ///
        /// Console.WriteLine(absolutePath);
        ///
        /// // Results in: E:\DotNet\CS\TestProject\Doc\Help.html
        /// </code>
        /// <code lang="vbnet">
        /// Dim basePath As String = "E:\DotNet\CS\TestProject\Source"
        /// Dim relativePath As String = "..\Doc\Help.html"
        ///
        /// Dim absolutePath As String = _
        ///     FilePath.RelativeToAbsolutePath(basePath, relativePath);
        ///
        /// Console.WriteLine(absolutePath)
        ///
        /// ' Results in: E:\DotNet\CS\TestProject\Doc\Help.html
        /// </code>
        /// </example>
        public static string RelativeToAbsolutePath(string basePath, string relativePath)
        {
            int idx;

            // If blank return the base path
            if (String.IsNullOrEmpty(relativePath))
            {
                return(basePath);
            }

            // Don't bother if already absolute
            if (IOPath.IsPathRooted(relativePath))
            {
                return(relativePath);
            }

            // If not specified, use the current folder as the base path
            if (basePath == null || basePath.Trim().Length == 0)
            {
                basePath = Directory.GetCurrentDirectory();
            }
            else
            {
                basePath = IOPath.GetFullPath(basePath);
            }

            // Remove trailing backslashes for comparison
            if (FolderPath.IsPathTerminated(basePath))
            {
                basePath = basePath.Substring(0, basePath.Length - 1);
            }

            if (relativePath == ".")
            {
                relativePath = String.Empty;
            }

            // Remove ".\" or "./" if it's there
            if (relativePath.Length > 1 && relativePath[0] == '.' &&
                (relativePath[1] == IOPath.DirectorySeparatorChar ||
                 relativePath[1] == IOPath.AltDirectorySeparatorChar))
            {
                relativePath = relativePath.Substring(2);
            }

            // Split the paths into their component parts
            string[] baseParts = basePath.Split(IOPath.DirectorySeparatorChar);
            string[] relParts  = relativePath.Split(IOPath.DirectorySeparatorChar);

            // Figure out how far to move up from the relative path
            for (idx = 0; idx < relParts.Length; ++idx)
            {
                if (relParts[idx] != "..")
                {
                    break;
                }
            }

            // If it's below the base path, just add it to the base path
            if (idx == 0)
            {
                return(FilePath.GetFullPath(basePath + IOPath.DirectorySeparatorChar + relativePath));
            }

            string absPath = String.Join(IOPath.DirectorySeparatorChar.ToString(), baseParts, 0,
                                         Math.Max(0, baseParts.Length - idx));

            absPath += IOPath.DirectorySeparatorChar + String.Join(IOPath.DirectorySeparatorChar.ToString(),
                                                                   relParts, idx, relParts.Length - idx);

            return(FilePath.GetFullPath(absPath));
        }
Exemple #19
0
        /// <summary>
        /// This helper method can be used to convert an absolute path to one that is relative to the given base
        /// path.
        /// </summary>
        /// <param name="basePath">The base path</param>
        /// <param name="absolutePath">An absolute path</param>
        /// <returns>A path to the given absolute path that is relative to the given base path</returns>
        /// <remarks>If the base path is null or empty, the current working folder is used.</remarks>
        /// <example>
        /// <code lang="cs">
        /// string basePath = @"E:\DotNet\CS\TestProject\Source";
        /// string absolutePath = @"E:\DotNet\CS\TestProject\Doc\Help.html";
        ///
        /// string relativePath = FilePath.AbsoluteToRelativePath(basePath,
        ///     absolutePath);
        ///
        /// Console.WriteLine(relativePath);
        ///
        /// // Results in: ..\Doc\Help.html
        /// </code>
        /// <code lang="vbnet">
        /// Dim basePath As String = "E:\DotNet\CS\TestProject\Source"
        /// Dim absolutePath As String = "E:\DotNet\CS\TestProject\Doc\Help.html"
        ///
        /// Dim relativePath As String = _
        ///     FilePath.AbsoluteToRelativePath(basePath, absolutePath);
        ///
        /// Console.WriteLine(relativePath)
        ///
        /// ' Results in: ..\Doc\Help.html
        /// </code>
        /// </example>
        public static string AbsoluteToRelativePath(string basePath, string absolutePath)
        {
            bool   hasBackslash = false;
            string relPath;
            int    minLength, idx;

            // If not specified, use the current folder as the base path
            if (basePath == null || basePath.Trim().Length == 0)
            {
                basePath = Directory.GetCurrentDirectory();
            }
            else
            {
                basePath = IOPath.GetFullPath(basePath);
            }

            if (absolutePath == null)
            {
                absolutePath = String.Empty;
            }

            // Just in case, make sure the path is absolute
            if (!IOPath.IsPathRooted(absolutePath))
            {
                absolutePath = FilePath.GetFullPath(absolutePath);
            }

            // Remove trailing backslashes for comparison
            if (FolderPath.IsPathTerminated(basePath))
            {
                basePath = basePath.Substring(0, basePath.Length - 1);
            }

            if (FolderPath.IsPathTerminated(absolutePath))
            {
                absolutePath = absolutePath.Substring(0, absolutePath.Length - 1);
                hasBackslash = true;
            }

            // Split the paths into their component parts
            char[]   separators = { IOPath.DirectorySeparatorChar, IOPath.AltDirectorySeparatorChar,
                                    IOPath.VolumeSeparatorChar };
            string[] baseParts = basePath.Split(separators);
            string[] absParts  = absolutePath.Split(separators);

            // Find the common base path
            minLength = Math.Min(baseParts.Length, absParts.Length);

            for (idx = 0; idx < minLength; idx++)
            {
                if (String.Compare(baseParts[idx], absParts[idx], StringComparison.OrdinalIgnoreCase) != 0)
                {
                    break;
                }
            }

            // Use the absolute path if there's nothing in common (i.e. they are on different drives or network
            // shares.
            if (idx == 0)
            {
                relPath = absolutePath;
            }
            else
            {
                // If equal to the base path, it doesn't have to go anywhere.  Otherwise, work up from the base
                // path to the common root.
                if (idx == baseParts.Length)
                {
                    relPath = String.Empty;
                }
                else
                {
                    relPath = new String(' ', baseParts.Length - idx).Replace(" ", ".." +
                                                                              IOPath.DirectorySeparatorChar);
                }

                // And finally, add the path from the common root to the absolute path
                relPath += String.Join(IOPath.DirectorySeparatorChar.ToString(), absParts, idx,
                                       absParts.Length - idx);
            }

            return((hasBackslash) ? FolderPath.TerminatePath(relPath) : relPath);
        }
Exemple #20
0
        private void LoadPage(string filename, bool isBacklink = false)
        {
            string text = "";

            try
            {
                // adjust path if not rooted (working directory is different when a file was opened with double click)
                if (!Path.IsPathRooted(filename))
                {
                    var dir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                    filename = dir + "\\" + filename;
                }
                // load text from file
                text = File.ReadAllText(filename);
            }
            catch (Exception)
            {
                models.Window.ShowErrorDialog("Could not open " + filename);
                Close();
                IsValid = false;
                return;
            }

            curDirectory  = Path.GetFullPath(Path.GetDirectoryName(filename));
            curDirectory += '/';

            var fileDirectory = curDirectory.Replace('\\', '/');

            fileDirectory = "file:///" + fileDirectory + "/";

            // correct links
            text = text.Replace("![](", "![](" + fileDirectory);

            // add back link
            if (history.Count > 0)
            {
                text += "\n[Back](back)";
            }

            history.Push(filename);

            //var pipe = new MarkdownPipeline();
            // convert markup into htm
            var pipe = new Markdig.MarkdownPipelineBuilder().UseAdvancedExtensions().Build();
            var html = Markdig.Markdown.ToHtml(text, pipe);

            // get correct pixel colors
            var bg          = (SolidColorBrush)FindResource("BackgroundBrush");
            var fg          = (SolidColorBrush)FindResource("FontBrush");
            var bgCol       = new byte[] { bg.Color.R, bg.Color.G, bg.Color.B };
            var fgCol       = new byte[] { fg.Color.R, fg.Color.G, fg.Color.B };
            var bgColString = BitConverter.ToString(bgCol).Replace("-", String.Empty);
            var fgColString = BitConverter.ToString(fgCol).Replace("-", String.Empty);

            html = $@"
<body style=""background-color:#{bgColString}; color:#{fgColString};"">
{html}
</body>
";
            // display markup in browser
            Browser.NavigateToString(html);
        }
Exemple #21
0
        private string ResolveAssemblyName(string assembly, bool isForReferenceAssembly)
        {
            // if it's a path, resolve it
            if (assembly.Contains(PathType.DirectorySeparatorChar) || assembly.Contains(PathType.AltDirectorySeparatorChar))
            {
                if (PathType.IsPathRooted(assembly))
                {
                    return(assembly);
                }
                else
                {
                    var paths = SessionState.Path.GetResolvedPSPathFromPSPath(assembly);
                    return(paths[0].Path);
                }
            }

            string refAssemblyDll = assembly;

            if (!assembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
            {
                // It could be a short assembly name or a full assembly name, but we
                // always want the short name to find the corresponding assembly file.
                var assemblyName = new AssemblyName(assembly);
                refAssemblyDll = assemblyName.Name + ".dll";
            }

            // We look up in reference/framework only when it's for resolving reference assemblies.
            // In case of 'Add-Type -AssemblyName' scenario, we don't attempt to resolve against framework assemblies because
            //   1. Explicitly loading a framework assembly usually is not necessary in PowerShell Core.
            //   2. A user should use assembly name instead of path if they want to explicitly load a framework assembly.
            if (isForReferenceAssembly)
            {
                // If it's for resolving a reference assembly, then we look in NetCoreApp ref assemblies first
                string netcoreAppRefPath = PathType.Combine(s_netcoreAppRefFolder, refAssemblyDll);
                if (File.Exists(netcoreAppRefPath))
                {
                    return(netcoreAppRefPath);
                }

                // Look up the assembly in the framework folder. This may happen when assembly is not part of
                // NetCoreApp, but comes from an additional package, such as 'Json.Net'.
                string frameworkPossiblePath = PathType.Combine(s_frameworkFolder, refAssemblyDll);
                if (File.Exists(frameworkPossiblePath))
                {
                    return(frameworkPossiblePath);
                }

                // The assembly name may point to a third-party assembly that is already loaded at run time.
                if (!assembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
                {
                    Assembly result = LoadAssemblyHelper(assembly);
                    if (result != null)
                    {
                        return(result.Location);
                    }
                }
            }

            // Look up the assembly in the current folder
            string currentFolderPath = SessionState.Path.GetResolvedPSPathFromPSPath(refAssemblyDll)[0].Path;

            if (File.Exists(currentFolderPath))
            {
                return(currentFolderPath);
            }

            ErrorRecord errorRecord = new ErrorRecord(
                new Exception(
                    String.Format(ParserStrings.ErrorLoadingAssembly, assembly)),
                "ErrorLoadingAssembly",
                ErrorCategory.InvalidOperation,
                assembly);

            ThrowTerminatingError(errorRecord);
            return(null);
        }
        public static (ImmutableArray <PythonLibraryPath> interpreterPaths, ImmutableArray <PythonLibraryPath> userPaths) ClassifyPaths(
            string root,
            IFileSystem fs,
            IEnumerable <PythonLibraryPath> fromInterpreter,
            IEnumerable <string> fromUser
            )
        {
#if DEBUG
            Debug.Assert(root == null || root.PathEquals(PathUtils.NormalizePathAndTrim(root)));
            Debug.Assert(!fromInterpreter.Any(p => !p.Path.PathEquals(PathUtils.NormalizePathAndTrim(p.Path))));
#endif

            // Clean up user configured paths.
            // 1) Normalize paths.
            // 2) If a path isn't rooted, then root it relative to the workspace root. If there is no root, just continue.
            // 3) Trim off any ending separators for consistency.
            // 4) Remove any empty paths, FS root paths (bad idea), or paths equal to the root.
            // 5) Deduplicate, preserving the order specified by the user.
            var fromUserList = fromUser
                               .Select(PathUtils.NormalizePath)
                               .Select(p => root == null || IOPath.IsPathRooted(p) ? p : IOPath.GetFullPath(IOPath.Combine(root, p))) // TODO: Replace with GetFullPath(p, root) when .NET Standard 2.1 is out.
                               .Select(PathUtils.TrimEndSeparator)
                               .Where(p => !string.IsNullOrWhiteSpace(p) && p != "/" && !p.PathEquals(root))
                               .Distinct(PathEqualityComparer.Instance)
                               .ToList();

            // Remove any interpreter paths specified in the user config so they can be reclassified.
            // The user list is usually small; List.Contains should not be too slow.
            fromInterpreter.Where(p => !fromUserList.Contains(p.Path, PathEqualityComparer.Instance))
            .Split(p => p.Type == PythonLibraryPathType.StdLib, out var stdlib, out var withoutStdlib);

            // Pull out stdlib paths, and make them always be interpreter paths.
            var interpreterPaths = stdlib;
            var userPaths        = ImmutableArray <PythonLibraryPath> .Empty;

            var allPaths = fromUserList.Select(p => new PythonLibraryPath(p))
                           .Concat(withoutStdlib.Where(p => !p.Path.PathEquals(root)));

            foreach (var p in allPaths)
            {
                // If path is within a stdlib path, then treat it as interpreter.
                if (stdlib.Any(s => fs.IsPathUnderRoot(s.Path, p.Path)))
                {
                    interpreterPaths = interpreterPaths.Add(p);
                    continue;
                }

                // If Python says it's site, then treat is as interpreter.
                if (p.Type == PythonLibraryPathType.Site)
                {
                    interpreterPaths = interpreterPaths.Add(p);
                    continue;
                }

                // If path is outside the workspace, then treat it as interpreter.
                if (root == null || !fs.IsPathUnderRoot(root, p.Path))
                {
                    interpreterPaths = interpreterPaths.Add(p);
                    continue;
                }

                userPaths = userPaths.Add(p);
            }

            return(interpreterPaths, userPaths);
        }
Exemple #23
0
        /// <summary>
        /// This is used to recursively load help page definitions
        /// </summary>
        /// <param name="page">The help page to load</param>
        /// <param name="root">The root tree node to which the page is added.  If null, it is added as a root
        /// page.</param>
        /// <param name="sandcastleDate">The Sandcastle version</param>
        private void AddHelpPage(XElement page, TreeViewItem root, string sandcastleVersion)
        {
            Assembly       asm = Assembly.GetExecutingAssembly();
            IInstallerPage pageInstance;
            TreeViewItem   node;
            Type           pageType;
            string         value;

            // Load the assembly?
            if (page.Attribute("assembly") != null)
            {
                value = page.Attribute("assembly").Value.Trim();

                if (!String.IsNullOrEmpty(value) && !IOPath.IsPathRooted(value))
                {
                    value = IOPath.Combine(Utility.BasePath, value);
                }

                if (!String.IsNullOrEmpty(value) && !assemblies.ContainsKey(value))
                {
                    if (!File.Exists(value))
                    {
                        MessageBox.Show("Unable to load installer page assembly: " + value, ApplicationTitle,
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }

                    assemblies.Add(value, Assembly.LoadFrom(value));
                }

                if (!String.IsNullOrEmpty(value))
                {
                    asm = assemblies[value];
                }
            }

            if (page.Attribute("type") == null)
            {
                throw new InvalidOperationException("Invalid installer page definition.  Missing type name.");
            }

            value = page.Attribute("type").Value.Trim();

            pageType = asm.GetType(value);

            if (pageType == null)
            {
                MessageBox.Show("Unable to load installer page type: " + value, ApplicationTitle,
                                MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            pageInstance                   = (IInstallerPage)Activator.CreateInstance(pageType);
            pageInstance.Installer         = this;
            pageInstance.SandcastleVersion = sandcastleVersion;

            pageInstance.Initialize(page);
            pageInstance.Control.Visibility = Visibility.Collapsed;

            node            = new TreeViewItem();
            node.Header     = pageInstance.PageTitle;
            node.IsExpanded = true;
            node.Name       = String.Format(CultureInfo.InvariantCulture, "P_{0}", allPages.Count);

            if (root == null)
            {
                tvPages.Items.Add(node);
            }
            else
            {
                root.Items.Add(node);
            }

            allPages.Add(pageInstance);
            pnlPages.Children.Add(pageInstance.Control);

            foreach (var childPage in page.Elements("page"))
            {
                this.AddHelpPage(childPage, node, sandcastleVersion);
            }
        }
Exemple #24
0
        private void convertButton_Click(object sender, RoutedEventArgs e)
        {
            var uwpSolutionFileLocation = uwpSolutionLocationTextBox.Text;

            if (string.IsNullOrWhiteSpace(uwpSolutionFileLocation) && !Path.IsPathRooted(uwpSolutionFileLocation))
            {
                MessageBox.Show("A valid Unity UWP Solution file must be provided.\nIt is the .sln file created by Unity when building for the Universal Windows Platform.", "Solution missing", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var uwpSolutionDirectory = Path.GetDirectoryName(uwpSolutionFileLocation);

            var projectName      = GetProjectName(uwpSolutionFileLocation);
            var namespaceName    = GetNamespaceName(projectName);
            var projectDirectory = Path.Combine(uwpSolutionDirectory, projectName);

            var displayName        = gameDisplayNameTextBox.Text;
            var displayDescription = descriptionTextBox.Text;

            int startWidth;
            int startHeight;
            int minWidth;
            int minHeight;

            try
            {
                startWidth  = int.Parse(widthTextBox.Text);
                startHeight = int.Parse(heightTextBox.Text);
                minWidth    = int.Parse(minWidthTextBox.Text);
                minHeight   = int.Parse(minHeightTextBox.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("Invalid input for one of the size fields. Whole numbers only.", "Invalid input", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            bool resizable = resizableCheckBox.IsChecked ?? false;

            try
            {
                AddGameBarPackage(uwpSolutionDirectory, projectName);
            }
            catch (Exception)
            {
                MessageBox.Show("An error occured when adding the Game Bar package.", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            try
            {
                ModifyAppManifest(uwpSolutionDirectory, projectName, true, displayName, displayDescription, startWidth, startHeight, minWidth, minHeight, resizable);
            }
            catch (Exception)
            {
                MessageBox.Show("An error occured when modifying the project's appxmanifest.", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            try
            {
                ModifyAppH(projectDirectory);
            }
            catch (Exception)
            {
                MessageBox.Show("An error occured when modifying the project's App.xaml.h file.", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            try
            {
                ModifyAppCpp(projectDirectory);
            }
            catch (Exception)
            {
                MessageBox.Show("An error occured when modifying the project's App.xaml.cpp file.", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            MessageBox.Show("Game Bar widget successfully attached to the Unity project.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
        }
Exemple #25
0
        public static HashSet <string> GetFiles(
            ResultCache cache,
            IEnumerable <string> searchablePaths,
            IEnumerable <IPattern> includePaths,
            IEnumerable <IPattern> excludePaths,
            string basePath = null)
        {
            searchablePaths = searchablePaths as string[] ?? searchablePaths.ToArray();
            includePaths    = includePaths as IPattern[] ?? includePaths.ToArray();

            if (excludePaths != null)
            {
                excludePaths = excludePaths as IPattern[] ?? excludePaths.ToArray();
            }
            else
            {
                excludePaths = new List <IPattern>();
            }

            basePath = basePath ?? "./";
            bool   returnAbsolutePaths = Path.IsPathRooted(basePath);
            string absBasePath;

            if (basePath == "./" || basePath == ".")
            {
                absBasePath = new DirectoryInfo(Directory.GetCurrentDirectory()).FullName;
            }
            else
            {
                absBasePath = new DirectoryInfo(basePath).FullName;
            }

            (int hash, bool hasResults, HashSet <string> files)cacheRequest =
                cache?.GetResultsOrReserve(
                    searchablePaths,
                    includePaths,
                    excludePaths,
                    basePath)
                ?? (0, false, null);

            if (cacheRequest.hasResults)
            {
                Log.Debug("Getting files for query hash {{{0}}} from cached results for base path '{1}':",
                          cacheRequest.hash, basePath);

                Log.IndentedCollection(cacheRequest.files, Log.Debug);
                return(cacheRequest.files);
            }

            Log.Debug("Getting files for query hash {{{0}}} using base path '{1}' and provided include/exclude paths:",
                      cacheRequest.hash, basePath);

            using (new CompositeDisposable(
                       new Log.ScopedIndent(),
                       new Log.ScopedTimer(Log.Level.Debug, "GetFiles(...)", $"{{{cacheRequest.hash,-11}}} {basePath}")))
            {
                Log.Debug("search paths:");
                Log.IndentedCollection(searchablePaths, Log.Debug);

                HashSet <string>       includeFiles;
                HashSet <GLOB>         includeGlobs;
                HashSet <RegexPattern> includeRegexes;
                HashSet <string>       excludeFiles;
                HashSet <GLOB>         excludeGlobs;
                HashSet <RegexPattern> excludeRegexes;

                (includeFiles, includeGlobs, includeRegexes) = ProcessFileValues(includePaths);
                (excludeFiles, excludeGlobs, excludeRegexes) = ProcessFileValues(excludePaths);
                var searchPathMatches = new Dictionary <string, List <PatternMatch> >();

                foreach (string currentSearchPath in searchablePaths)
                {
                    var currentMatches = new List <PatternMatch>();

                    var dir = new DirectoryInfo(new DirectoryInfo(
                                                    currentSearchPath == "./" || currentSearchPath == "."
                            ? Directory.GetCurrentDirectory()
                            : currentSearchPath)
                                                .FullName);

                    bool makeCandidatesAbsolute = Path.IsPathRooted(currentSearchPath);

                    if (!dir.Exists)
                    {
                        Log.Debug("Skipping searchable directory because it does not exist: {0}'", currentSearchPath);
                        continue;
                    }

                    string[] candidates = dir.GetFilesSafeRecursive("*")
                                          .Select(f => GetPath(makeCandidatesAbsolute, f.FullName, absBasePath))
                                          .Reverse()
                                          .ToArray();

                    DirectoryInfo[] allDirs = dir.GetDirectoriesSafeRecursive("*")
                                              .Reverse()
                                              .Concat(new[] { dir })
                                              .ToArray();

                    #region includes
                    if (includeGlobs != null && includeGlobs.Count > 0)
                    {
                        foreach (GLOB glob in includeGlobs)
                        {
                            IEnumerable <string> matchesForGlob = candidates.Where(f => glob.IsMatch(f));

                            currentMatches.AddRange(matchesForGlob.Select(
                                                        f => new PatternMatch(f, currentSearchPath, "glob \"" + glob.Pattern + "\"")));
                        }
                    }

                    if (includeRegexes != null && includeRegexes.Count > 0)
                    {
                        IEnumerable <PatternMatch> matchesForRegex = includeRegexes.SelectMany(
                            r => r.FilterMatches(candidates).Select(
                                f => new PatternMatch(f,
                                                      currentSearchPath,
                                                      r.ToString())));

                        currentMatches.AddRange(matchesForRegex);
                    }

                    var literalPatternMatches = new Dictionary <string, PatternMatch[]>();
                    if (includeFiles != null && includeFiles.Count > 0)
                    {
                        foreach (string filePattern in includeFiles.ToArray())
                        {
                            string[] matchesForFile =
                                (from dirInfo in allDirs
                                 select Path.Combine(dirInfo.FullName, filePattern)
                                 into includeFilePath
                                 where File.Exists(includeFilePath)
                                 select GetPath(makeCandidatesAbsolute, includeFilePath, absBasePath))
                                .ToArray();

                            PatternMatch[] patternMatchesForFile = matchesForFile.Select(
                                f => new PatternMatch(f, currentSearchPath, filePattern))
                                                                   .ToArray();

                            if (patternMatchesForFile.Length > 0)
                            {
                                literalPatternMatches[filePattern] = patternMatchesForFile;
                                currentMatches.AddRange(patternMatchesForFile);
                            }
                        }
                    }
                    #endregion

                    #region excludes
                    IEnumerable <PatternMatch> tempMatches = currentMatches;
                    if (excludeGlobs != null && excludeGlobs.Count > 0)
                    {
                        var excludeGlob = new CompositeGlob(excludeGlobs, null);
                        tempMatches = tempMatches.Where(m => !excludeGlob.IsMatch(m.File))
                                      .ToList(); // Helps with debugging
                    }

                    if (excludeRegexes != null && excludeRegexes.Count > 0)
                    {
                        tempMatches = tempMatches.Where(m => excludeRegexes.All(r => !r.Regex.IsMatch(m.File)))
                                      .ToList(); // Helps with debugging
                    }

                    if (excludeFiles != null && excludeFiles.Count > 0)
                    {
                        tempMatches = tempMatches.Where(m => excludeFiles.All(x => x != Path.GetFileName(m.File)))
                                      .ToList(); // Helps with debugging
                    }
                    #endregion

                    #region literal validation
                    currentMatches = tempMatches.ToList();
                    foreach (KeyValuePair <string, PatternMatch[]> kvp in literalPatternMatches)
                    {
                        PatternMatch[] patternMatchesForFile = kvp.Value;
                        if (patternMatchesForFile.Length > 1 &&
                            currentMatches.Intersect(patternMatchesForFile).Count() > 1)
                        {
                            Log.Warn("The literal pattern '{0}' matched more than one file.",
                                     kvp.Key);
                            Log.Warn("Only the first match '{0}' will be returned. See all matches below.",
                                     patternMatchesForFile.First().File);

                            int count = 0;
                            Log.IndentedCollection(patternMatchesForFile,
                                                   p => $"{p.File} (from {p.SearchPath}) {(count++ == 0 ? "*" : "")}",
                                                   Log.Warn);

                            currentMatches = currentMatches.Except(patternMatchesForFile.Skip(1)).ToList();
                        }
                    }

                    searchPathMatches[currentSearchPath] = currentMatches;
                    #endregion
                }

                #region validation
                IEnumerable <PatternMatch> allMatches   = searchPathMatches.Values.SelectMany(v => v);
                IEnumerable <PatternMatch> finalMatches = ValidateMatches(allMatches, includePaths);
                #endregion

                #region results
                HashSet <string> allMatchedFiles =
                    finalMatches.Select(m => GetPath(returnAbsolutePaths, m.File, absBasePath)).ToHashSet();

                Log.Debug("include globs:");
                Log.IndentedCollection(includeGlobs, s => s.Pattern, Log.Debug);
                Log.Debug("include regexes:");
                Log.IndentedCollection(includeRegexes, r => r.Value, Log.Debug);
                Log.Debug("include literals:");
                Log.IndentedCollection(includeFiles, Log.Debug);
                Log.Debug("exclude globs:");
                Log.IndentedCollection(excludeGlobs, s => s.Pattern, Log.Debug);
                Log.Debug("exclude regexes:");
                Log.IndentedCollection(excludeRegexes, r => r.Value, Log.Debug);
                Log.Debug("exclude literals:");
                Log.IndentedCollection(excludeFiles, Log.Debug);
                Log.Debug("matched files:");
                Log.IndentedCollection(allMatchedFiles, Log.Debug);

                cache?.CacheResults(allMatchedFiles, cacheRequest.hash);
                return(allMatchedFiles);

                #endregion
            }
        }
Exemple #26
0
 internal static bool IsPartiallyQualified(string path)
 {
     // This is much simpler than Windows where paths can be rooted, but not fully qualified (such as Drive Relative)
     // As long as the path is rooted in Unix it doesn't use the current directory and therefore is fully qualified.
     return(!Path.IsPathRooted(path));
 }