//=====================================================================

        /// <summary>
        /// Snippet loading logic
        /// </summary>
        /// <param name="file">The file from which to load the snippets</param>
        private void LoadContent(string file)
        {
            SnippetIdentifier key = new SnippetIdentifier();
            string            language;

            WriteMessage(MessageLevel.Info, "Loading code snippet file '{0}'.", file);

            try
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.CheckCharacters = false;
                XmlReader reader = XmlReader.Create(file, settings);

                try
                {
                    reader.MoveToContent();
                    while (!reader.EOF)
                    {
                        if (reader.NodeType == XmlNodeType.Element && reader.Name == "item")
                        {
                            key = new SnippetIdentifier(reader.GetAttribute("id"));
                            reader.Read();
                        }
                        else if (reader.NodeType == XmlNodeType.Element && reader.Name == "sampleCode")
                        {
                            language = reader.GetAttribute("language");

                            string content = reader.ReadString();

                            // If the element is empty, ReadString does not advance the reader, so we must do it
                            // manually.
                            if (String.IsNullOrEmpty(content))
                            {
                                reader.Read();
                            }

                            if (!content.IsLegalXmlText())
                            {
                                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
                                                                                  "Snippet '{0}' language '{1}' contains illegal characters.", key, language));
                            }

                            content = StripLeadingSpaces(content);

                            StoredSnippet        snippet = new StoredSnippet(content, language);
                            List <StoredSnippet> values;

                            if (!snippets.TryGetValue(key, out values))
                            {
                                values = new List <StoredSnippet>();
                                snippets.Add(key, values);
                            }

                            values.Add(snippet);
                        }
                        else
                        {
                            reader.Read();
                        }
                    }
                }
                catch (XmlException e)
                {
                    WriteMessage(MessageLevel.Warn, "The contents of the snippet file '{0}' are not " +
                                 "well-formed XML. The error message is: {1}. Some snippets may be lost.", file, e.Message);
                }
                finally
                {
                    reader.Close();
                }
            }
            catch (IOException e)
            {
                WriteMessage(MessageLevel.Error, "An access error occurred while attempting to read the " +
                             "snippet file '{0}'. The error message is: {1}", file, e.Message);
            }
        }
        /// <inheritdoc />
        public override void Apply(XmlDocument document, string key)
        {
            foreach (XPathNavigator node in document.CreateNavigator().Select(selector).ToArray())
            {
                string reference = node.Value;

                // check for validity of reference
                if (validSnippetReference.IsMatch(reference))
                {
                    var identifiers = SnippetIdentifier.ParseReference(reference);

                    if (identifiers.Count() == 1)
                    {
                        // one snippet referenced

                        SnippetIdentifier    identifier = identifiers.First();
                        List <StoredSnippet> values;

                        if (snippets.TryGetValue(identifier, out values))
                        {
                            XmlWriter writer = node.InsertAfter();
                            writer.WriteStartElement("snippets");
                            writer.WriteAttributeString("reference", reference);

                            foreach (StoredSnippet value in values)
                            {
                                writer.WriteStartElement("snippet");
                                writer.WriteAttributeString("language", value.Language);

                                if (colorization.ContainsKey(value.Language))
                                {
                                    WriteColorizedSnippet(ColorizeSnippet(value.Text, colorization[value.Language]), writer);
                                }
                                else
                                {
                                    writer.WriteString(value.Text);
                                }

                                writer.WriteEndElement();
                            }

                            writer.WriteEndElement();
                            writer.Close();
                        }
                        else
                        {
                            base.WriteMessage(key, MessageLevel.Warn, "No snippet with identifier '{0}' was found.", identifier);
                        }
                    }
                    else
                    {
                        // multiple snippets referenced

                        // create structure that maps language -> snippets
                        Dictionary <string, List <StoredSnippet> > map = new Dictionary <string, List <StoredSnippet> >();

                        foreach (SnippetIdentifier identifier in identifiers)
                        {
                            List <StoredSnippet> values;

                            if (snippets.TryGetValue(identifier, out values))
                            {
                                foreach (StoredSnippet value in values)
                                {
                                    List <StoredSnippet> pieces;
                                    if (!map.TryGetValue(value.Language, out pieces))
                                    {
                                        pieces = new List <StoredSnippet>();
                                        map.Add(value.Language, pieces);
                                    }
                                    pieces.Add(value);
                                }
                            }
                        }

                        XmlWriter writer = node.InsertAfter();
                        writer.WriteStartElement("snippets");
                        writer.WriteAttributeString("reference", reference);

                        foreach (KeyValuePair <string, List <StoredSnippet> > entry in map)
                        {
                            writer.WriteStartElement("snippet");
                            writer.WriteAttributeString("language", entry.Key);

                            List <StoredSnippet> values = entry.Value;
                            for (int i = 0; i < values.Count; i++)
                            {
                                if (i > 0)
                                {
                                    writer.WriteString("\n\n...\n\n");
                                }

                                writer.WriteString(values[i].Text);
                            }

                            writer.WriteEndElement();
                        }

                        writer.WriteEndElement();
                        writer.Close();
                    }
                }
                else
                {
                    base.WriteMessage(key, MessageLevel.Warn, "The code reference '{0}' is not well-formed", reference);
                }

                node.DeleteSelf();
            }
        }
Example #3
0
        //=====================================================================

        /// <summary>
        /// Snippet loading logic
        /// </summary>
        /// <param name="file">The file from which to load the snippets</param>
        private void LoadContent(string file)
        {
            SnippetIdentifier key = new SnippetIdentifier();
            string language;

            WriteMessage(MessageLevel.Info, "Loading code snippet file '{0}'.", file);

            try
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.CheckCharacters = false;
                XmlReader reader = XmlReader.Create(file, settings);

                try
                {
                    reader.MoveToContent();
                    while(!reader.EOF)
                    {
                        if(reader.NodeType == XmlNodeType.Element && reader.Name == "item")
                        {
                            key = new SnippetIdentifier(reader.GetAttribute("id"));
                            reader.Read();
                        }
                        else if(reader.NodeType == XmlNodeType.Element && reader.Name == "sampleCode")
                        {
                            language = reader.GetAttribute("language");

                            string content = reader.ReadString();

                            // If the element is empty, ReadString does not advance the reader, so we must do it
                            // manually.
                            if(String.IsNullOrEmpty(content))
                                reader.Read();

                            if(!content.IsLegalXmlText())
                                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
                                    "Snippet '{0}' language '{1}' contains illegal characters.", key, language));

                            content = StripLeadingSpaces(content);

                            StoredSnippet snippet = new StoredSnippet(content, language);
                            List<StoredSnippet> values;

                            if(!snippets.TryGetValue(key, out values))
                            {
                                values = new List<StoredSnippet>();
                                snippets.Add(key, values);
                            }

                            values.Add(snippet);
                        }
                        else
                            reader.Read();
                    }
                }
                catch(XmlException e)
                {
                    WriteMessage(MessageLevel.Warn, "The contents of the snippet file '{0}' are not " +
                        "well-formed XML. The error message is: {1}. Some snippets may be lost.", file, e.Message);
                }
                finally
                {
                    reader.Close();
                }

            }
            catch(IOException e)
            {
                WriteMessage(MessageLevel.Error, "An access error occurred while attempting to read the " +
                    "snippet file '{0}'. The error message is: {1}", file, e.Message);
            }
        }
Example #4
0
 public List<Snippet> GetContent(SnippetIdentifier identifier)
 {
     if(exampleSnippets.ContainsKey(identifier))
         return exampleSnippets[identifier];
     else
         return null;
 }
Example #5
0
        public List<Snippet> GetContent(string examplePath, SnippetIdentifier snippetId)
        {

            // get the example containing the identifier
            IndexedExample exampleIndex = GetCachedExample(examplePath);
            if(exampleIndex == null)
                return (null);

            // 
            return exampleIndex.GetContent(snippetId);
        }
Example #6
0
        /// <summary>
        /// Parse the snippet content.
        /// </summary>
        /// <param name="text">content to be parsed</param>
        /// <param name="language">snippet language</param>
        /// <param name="extension">file extension</param>
        /// <param name="example">snippet example</param>
        private void ParseSnippetContent(string text, string language, string extension, string example)
        {
            // parse the text for snippets
            for(Match match = find.Match(text); match.Success; match = find.Match(text, match.Index + 10))
            {
                string snippetIdentifier = match.Groups["id"].Value;
                string snippetContent = match.Groups["tx"].Value;
                snippetContent = clean.Replace(snippetContent, "\n");

                //if necessary, clean one more time to catch snippet comments on consecutive lines
                if(clean.Match(snippetContent).Success)
                {
                    snippetContent = clean.Replace(snippetContent, "\n");
                }

                snippetContent = cleanAtStart.Replace(snippetContent, "");
                snippetContent = cleanAtEnd.Replace(snippetContent, "");

                // get the language/extension from our languages List, which may contain colorization rules for the language
                Language snippetLanguage = new Language(language, extension, null);
                foreach(Language lang in _languages)
                {
                    if(!lang.IsMatch(language, extension))
                        continue;
                    snippetLanguage = lang;
                    break;
                }

                SnippetIdentifier identifier = new SnippetIdentifier(example, snippetIdentifier);

                // BUGBUG: i don't think this ever happens, but if it did we should write an error
                if(!snippetContent.IsLegalXmlText())
                {
                    // WriteMessage(MessageLevel.Warn, "Snippet '{0}' language '{1}' contains illegal characters.", identifier.ToString(), snippetLanguage.LanguageId);
                    continue;
                }

                snippetContent = StripLeadingSpaces(snippetContent);

                // Add the snippet information to dictionary
                Snippet snippet = new Snippet(snippetContent, snippetLanguage);
                List<Snippet> values;

                if(!this.exampleSnippets.TryGetValue(identifier, out values))
                {
                    values = new List<Snippet>();
                    this.exampleSnippets.Add(identifier, values);
                }
                values.Add(snippet);
            }
        }