Пример #1
0
        private async Task <string> GetUpdatedSourceMapFileContent(string cssFileName, string sourceMapFileName)
        {
            string jsonString = await ReadMapFile(sourceMapFileName);

            if (string.IsNullOrEmpty(jsonString))
            {
                return(null);
            }

            // Read JSON map file and deserialize.

            JObject jsonSourceMap = JObject.Parse(jsonString);

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

            for (int i = 0; i < ((JArray)jsonSourceMap["sources"]).Count; i++)
            {
                jsonSourceMap["sources"][i] = FileHelpers.RelativePath(cssFileName, jsonSourceMap["sources"][i].Value <string>());
            }

            jsonSourceMap["file"] = Path.GetFileName(cssFileName);

            return(jsonSourceMap.ToString());
        }
Пример #2
0
        private string UpdateSourceMapUrls(string content, string compiledFileName)
        {
            if (!GenerateSourceMap || !File.Exists(compiledFileName))
            {
                return(content);
            }

            string sourceMapFilename = compiledFileName + ".map";

            if (!File.Exists(sourceMapFilename))
            {
                return(content);
            }

            var updatedFileContent = GetUpdatedSourceMapFileContent(compiledFileName, sourceMapFilename);

            if (updatedFileContent == null)
            {
                return(content);
            }

            File.WriteAllText(sourceMapFilename, updatedFileContent, Encoding.UTF8);

            return(UpdateSourceLinkInCssComment(content, FileHelpers.RelativePath(compiledFileName, sourceMapFilename)));
        }
Пример #3
0
        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);
        }
        public DragDropPointerEffects HandleDataDropped(DragDropInfo dragDropInfo)
        {
            string reference = FileHelpers.RelativePath(EditorExtensionsPackage.DTE.ActiveDocument.FullName, _imageFilename);

            if (reference.Contains("://"))
            {
                int index = reference.IndexOf('/', 12);
                if (index > -1)
                {
                    reference = reference.Substring(index).ToLowerInvariant();
                }
            }
            reference = HttpUtility.UrlPathEncode(reference);

            ITextDocument document;

            if (!_documentFactory.TryGetTextDocument(_view.TextDataModel.DocumentBuffer, out document))
            {
                return(DragDropPointerEffects.None);
            }

            string template = document.TextBuffer.ContentType.IsOfType("Markdown") ? MarkdownTemplate : HtmlTemplate;

            _view.TextBuffer.Insert(dragDropInfo.VirtualBufferPosition.Position.Position, string.Format(CultureInfo.CurrentCulture, template, Path.GetFileName(reference), reference, HttpUtility.HtmlAttributeEncode(reference)));

            return(DragDropPointerEffects.Link);
        }
Пример #5
0
        private void ReplaceUrlValue(string fileName)
        {
            string relative = FileHelpers.RelativePath(EditorExtensionsPackage.DTE.ActiveDocument.FullName, fileName);
            string urlValue = string.Format(CultureInfo.InvariantCulture, "url({0})", relative);

            _span.TextBuffer.Replace(_span.GetSpan(_span.TextBuffer.CurrentSnapshot), urlValue);
        }
Пример #6
0
        public string GetCodeFromFile(string fileName, out string fontFamily)
        {
            var files = GetRelativeFiles(fileName);

            string[] sources = new string[files.Count()];

            for (int i = 0; i < files.Count(); i++)
            {
                string file      = files.ElementAt(i);
                string extension = Path.GetExtension(file).ToLowerInvariant();
                string reference = FileHelpers.RelativePath(EditorExtensionsPackage.DTE.ActiveDocument.FullName, file);

                if (reference.StartsWith("http://localhost:"))
                {
                    int index = reference.IndexOf('/', 24);
                    if (index > -1)
                    {
                        reference = reference.Substring(index + 1).ToLowerInvariant();
                    }
                }

                sources[i] = string.Format(_fontUrls, reference, _formats[extension]);
            }

            string sourceUrls = string.Join(", ", sources);

            fontFamily = _fontName;
            return(string.Format(_fontFace, _fontName, sourceUrls));
        }
Пример #7
0
        private string GetRelativePath(string file, string root)
        {
            file = "/" + FileHelpers.RelativePath(root, file);

            OriginalBundleAssets.Add(file);

            return(file);
        }
Пример #8
0
        public async static Task <Dictionary <string, string> > WatchFiles(BundleDocument document, Func <string, bool, Task> updateBundle, string bundleFile = null)
        {
            if (document == null)
            {
                return(null);
            }

            if (bundleFile == null && document.OutputDirectory != null)
            {
                bundleFile = ProjectHelpers.GetAbsolutePathFromSettings(document.OutputDirectory, Path.Combine(Path.GetDirectoryName(document.FileName), Path.GetFileNameWithoutExtension(document.FileName)));
            }

            Dictionary <string, string> files = new Dictionary <string, string>();

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

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

                if (!File.Exists(absoluteActual))
                {
                    WebEssentialsPackage.DTE.ItemOperations.OpenFile(document.FileName);
                    Logger.ShowMessage(String.Format(CultureInfo.CurrentCulture, "Bundle error: The file '{0}' doesn't exist", asset));

                    return(null);
                }

                if (!File.Exists(absolute))
                {
                    WebEssentialsPackage.DTE.ItemOperations.OpenFile(document.FileName);
                    Logger.ShowMessage(String.Format(CultureInfo.CurrentCulture, "Bundle error: The file '{0}' doesn't exist", absolute));

                    return(null);
                }

                if (!files.ContainsKey(absoluteActual))
                {
                    if (Path.IsPathRooted(asset))
                    {
                        files.Add(absolute, asset);
                    }
                    else
                    {
                        files.Add(absolute, FileHelpers.RelativePath(bundleFile, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(document.FileName), asset))));
                    }

                    await new BundleFileObserver().AttachFileObserver(document, absoluteActual, updateBundle);
                }
            }

            return(files);
        }
Пример #9
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);
        }
Пример #10
0
        public DragDropPointerEffects HandleDataDropped(DragDropInfo dragDropInfo)
        {
            string reference = FileHelpers.RelativePath(EditorExtensionsPackage.DTE.ActiveDocument.FullName, _imageFilename);

            if (reference.Contains("://"))
            {
                int index = reference.IndexOf('/', 12);
                if (index > -1)
                {
                    reference = reference.Substring(index).ToLowerInvariant();
                }
            }

            _view.TextBuffer.Insert(dragDropInfo.VirtualBufferPosition.Position.Position, string.Format(_background, reference));

            return(DragDropPointerEffects.Copy);
        }
Пример #11
0
        public DragDropPointerEffects HandleDataDropped(DragDropInfo dragDropInfo)
        {
            string reference = FileHelpers.RelativePath(ProjectHelpers.GetRootFolder(), _draggedFilename);

            if (reference.StartsWith("http://localhost:", StringComparison.OrdinalIgnoreCase))
            {
                int index = reference.IndexOf('/', 20);
                if (index > -1)
                {
                    reference = reference.Substring(index + 1).ToLowerInvariant();
                }
            }

            _view.TextBuffer.Insert(dragDropInfo.VirtualBufferPosition.Position.Position, string.Format(_format, reference));

            return(DragDropPointerEffects.Copy);
        }
Пример #12
0
        public DragDropPointerEffects HandleDataDropped(DragDropInfo dragDropInfo)
        {
            string reference = FileHelpers.RelativePath(EditorExtensionsPackage.DTE.ActiveDocument.FullName, _imageFilename);

            if (reference.StartsWith("http://localhost:"))
            {
                int index = reference.IndexOf('/', 24);
                if (index > -1)
                {
                    reference = reference.Substring(index).ToLowerInvariant();
                }
            }
            reference = HttpUtility.UrlPathEncode(reference);

            _view.TextBuffer.Insert(dragDropInfo.VirtualBufferPosition.Position.Position, string.Format(_import, reference));

            return(DragDropPointerEffects.Copy);
        }
Пример #13
0
        public DragDropPointerEffects HandleDataDropped(DragDropInfo dragDropInfo)
        {
            string reference = FileHelpers.RelativePath(EditorExtensionsPackage.DTE.ActiveDocument.FullName, _imageFilename);

            if (reference.StartsWith("http://localhost:"))
            {
                int index = reference.IndexOf('/', 24);
                if (index > -1)
                {
                    reference = reference.Substring(index).ToLowerInvariant();
                }
            }

            reference = reference.Trim('/');
            string comment = string.Format(_background, reference);

            _view.TextBuffer.Insert(0, comment + Environment.NewLine);

            return(DragDropPointerEffects.Copy);
        }
Пример #14
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);
            }
        }
Пример #15
0
        private async Task <string> UpdateSourceMapUrls(string content, string compiledFileName, string mapFileName)
        {
            if (!File.Exists(compiledFileName) || !File.Exists(mapFileName))
            {
                return(content);
            }

            var updatedFileContent = await GetUpdatedSourceMapFileContent(compiledFileName, mapFileName);

            if (updatedFileContent == null)
            {
                return(content);
            }

            await FileHelpers.WriteAllTextRetry(mapFileName, updatedFileContent);

            if (!GenerateSourceMap)
            {
                return(_sourceMapInCss.Replace(content, string.Empty));
            }

            return(UpdateSourceLinkInCssComment(content, FileHelpers.RelativePath(compiledFileName, mapFileName)));
        }
Пример #16
0
        public void Save()
        {
            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Indent = true
            };

            using (XmlWriter writer = XmlWriter.Create(FileName, settings))
            {
                writer.WriteStartElement("sprite");
                writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
                writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation", null, "http://vswebessentials.com/schemas/v1/sprite.xsd");

                // Settings
                writer.WriteStartElement("settings");
                writer.WriteComment("Determines if the sprite image should be automatically optimized after creation/update");
                writer.WriteElementString("optimize", Optimize ? "true" : "false");
                writer.WriteElementString("orientation", IsVertical ? "vertical" : "horizontal");
                writer.WriteElementString("outputType", FileExtension.ToString().ToLowerInvariant());
                writer.WriteEndElement(); // </settings>

                // Files
                writer.WriteComment("The order of the <file> elements determines the order of the images in the sprite.");
                writer.WriteStartElement("files");

                string root = ProjectHelpers.GetRootFolder();

                foreach (string file in ImageFiles)
                {
                    string relative = "/" + FileHelpers.RelativePath(root, file);
                    writer.WriteElementString("file", relative);
                }

                writer.WriteEndElement(); // </files>
                writer.WriteEndElement(); // </sprite>
            }
        }
        private void UpdateTextBuffer(string fileName)
        {
            int    position = TextView.Caret.Position.BufferPosition.Position;
            string relative = FileHelpers.RelativePath(ProjectHelpers.GetRootFolder() ?? "/", fileName);
            string text     = string.Format(CultureInfo.InvariantCulture, _format, relative);

            using (EditorExtensionsPackage.UndoContext("Insert Image"))
            {
                TextView.TextBuffer.Insert(position, text);

                try
                {
                    SnapshotSpan span = new SnapshotSpan(TextView.TextBuffer.CurrentSnapshot, position, _format.Length);
                    TextView.Selection.Select(span, false);

                    EditorExtensionsPackage.ExecuteCommand("Edit.FormatSelection");
                    TextView.Selection.Clear();
                }
                catch
                {
                    // Try to format the selection. Some editors handle this differently, so try/catch
                }
            }
        }
Пример #18
0
        internal static void WriteTypeScript(IEnumerable <IntellisenseObject> objects, StringBuilder sb, string file = null)
        {
            bool          extraLineFeed = false;
            StringBuilder references    = new StringBuilder();

            foreach (var ns in objects.GroupBy(o => o.Namespace))
            {
                sb.AppendFormat("declare module {0} {{\r\n", ns.Key);

                foreach (IntellisenseObject io in ns)
                {
                    if (!string.IsNullOrEmpty(io.Summary))
                    {
                        sb.AppendLine("\t/** " + whitespaceTrimmer.Replace(io.Summary, "") + " */");
                    }
                    if (io.IsEnum)
                    {
                        sb.AppendLine("\tenum " + CamelCaseClassName(io.Name) + " {");
                        foreach (var p in io.Properties)
                        {
                            WriteTypeScriptComment(p, sb);
                            if (p.InitExpression != null)
                            {
                                sb.AppendLine("\t\t" + CamelCasePropertyName(p.Name) + " = " + CleanEnumInitValue(p.InitExpression) + ",");
                            }
                            else
                            {
                                sb.AppendLine("\t\t" + CamelCasePropertyName(p.Name) + ",");
                            }
                        }
                        sb.AppendLine("\t}");
                    }
                    else
                    {
                        sb.Append("\tinterface ").Append(CamelCaseClassName(io.Name)).Append(" ");
                        WriteTSInterfaceDefinition(sb, "\t", io.Properties);
                        sb.AppendLine();

                        if (file != null)
                        {
                            foreach (var reference in io.References.SkipWhile(r => r == file))
                            {
                                references.Insert(0, string.Format(CultureInfo.InvariantCulture, "/// <reference path=\"{0}\" />\r\n", FileHelpers.RelativePath(file, reference)));
                            }

                            if (references.Length > 0)
                            {
                                if (!extraLineFeed)
                                {
                                    references.AppendLine();
                                    extraLineFeed = true;
                                }

                                sb.Insert(0, references);
                                references.Clear();
                            }
                        }
                    }
                }

                sb.AppendLine("}");
            }
        }
Пример #19
0
        public async Task <XDocument> WriteBundleRecipe()
        {
            string            root     = ProjectHelpers.GetRootFolder();
            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Indent = true
            };
            XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

            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("Determin 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", "/" + FileHelpers.RelativePath(root, file))))
                                 )
                    );

                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);
            }
        }
Пример #20
0
        internal static void WriteTypeScript(IEnumerable <IntellisenseObject> objects, StringBuilder sb, string file = null)
        {
            if (WESettings.Instance.CodeGen.AddTypeScriptReferencePath && !string.IsNullOrEmpty(file))
            {
                var references = objects.SelectMany(io => io.References.Where(r => r != file)).Distinct().ToList();

                foreach (var reference in references)
                {
                    sb.AppendFormat("/// <reference path=\"{0}\" />\r\n", FileHelpers.RelativePath(file, reference));
                }

                if (references.Count > 0)
                {
                    sb.AppendLine();
                }
            }

            foreach (var ns in objects.GroupBy(o => o.Namespace))
            {
                sb.AppendFormat("declare module {0} {{\r\n", ns.Key);

                foreach (IntellisenseObject io in ns)
                {
                    if (!string.IsNullOrEmpty(io.Summary))
                    {
                        sb.AppendLine("\t/** " + whitespaceTrimmer.Replace(io.Summary, "") + " */");
                    }

                    if (io.IsEnum)
                    {
                        sb.AppendLine("\tconst enum " + CamelCaseClassName(io.Name) + " {");

                        foreach (var p in io.Properties)
                        {
                            WriteTypeScriptComment(p, sb);

                            if (p.InitExpression != null)
                            {
                                sb.AppendLine("\t\t" + CamelCaseEnumValue(p.Name) + " = " + CleanEnumInitValue(p.InitExpression) + ",");
                            }
                            else
                            {
                                sb.AppendLine("\t\t" + CamelCaseEnumValue(p.Name) + ",");
                            }
                        }

                        sb.AppendLine("\t}");
                    }
                    else
                    {
                        sb.Append("\tinterface ").Append(CamelCaseClassName(io.Name)).Append(" ");

                        if (!string.IsNullOrEmpty(io.BaseName))
                        {
                            sb.Append("extends ");

                            if (!string.IsNullOrEmpty(io.BaseNamespace) && io.BaseNamespace != io.Namespace)
                            {
                                sb.Append(io.BaseNamespace).Append(".");
                            }

                            sb.Append(io.BaseName).Append(" ");
                        }

                        WriteTSInterfaceDefinition(sb, "\t", io.Properties);
                        sb.AppendLine();
                    }
                }

                sb.AppendLine("}");
            }
        }
Пример #21
0
        private async Task <string> GetUpdatedSourceMapFileContent(string cssFileName, string sourceMapFileName)
        {
            // Read JSON map file and deserialize.
            dynamic jsonSourceMap = Json.Decode(await ReadMapFile(sourceMapFileName));

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

            jsonSourceMap.sources = ((IEnumerable <dynamic>)jsonSourceMap.sources).Select(s => FileHelpers.RelativePath(cssFileName, s));
            jsonSourceMap.names   = new List <dynamic>(jsonSourceMap.names);
            jsonSourceMap.file    = Path.GetFileName(cssFileName);

            return(Json.Encode(jsonSourceMap));
        }