public async static Task <Dictionary <string, string> > WatchFiles(BundleDocument document, Func <string, bool, Task> updateBundle)
        {
            Dictionary <string, string> files = new Dictionary <string, string>();

            if (document == null)
            {
                return(null);
            }

            await new BundleFileObserver().AttachFileObserver(document.FileName, document.FileName, updateBundle);

            foreach (string asset in document.BundleAssets)
            {
                string absolute = asset.Contains(":\\") ? asset : ProjectHelpers.ToAbsoluteFilePath(asset, document.FileName);

                if (File.Exists(absolute))
                {
                    if (!files.ContainsKey(absolute))
                    {
                        files.Add(absolute, "/" + FileHelpers.RelativePath(ProjectHelpers.GetProjectFolder(document.FileName), asset));

                        await new BundleFileObserver().AttachFileObserver(absolute, document.FileName, updateBundle);
                    }
                }
                else
                {
                    EditorExtensionsPackage.DTE.ItemOperations.OpenFile(document.FileName);
                    Logger.ShowMessage(String.Format(CultureInfo.CurrentCulture, "Bundle error: The file '{0}' doesn't exist", asset));

                    return(null);
                }
            }

            return(files);
        }
Esempio n. 2
0
        private static void UpdateBundle(string changedFile, bool isBuild)
        {
            bool isDir = Directory.Exists(changedFile);

            string dir = isDir ? changedFile : ProjectHelpers.GetProjectFolder(changedFile);

            if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir))
            {
                return;
            }

            //if (dir.Contains("."))
            //{
            //    dir = Path.GetDirectoryName(dir);
            //}

            foreach (string file in Directory.GetFiles(dir, "*" + _ext, SearchOption.AllDirectories))
            {
                if (file.IndexOf("\\app_data\\", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    continue;
                }

                XmlDocument doc     = GetXmlDocument(file);
                bool        enabled = false;

                if (doc != null)
                {
                    XmlNode bundleNode = doc.SelectSingleNode("//bundle");
                    if (bundleNode == null)
                    {
                        continue;
                    }

                    XmlNodeList nodes = doc.SelectNodes("//file");
                    foreach (XmlNode node in nodes)
                    {
                        string relative = node.InnerText;
                        string absolute = ProjectHelpers.ToAbsoluteFilePath(relative, dir).Replace("/", "\\").Replace("\\\\", "\\");

                        if (changedFile != null && absolute.Equals(changedFile.Replace("\\\\", "\\"), StringComparison.OrdinalIgnoreCase))
                        {
                            enabled = true;
                            break;
                        }
                    }

                    if (isBuild && bundleNode.Attributes["runOnBuild"] != null && bundleNode.Attributes["runOnBuild"].InnerText == "true")
                    {
                        enabled = true;
                    }

                    if (enabled)
                    {
                        WriteBundleFile(file, doc);
                    }
                }
            }
        }
        public static string GetFileName(string text)
        {
            try
            {
                if (!string.IsNullOrEmpty(text))
                {
                    if (text.StartsWith("data:", StringComparison.Ordinal))
                    {
                        return(text);
                    }

                    string imageUrl = text.Trim(new[] { '\'', '"' });
                    //if (!_imageExtensions.Contains(Path.GetExtension(imageUrl)))
                    //    return null;

                    string filePath = string.Empty;

                    if (text.StartsWith("//", StringComparison.Ordinal))
                    {
                        text = "http:" + text;
                    }

                    if (text.StartsWith("http://", StringComparison.Ordinal) || text.Contains(";base64,"))
                    {
                        return(text);
                    }
                    else if (imageUrl.StartsWith("/", StringComparison.Ordinal))
                    {
                        string root = ProjectHelpers.GetProjectFolder(EditorExtensionsPackage.DTE.ActiveDocument.FullName);
                        if (root.Contains("://"))
                        {
                            return(root + imageUrl);
                        }
                        else if (!string.IsNullOrEmpty(root))
                        {
                            filePath = root + imageUrl;// new FileInfo(root).Directory + imageUrl;
                        }
                    }
                    else if (EditorExtensionsPackage.DTE.ActiveDocument != null)
                    {
                        FileInfo      fi  = new FileInfo(EditorExtensionsPackage.DTE.ActiveDocument.FullName);
                        DirectoryInfo dir = fi.Directory;
                        while (imageUrl.Contains("../"))
                        {
                            imageUrl = imageUrl.Remove(imageUrl.IndexOf("../", StringComparison.Ordinal), 3);
                            dir      = dir.Parent;
                        }

                        filePath = Path.Combine(dir.FullName, imageUrl.Replace("/", "\\"));
                    }

                    return(File.Exists(filePath) ? filePath : "pack://application:,,,/WebEssentials2013;component/Resources/nopreview.png");
                }
            }
            catch
            { }

            return(null);
        }
Esempio n. 4
0
        ///<summary>Converts a relative URL to an absolute path on disk, as resolved from the specified file.</summary>
        private static string ToAbsoluteFilePath(string relativeUrl, ProjectItem file)
        {
            if (file == null)
            {
                return(null);
            }

            var baseFolder = file.Properties == null ? null : ProjectHelpers.GetProjectFolder(file);

            return(ToAbsoluteFilePath(relativeUrl, GetProjectFolder(file), baseFolder));
        }
Esempio n. 5
0
        public async Task <XDocument> WriteBundleRecipe()
        {
            string root = ProjectHelpers.GetRootFolder();

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

            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Indent = true
            };
            XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

            ProjectHelpers.CheckOutFileFromSourceControl(FileName);

            using (XmlWriter writer = await Task.Run(() => XmlWriter.Create(FileName, settings)))
            {
                XDocument doc = new XDocument(
                    new XElement("bundle",
                                 new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                                 new XAttribute(xsi + "noNamespaceSchemaLocation", "http://vswebessentials.com/schemas/v1/bundle.xsd"),
                                 new XElement("settings",
                                              new XComment("Determines if the bundle file should be automatically optimized after creation/update."),
                                              new XElement("minify", Minified.ToString().ToLowerInvariant()),
                                              new XComment("Determine whether to generate/re-generate this bundle on building the solution."),
                                              new XElement("runOnBuild", RunOnBuild.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("The order of the <file> elements determines the order of the files in the bundle."),
                                 new XElement("files", BundleAssets.Select(file => new XElement("file", GetRelativePath(file, root))))
                                 )
                    );

                if (isCss)
                {
                    doc.Descendants("runOnBuild").FirstOrDefault().AddAfterSelf(
                        new XComment("Use absolute path in the generated CSS files. By default, the URLs are relative to generated bundled CSS file."),
                        new XElement("adjustRelativePaths", AdjustRelativePaths.ToString().ToLowerInvariant())
                        );
                }

                doc.Save(writer);

                return(doc);
            }
        }
Esempio n. 6
0
        private async static Threading.Task WriteBundleRecipe(string filePath, IEnumerable <ProjectItem> files, string output)
        {
            string            projectRoot = ProjectHelpers.GetProjectFolder(files.ElementAt(0).FileNames[1]);
            StringBuilder     sb          = new StringBuilder();
            XmlWriterSettings settings    = new XmlWriterSettings();

            settings.Indent = true;

            using (XmlWriter writer = XmlWriter.Create(sb, settings))
            {
                writer.WriteStartElement("bundle");
                writer.WriteAttributeString("minify", "true");
                writer.WriteAttributeString("runOnBuild", "true");
                writer.WriteAttributeString("output", output);
                writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
                writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation", null, "http://vswebessentials.com/schemas/v1/bundle.xsd");
                writer.WriteComment("The order of the <file> elements determines the order of the file contents when bundled.");

                foreach (ProjectItem item in files)
                {
                    string relative = item.IsLink() ? item.FileNames[1] : "/" + FileHelpers.RelativePath(projectRoot, item.FileNames[1]);
                    writer.WriteElementString("file", relative);
                }

                writer.WriteEndElement();
            }

            sb.Replace(Encoding.Unicode.WebName, Encoding.UTF8.WebName);

            ProjectHelpers.CheckOutFileFromSourceControl(filePath);
            await FileHelpers.WriteAllTextRetry(filePath, sb.ToString());

            ProjectHelpers.AddFileToActiveProject(filePath, "None");

            _dte.ItemOperations.OpenFile(filePath);

            //TODO: Use XLINQ
            XmlDocument doc = await GetXmlDocument(filePath);

            if (doc == null)
            {
                return;
            }

            await Dispatcher.CurrentDispatcher.BeginInvoke(
                new Action(() => WriteBundleFile(filePath, doc).DoNotWait("writing " + filePath + "file")), DispatcherPriority.ApplicationIdle, null);
        }
        protected override bool Execute(uint commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            _path = _path.TrimStart('~').Trim();
            string openFile      = EditorExtensionsPackage.DTE.ActiveDocument.FullName;
            string projectFolder = ProjectHelpers.GetProjectFolder(openFile);
            string absolute      = ProjectHelpers.ToAbsoluteFilePath(_path, projectFolder);

            if (File.Exists(absolute))
            {
                OpenFileInPreviewTab(absolute);
                return(true);
            }

            EditorExtensionsPackage.DTE.StatusBar.Text = "Couldn't find " + _path;

            return(false);
        }
        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);
        }
Esempio n. 9
0
        private async static Threading.Task UpdateBundle(string changedFile, bool isBuild)
        {
            string absolutePath = ProjectHelpers.FixAbsolutePath(changedFile);
            bool   isDir        = Directory.Exists(changedFile);
            string dir          = isDir ? changedFile : ProjectHelpers.GetProjectFolder(changedFile);

            if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir))
            {
                return;
            }

            foreach (string file in Directory.EnumerateFiles(dir, "*" + _ext, SearchOption.AllDirectories))
            {
                if (_ignoreFolders.Any(p => file.Contains("\\" + p + "\\")))
                {
                    continue;
                }

                XmlDocument doc = await GetXmlDocument(file);

                if (doc == null)
                {
                    continue;
                }

                XmlNode bundleNode = doc.SelectSingleNode("//bundle");

                if (bundleNode == null)
                {
                    continue;
                }

                string baseDir = Path.GetDirectoryName(file);

                if ((changedFile != null && doc.SelectNodes("//file").Cast <XmlNode>().Any(x =>
                                                                                           absolutePath == ProjectHelpers.ToAbsoluteFilePath(x.InnerText, dir, baseDir))) ||
                    (isBuild && bundleNode.Attributes["runOnBuild"] != null &&
                     bundleNode.Attributes["runOnBuild"].InnerText == "true"))
                {
                    WriteBundleFile(file, doc).DoNotWait("reading " + file + " file");
                }
            }
        }
Esempio n. 10
0
        private static void WriteFile(string filePath, IEnumerable <ProjectItem> files, string extension, string output)
        {
            string            projectRoot = ProjectHelpers.GetProjectFolder(files.ElementAt(0).FileNames[1]);
            StringBuilder     sb          = new StringBuilder();
            XmlWriterSettings settings    = new XmlWriterSettings();

            settings.Indent = true;

            using (XmlWriter writer = XmlWriter.Create(sb, settings))
            {
                writer.WriteStartElement("bundle");
                writer.WriteAttributeString("minify", "true");
                writer.WriteAttributeString("runOnBuild", "true");
                writer.WriteAttributeString("output", output);
                writer.WriteComment("The order of the <file> elements determines the order of them when bundled.");

                foreach (ProjectItem item in files)
                {
                    string relative = item.IsLink() ? item.FileNames[1] : "/" + FileHelpers.RelativePath(projectRoot, item.FileNames[1]);
                    writer.WriteElementString("file", relative);
                }

                writer.WriteEndElement();
            }

            sb.Replace(Encoding.Unicode.WebName, Encoding.UTF8.WebName);

            ProjectHelpers.CheckOutFileFromSourceControl(filePath);
            File.WriteAllText(filePath, sb.ToString());
            ProjectHelpers.AddFileToActiveProject(filePath, "None");

            _dte.ItemOperations.OpenFile(filePath);

            XmlDocument doc = GetXmlDocument(filePath);

            if (doc != null)
            {
                Dispatcher.CurrentDispatcher.BeginInvoke(
                    new Action(() => WriteBundleFile(filePath, doc)), DispatcherPriority.ApplicationIdle, null);
            }
        }
Esempio n. 11
0
        public static async Task <BundleDocument> 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);
            }

            // Migrate old bundles
            doc = await MigrateBundle(doc, fileName, root, folder);

            if (doc == null)
            {
                return(null);
            }

            XElement             element          = null;
            IEnumerable <string> rawConstituents  = doc.Descendants("file").Select(s => s.Value);
            IEnumerable <string> constituentFiles = ProjectHelpers.GetBundleConstituentFiles(rawConstituents, root, folder, fileName);

            if (constituentFiles.Count() > 0)
            {
                BundleDocument bundle = new BundleDocument(fileName, constituentFiles.ToArray())
                {
                    OriginalBundleAssets = new List <string>(rawConstituents)
                };

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

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

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

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

                if (bundle.isCss)
                {
                    element = doc.Descendants("adjustRelativePaths").FirstOrDefault();

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

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

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

                return(bundle);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 12
0
        private static void WriteBundleFile(string filePath, XmlDocument doc)
        {
            XmlNode bundleNode = doc.SelectSingleNode("//bundle");

            if (bundleNode == null)
            {
                return;
            }

            XmlNode outputAttr = bundleNode.Attributes["output"];

            if (outputAttr != null && (outputAttr.InnerText.Contains("/") || outputAttr.InnerText.Contains("\\")))
            {
                MessageBox.Show("The 'output' attribute should contain a file name without a path", "Web Essentials");
                return;
            }

            Dictionary <string, string> files = new Dictionary <string, string>();
            string      extension             = Path.GetExtension(filePath.Replace(_ext, string.Empty));
            XmlNodeList nodes = doc.SelectNodes("//file");

            foreach (XmlNode node in nodes)
            {
                string absolute;
                if (node.InnerText.Contains(":\\"))
                {
                    absolute = node.InnerText;
                }
                else
                {
                    absolute = ProjectHelpers.ToAbsoluteFilePath(node.InnerText, ProjectHelpers.GetProjectFolder(filePath)).Replace("\\\\", "\\");
                }

                if (File.Exists(absolute))
                {
                    if (!files.ContainsKey(absolute))
                    {
                        files.Add(absolute, node.InnerText);
                    }
                }
                else
                {
                    string error = string.Format("Bundle error: The file '{0}' doesn't exist", node.InnerText);
                    _dte.ItemOperations.OpenFile(filePath);
                    MessageBox.Show(error, "Web Essentials");
                    return;
                }
            }

            string bundlePath = outputAttr != null?Path.Combine(Path.GetDirectoryName(filePath), outputAttr.InnerText) : filePath.Replace(_ext, string.Empty);

            StringBuilder sb = new StringBuilder();

            foreach (string file in files.Keys)
            {
                //if (extension.Equals(".css", StringComparison.OrdinalIgnoreCase))
                //{
                //    sb.AppendLine("/*#source " + files[file] + " */");
                //}
                if (extension.Equals(".js", StringComparison.OrdinalIgnoreCase) && WESettings.GetBoolean(WESettings.Keys.GenerateJavaScriptSourceMaps))
                {
                    sb.AppendLine("///#source 1 1 " + files[file]);
                }

                sb.AppendLine(File.ReadAllText(file));
            }

            if (!File.Exists(bundlePath) || File.ReadAllText(bundlePath) != sb.ToString())
            {
                ProjectHelpers.CheckOutFileFromSourceControl(bundlePath);
                using (StreamWriter writer = new StreamWriter(bundlePath, false, new UTF8Encoding(true)))
                {
                    writer.Write(sb.ToString());
                    Logger.Log("Updating bundle: " + Path.GetFileName(bundlePath));
                }
                MarginBase.AddFileToProject(filePath, bundlePath);

                if (bundleNode.Attributes["minify"] != null || bundleNode.Attributes["minify"].InnerText == "true")
                {
                    WriteMinFile(filePath, bundlePath, sb.ToString(), extension);
                }
            }
        }
Esempio n. 13
0
        public static async Task <BundleDocument> FromFile(string fileName)
        {
            var    extension = Path.GetExtension(fileName).TrimStart('.').ToLowerInvariant();
            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);
            }

            // Migrate old bundles
            doc = await MigrateBundle(doc, fileName, root, folder);

            if (doc == null)
            {
                return(null);
            }

            XElement             element          = null;
            IEnumerable <string> constituentFiles = from f in doc.Descendants("file")
                                                    select ProjectHelpers.ToAbsoluteFilePath(f.Value, root, folder);

            BundleDocument bundle = new BundleDocument(fileName, constituentFiles.ToArray());

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

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

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

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

            if (extension == "css")
            {
                element = doc.Descendants("adjustRelativePaths").FirstOrDefault();

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

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

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

            return(bundle);
        }