Exemple #1
0
        protected override bool Execute(VSConstants.VSStd97CmdID commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            var path = FindReferencedPath();

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

            string referencedPath;

            if (path.StartsWith("~/", StringComparison.Ordinal))
            {
                referencedPath = Path.Combine(ProjectHelpers.GetProjectFolder(TextView.TextBuffer.GetFileName()), path.Substring(2));
            }
            else
            {
                referencedPath = Path.Combine(Path.GetDirectoryName(TextView.TextBuffer.GetFileName()), path);
            }

            if (referencedPath != null)
            {
                FileHelpers.OpenFileInPreviewTab(Path.GetFullPath(referencedPath));
                return(true);
            }

            WebEssentialsPackage.DTE.StatusBar.Text = "Couldn't find " + path;

            return(false);
        }
Exemple #2
0
        private ProvisioningTemplateToolsConfiguration GetConfig(bool createIfNotExists)
        {
            var    project     = ProjectHelpers.GetActiveProject();
            string projectPath = ProjectHelpers.GetProjectFolder(project);

            return(GetConfig(projectPath, createIfNotExists));
        }
Exemple #3
0
        private string FindFile(IEnumerable <string> extensions, out int position)
        {
            ICssParser parser = CssParserLocator.FindComponent(Mef.GetContentType(LessContentTypeDefinition.LessContentType)).CreateParser();

            string root = ProjectHelpers.GetProjectFolder(TextView.TextBuffer.GetFileName());

            position = -1;
            string result = null;

            foreach (string ext in extensions)
            {
                foreach (string file in Directory.GetFiles(root, "*" + ext, SearchOption.AllDirectories))
                {
                    if (file.EndsWith(".min" + ext, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    string text  = File.ReadAllText(file);
                    int    index = text.IndexOf("." + _className, StringComparison.Ordinal);

                    if (index > -1)
                    {
                        var css     = parser.Parse(text, true);
                        var visitor = new CssItemCollector <ClassSelector>(false);
                        css.Accept(visitor);

                        var selectors = visitor.Items.Where(c => c.ClassName.Text == _className);
                        var high      = selectors.FirstOrDefault(c => c.FindType <AtDirective>() == null && (c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ","));

                        if (high != null)
                        {
                            position = high.Start;
                            return(file);
                        }

                        var medium = selectors.FirstOrDefault(c => c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ",");

                        if (medium != null)
                        {
                            position = medium.Start;
                            result   = file;
                            continue;
                        }

                        var low = selectors.FirstOrDefault();

                        if (low != null)
                        {
                            position = low.Start;
                            result   = file;
                            continue;
                        }
                    }
                }
            }

            return(result);
        }
        public async Task <XDocument> WriteSpriteRecipe()
        {
            string            root     = ProjectHelpers.GetRootFolder();
            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Indent = true
            };
            XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

            if (string.IsNullOrEmpty(root))
            {
                root = ProjectHelpers.GetProjectFolder(FileName);
            }

            ProjectHelpers.CheckOutFileFromSourceControl(FileName);

            using (XmlWriter writer = await Task.Run(() => XmlWriter.Create(FileName, settings)))
            {
                XDocument doc =
                    new XDocument(
                        new XElement("sprite",
                                     new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                                     new XAttribute(xsi + "noNamespaceSchemaLocation", "http://vswebessentials.com/schemas/v1/sprite.xsd"),
                                     new XElement("settings",
                                                  new XComment("Determines if the sprite image should be automatically optimized after creation/update."),
                                                  new XElement("optimize", Optimize.ToString().ToLowerInvariant()),
                                                  new XComment("Determines the orientation of images to form this sprite. The value must be vertical or horizontal."),
                                                  new XElement("orientation", IsVertical ? "vertical" : "horizontal"),
                                                  new XComment("The margin (in pixel) around and between the constituent images."),
                                                  new XElement("margin", Margin),
                                                  new XComment("File extension of sprite image."),
                                                  new XElement("outputType", FileExtension.ToString().ToLowerInvariant()),
                                                  new XComment("Determine whether to generate/re-generate this sprite on building the solution."),
                                                  new XElement("runOnBuild", RunOnBuild.ToString().ToLowerInvariant()),
                                                  new XComment("Use full path to generate unique class or mixin name in CSS, LESS and SASS files. Consider disabling this if you want class names to be filename only."),
                                                  new XElement("fullPathForIdentifierName", UseFullPathForIdentifierName.ToString().ToLowerInvariant()),
                                                  new XComment("Use absolute path in the generated CSS-like files. By default, the URLs are relative to sprite image file (and the location of CSS, LESS and SCSS)."),
                                                  new XElement("useAbsoluteUrl", UseAbsoluteUrl.ToString().ToLowerInvariant()),
                                                  new XComment("Specifies a custom subfolder to save files to. By default, compiled output will be placed in the same folder and nested under the original file."),
                                                  new XElement("outputDirectory", OutputDirectory),
                                                  new XComment("Specifies a custom subfolder to save CSS files to. By default, compiled output will be placed in the same folder and nested under the original file."),
                                                  new XElement("outputDirectoryForCss", CssOutputDirectory),
                                                  new XComment("Specifies a custom subfolder to save LESS files to. By default, compiled output will be placed in the same folder and nested under the original file."),
                                                  new XElement("outputDirectoryForLess", LessOutputDirectory),
                                                  new XComment("Specifies a custom subfolder to save SCSS files to. By default, compiled output will be placed in the same folder and nested under the original file."),
                                                  new XElement("outputDirectoryForScss", ScssOutputDirectory)
                                                  ),
                                     new XComment("The order of the <file> elements determines the order of the images in the sprite."),
                                     new XElement("files", BundleAssets.Select(file => new XElement("file", "/" + FileHelpers.RelativePath(root, file))))
                                     )
                        );

                doc.Save(writer);

                return(doc);
            }
        }
Exemple #5
0
            public async override void Invoke()
            {
                string file;
                string root = ProjectHelpers.GetProjectFolder(WebEssentialsPackage.DTE.ActiveDocument.FullName);

                if (CanSaveFile(root, out file))
                {
                    await MakeChanges(root, file);
                }
            }
Exemple #6
0
            public override void Invoke()
            {
                string file;
                string root = ProjectHelpers.GetProjectFolder(EditorExtensionsPackage.DTE.ActiveDocument.FullName);

                if (CanSaveFile(root, out file))
                {
                    MakeChanges(root, file);
                }
            }
Exemple #7
0
            /// <summary>
            /// This method will get the folder for the current project.  This will limit the search to the
            /// current project which is unfortunate.  Should probably extend this to include all projects
            /// in the solution at some point
            /// </summary>
            ///
            /// <remarks>
            /// Note that this method is always called on a background thread of Visual Studio.  Yet it is
            /// issuing queries to several DTE objects.  All DTE objects are really STA COM objects meaning
            /// that this method ends up running a bit of code on the UI thread of Visual Studio via
            /// COM marshalling.  It would probably be best if we just ran this one time and cached the
            /// result but for now it doesn't cause a significant delay so not adding the caching overhead
            /// </remarks>
            private static string GetProjectFolderPath()
            {
                string folder = ProjectHelpers.GetRootFolder();

                if (string.IsNullOrEmpty(folder))
                {
                    var doc = EditorExtensionsPackage.DTE.ActiveDocument;
                    if (doc != null)
                    {
                        folder = ProjectHelpers.GetProjectFolder(EditorExtensionsPackage.DTE.ActiveDocument.FullName);
                    }
                }

                return(folder);
            }
        public static SpriteDocument FromFile(string fileName)
        {
            XDocument doc    = XDocument.Load(fileName);
            string    root   = ProjectHelpers.GetProjectFolder(fileName);
            string    folder = Path.GetDirectoryName(root);

            var imageFiles = from f in doc.Descendants("file")
                             select ProjectHelpers.ToAbsoluteFilePath(f.Value, root, folder);

            SpriteDocument sprite = new SpriteDocument(fileName, imageFiles.ToArray());

            sprite.Optimize      = doc.Descendants("optimize").First().Value.Equals("true", StringComparison.OrdinalIgnoreCase);
            sprite.IsVertical    = doc.Descendants("orientation").First().Value.Equals("vertical", StringComparison.OrdinalIgnoreCase);
            sprite.FileExtension = doc.Descendants("outputType").First().Value;

            return(sprite);
        }
        /// <summary>
        /// Retrieve the string that rapresent the html to display in
        /// the preview.
        /// If an html template is found in the project folder or in the solution folder, it
        /// is returned after the place holders have been substituted.
        /// If no html template is found, the old behavior that was in place before
        /// the html template was introduced is used (a minimal html is returned with a
        /// reference to a custom stylesheet). The only change is that a custom stylesheet
        /// found in the project folder will take precedence over the one in the solution
        /// folder.
        /// </summary>
        /// <remarks>
        /// The supported placeholders are:
        ///
        /// {##SOLUTION_PATH_PLACEHOLDER##}
        /// {##PROJECT_PATH_PLACEHOLDER##}
        /// {##DOCUMENT_PATH_PLACEHOLDER##}
        /// {##MARKDOWN_HTML_PLACEHOLDER##}
        ///
        /// Note that to keep things simple, a placeholder must appear in the html template
        /// literally. there is no parsing involved.
        /// </remarks>
        /// <param name="compilerResult">The result of the markdown compilation</param>
        /// <returns>The html string</returns>
        public static string CompileHtmlDocumentString(string currentDocumentPath, string globalStylesheetPath, CompilerResult compilerResult)
        {
            // The Markdown compiler cannot return errors
            var solutionPath         = ProjectHelpers.GetSolutionFolderPath();
            var projectPath          = ProjectHelpers.GetProjectFolder(currentDocumentPath);
            var htmlTemplateFilePath = GetExistingFilesInFolders(_htmlTemplate, projectPath, solutionPath).FirstOrDefault();

            var currentDocumentPathUrl = ConvertLocalDirectoryPathToUrl(Path.GetDirectoryName(currentDocumentPath));

            if (htmlTemplateFilePath != null)
            {
                var solutionPathUrl = solutionPath == null ? currentDocumentPathUrl : ConvertLocalDirectoryPathToUrl(solutionPath);
                var projectPathUrl  = projectPath == null ? currentDocumentPathUrl : ConvertLocalDirectoryPathToUrl(projectPath);

                //Load the template and replace the placeholder with the generated html
                var htmlTemplate = File.ReadAllText(htmlTemplateFilePath);

                // TODO: Find a better way to do this(Handlerbar, HTML parsing, etc...)
                return(htmlTemplate
                       .Replace("{##SOLUTION_PATH_PLACEHOLDER##}", solutionPathUrl)
                       .Replace("{##PROJECT_PATH_PLACEHOLDER##}", projectPathUrl)
                       .Replace("{##DOCUMENT_PATH_PLACEHOLDER##}", currentDocumentPathUrl)
                       .Replace("{##MARKDOWN_HTML_PLACEHOLDER##}", compilerResult.Result));
            }

            // Keep the legacy behavior
            return(string.Format(
                       CultureInfo.InvariantCulture,
                       @"<!DOCTYPE html>
                    <html lang=""en"" xmlns=""http://www.w3.org/1999/xhtml"">
                        <head>
                            <meta charset=""utf-8"" />
                            <base href=""{0}"">                                  
                            <title>Markdown Preview</title>
                            {1}
                        </head>
                        <body>
                        {2}
                        </body>
                    </html>",
                       currentDocumentPathUrl,
                       GetStylesheet(globalStylesheetPath, projectPath, solutionPath),
                       compilerResult.Result
                       ));
        }
Exemple #10
0
            public override void Invoke()
            {
                string value = HtmlSmartTag.Element.GetAttribute("ng-controller").Value;

                if (string.IsNullOrEmpty(value))
                {
                    value = "myController";
                }

                string folder = ProjectHelpers.GetProjectFolder(EditorExtensionsPackage.DTE.ActiveDocument.FullName);
                string file;

                using (var dialog = new SaveFileDialog())
                {
                    dialog.FileName         = value + ".js";
                    dialog.DefaultExt       = ".js";
                    dialog.Filter           = "JS files | *.js";
                    dialog.InitialDirectory = folder;

                    if (dialog.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    file = dialog.FileName;
                }

                EditorExtensionsPackage.DTE.UndoContext.Open(this.DisplayText);

                string script = GetScript(value);

                File.WriteAllText(file, script);

                ProjectHelpers.AddFileToActiveProject(file);
                EditorExtensionsPackage.DTE.ItemOperations.OpenFile(file);

                EditorExtensionsPackage.DTE.UndoContext.Close();
            }
Exemple #11
0
        public async override void Invoke(CancellationToken cancellationToken)
        {
            string value = _ngController.Value;

            if (string.IsNullOrEmpty(value))
            {
                value = "myController";
            }

            string folder = ProjectHelpers.GetProjectFolder(WebEssentialsPackage.DTE.ActiveDocument.FullName);
            string file;

            using (var dialog = new SaveFileDialog())
            {
                dialog.FileName         = value + ".js";
                dialog.DefaultExt       = ".js";
                dialog.Filter           = "JS files | *.js";
                dialog.InitialDirectory = folder;

                if (dialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                file = dialog.FileName;
            }

            using (WebEssentialsPackage.UndoContext((this.DisplayText)))
            {
                string script = GetScript(value);
                await FileHelpers.WriteAllTextRetry(file, script);

                ProjectHelpers.AddFileToActiveProject(file);
                WebEssentialsPackage.DTE.ItemOperations.OpenFile(file);
            }
        }
Exemple #12
0
        private string FindRuleSetInFile(IEnumerable <string> extensions, string id, out RuleSet rule)
        {
            string root = ProjectHelpers.GetProjectFolder(peekableItem._textbuffer.GetFileName());
            string result = null;
            bool   isLow = false, isMedium = false;

            rule = null;

            foreach (string ext in extensions)
            {
                ICssParser parser = CssParserLocator.FindComponent(Mef.GetContentType(ext.Trim('.'))).CreateParser();

                foreach (string file in Directory.EnumerateFiles(root, "*" + ext, SearchOption.AllDirectories))
                {
                    if (file.EndsWith(".min" + ext, StringComparison.OrdinalIgnoreCase) ||
                        file.Contains("node_modules") ||
                        file.Contains("bower_components"))
                    {
                        continue;
                    }

                    string text  = FileHelpers.ReadAllTextRetry(file).ConfigureAwait(false).GetAwaiter().GetResult();
                    int    index = text.IndexOf("#" + id, StringComparison.Ordinal);

                    if (index == -1)
                    {
                        continue;
                    }

                    var css     = parser.Parse(text, true);
                    var visitor = new CssItemCollector <IdSelector>(false);
                    css.Accept(visitor);

                    var selectors = visitor.Items.Where(c => c.HashName.Text == "#" + id);
                    var high      = selectors.FirstOrDefault(c => c.FindType <AtDirective>() == null && (c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ","));

                    if (high != null)
                    {
                        rule = high.FindType <RuleSet>();
                        return(file);
                    }

                    var medium = selectors.FirstOrDefault(c => c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ",");

                    if (medium != null && !isMedium)
                    {
                        rule     = medium.FindType <RuleSet>();
                        result   = file;
                        isMedium = true;
                        continue;
                    }

                    var low = selectors.FirstOrDefault();

                    if (low != null && !isMedium && !isLow)
                    {
                        rule   = low.FindType <RuleSet>();
                        result = file;
                        isLow  = true;
                        continue;
                    }
                }
            }

            return(result);
        }
        public static async Task <SpriteDocument> FromFile(string fileName)
        {
            string root   = ProjectHelpers.GetProjectFolder(fileName);
            string folder = Path.GetDirectoryName(root);

            if (folder == null || root == null)
            {
                return(null);
            }

            XDocument doc = null;

            string contents = await FileHelpers.ReadAllTextRetry(fileName);

            try
            {
                doc = XDocument.Parse(contents);
            }
            catch (XmlException)
            {
                return(null);
            }

            XElement element = null;

            IEnumerable <string> imageFiles = ProjectHelpers.GetBundleConstituentFiles(doc.Descendants("file").Select(s => s.Value), root, folder, fileName);

            SpriteDocument sprite = new SpriteDocument(fileName, imageFiles.ToArray());

            element = doc.Descendants("optimize").FirstOrDefault();

            if (element != null)
            {
                sprite.Optimize = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase);
            }

            element = doc.Descendants("orientation").FirstOrDefault();

            if (element != null)
            {
                sprite.IsVertical = element.Value.Equals("vertical", StringComparison.OrdinalIgnoreCase);
            }

            element = doc.Descendants("runOnBuild").FirstOrDefault();

            if (element != null)
            {
                sprite.RunOnBuild = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase);
            }

            element = doc.Descendants("outputType").FirstOrDefault();

            if (element != null)
            {
                sprite.FileExtension = element.Value;
            }

            element = doc.Descendants("fullPathForIdentifierName").FirstOrDefault();

            if (element != null)
            {
                sprite.UseFullPathForIdentifierName = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase);
            }

            element = doc.Descendants("outputDirectory").FirstOrDefault();

            if (element != null)
            {
                sprite.OutputDirectory = element.Value;
            }

            element = doc.Descendants("useAbsoluteUrl").FirstOrDefault();

            if (element != null)
            {
                sprite.UseAbsoluteUrl = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase);
            }

            element = doc.Descendants("outputDirectoryForCss").FirstOrDefault();

            if (element != null)
            {
                sprite.CssOutputDirectory = element.Value;
            }

            element = doc.Descendants("outputDirectoryForLess").FirstOrDefault();

            if (element != null)
            {
                sprite.LessOutputDirectory = element.Value;
            }

            element = doc.Descendants("outputDirectoryForScss").FirstOrDefault();

            if (element != null)
            {
                sprite.ScssOutputDirectory = element.Value;
            }

            return(sprite);
        }
        public static SpriteDocument FromFile(string fileName)
        {
            string    root    = ProjectHelpers.GetProjectFolder(fileName);
            string    folder  = Path.GetDirectoryName(root);
            XDocument doc     = XDocument.Load(fileName);
            XElement  element = null;

            var imageFiles = from f in doc.Descendants("file")
                             select ProjectHelpers.ToAbsoluteFilePath(f.Value, root, folder);

            SpriteDocument sprite = new SpriteDocument(fileName, imageFiles.ToArray());

            element = doc.Descendants("optimize").FirstOrDefault();

            if (element != null)
            {
                sprite.Optimize = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase);
            }

            element = doc.Descendants("orientation").FirstOrDefault();

            if (element != null)
            {
                sprite.IsVertical = element.Value.Equals("vertical", StringComparison.OrdinalIgnoreCase);
            }

            element = doc.Descendants("outputType").FirstOrDefault();

            if (element != null)
            {
                sprite.FileExtension = element.Value;
            }

            element = doc.Descendants("fullPathForIdentifierName").FirstOrDefault();

            if (element != null)
            {
                sprite.UseFullPathForIdentifierName = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase);
            }

            element = doc.Descendants("useAbsoluteUrl").FirstOrDefault();

            if (element != null)
            {
                sprite.UseAbsoluteUrl = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase);
            }

            element = doc.Descendants("outputDirectoryForCss").FirstOrDefault();

            if (element != null)
            {
                sprite.CssOutputDirectory = element.Value;
            }

            element = doc.Descendants("outputDirectoryForLess").FirstOrDefault();

            if (element != null)
            {
                sprite.LessOutputDirectory = element.Value;
            }

            element = doc.Descendants("outputDirectoryForScss").FirstOrDefault();

            if (element != null)
            {
                sprite.ScssOutputDirectory = element.Value;
            }

            return(sprite);
        }