public void ReadToMatch() { string input; HtmlTextReader reader; StringReader sr; // Found input = "abcabc--> "; sr = new StringReader(input); reader = new HtmlTextReader(sr); Assert.AreEqual("abcabc", reader.ReadTo("-->")); Assert.AreEqual(' ', sr.Read()); // Not found input = "abcabc-- "; sr = new StringReader(input); reader = new HtmlTextReader(sr); Assert.AreEqual("abcabc-- ", reader.ReadTo("-->")); Assert.AreEqual(-1, sr.Read()); // Found with multiple matches input = "abcabc---->"; sr = new StringReader(input); reader = new HtmlTextReader(sr); Assert.AreEqual("abcabc--", reader.ReadTo("-->")); Assert.AreEqual(-1, sr.Read()); }
public async Task TestGetTextReaderAsync_ForEncoding(string url, string expectedTitle, ClientOptions options = null) { ClientOptions optionsToUse = options == null ? HtmlClient.Options : options; XmlDocument doc1 = new XmlDocument(); System.Text.Encoding initialEncoding = null; EncodingConfidence initialConfidence = EncodingConfidence.Tentative; System.Text.Encoding finalEncoding = null; EncodingConfidence finalConfidence = EncodingConfidence.Tentative; // Get the Html asynchronously and Parse it into an Xml Document using (HtmlTextReader textReader = await HtmlClient.GetHtmlTextReaderAsync(url, optionsToUse)) { initialEncoding = textReader.CurrentEncoding; initialConfidence = textReader.CurrentEncodingConfidence; HtmlParser.DefaultParser.Parse(doc1, textReader, new ParserOptions { BaseUrl = url }); finalEncoding = textReader.CurrentEncoding; finalConfidence = textReader.CurrentEncodingConfidence; } string title1 = doc1.SelectSingleNode("//title/text()").InnerText; Console.WriteLine("Crawled: " + url + ", title: " + title1 + ", default: " + optionsToUse.DefaultEncoding.WebName + " (detect=" + optionsToUse.DetectEncoding + "), inital: " + initialEncoding.WebName + " (" + initialConfidence + "), final: " + finalEncoding.WebName + " (" + finalConfidence + ")"); // Compare the titles of the pages to see if the encoding is picking up consistently between Assert.AreEqual(expectedTitle, title1); }
internal static KeyValuePair <string, ParseState>[] ReadAll(HtmlTextReader reader) { List <KeyValuePair <string, ParseState> > toks = new List <KeyValuePair <string, ParseState> >(); while (reader.ParseState != ParseState.Done) { toks.Add(new KeyValuePair <string, ParseState>(reader.ReadNext(), reader.ParseState)); } return(toks.ToArray()); }
public async Task <XmlDocument> LoadXHtmlDocAsync(string url) { XmlDocument xhtmlDoc = new XmlDocument(); // Get the Html asynchronously and Parse it into an Xml Document using (HtmlTextReader htmlReader = await HtmlClient.GetHtmlTextReaderAsync(url)) this.Parser.Parse(xhtmlDoc, htmlReader, new ParserOptions { BaseUrl = url }); return(xhtmlDoc); }
/// <summary> /// Returns a TextReader that detects the underlying stream's endoding. Allows clients to stream the /// retured content using a TextReader. This method is similar in purpose to GetStreamAsync, however, GetStreamAsync /// doesn't detect the Stream's encoding as GetStringAsync does. /// </summary> /// <param name="httpClient"></param> public static async Task <HtmlTextReader> GetHtmlTextReaderAsync(string url, ClientOptions options) { HtmlTextReader reader; ClientOptions optionsToUse = options == null ? HtmlClient.Options : options; Uri uri = new Uri(url); // See if the url pointed to a file. If so, return a reader with a file stream // under the hood. if (uri.IsFile) { FileStream fs = File.OpenRead(uri.AbsolutePath); HtmlStream stream = new HtmlStream(fs); reader = new HtmlTextReader(stream, options.DefaultEncoding, EncodingConfidence.Tentative); reader.OriginatingUrl = url; return(reader); } // Set a user agent if one was specified if (!string.IsNullOrEmpty(optionsToUse.UserAgent)) { HttpClient.DefaultRequestHeaders.Remove("User-Agent"); HttpClient.DefaultRequestHeaders.Add("User-Agent", optionsToUse.UserAgent); } // Get the Http response (only read the headers at this point) and ensure succes HttpResponseMessage responseMessage = await HttpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); responseMessage.EnsureSuccessStatusCode(); // If there is no content to return, return an empty HtmlTextReader HttpContent content = responseMessage.Content; if (content == null) { reader = new HtmlTextReader(String.Empty); } else { reader = await content.GetHtmlTextReaderAsync(optionsToUse.DefaultEncoding, optionsToUse.DetectEncoding); } // Store some metadata on the reader. Could be used by a parser. reader.OriginatingUrl = url; foreach (var header in content.Headers) { reader.OriginatingHttpHeaders.Add(new KeyValuePair <string, string>(header.Key, string.Join(";", header.Value))); } return(reader); }
/// <summary> /// Returns true if the reader is positioned on a node that has a bgColor="#ff99cb" attribute. /// </summary> private static bool IsBgColorFF99CB(HtmlTextReader reader) { if (reader.HasAttributes) { for (int i = 0; i < reader.AttributeCount; i++) { if (String.Compare("bgColor", reader.GetAttributeName(i), StringComparison.OrdinalIgnoreCase) == 0 && String.Compare("#ff99cb", reader.GetAttributeValue(i).ToString(), StringComparison.OrdinalIgnoreCase) == 0) { return(true); } } } return(false); }
public void ReadAttrName() { string input; StringReader sr; HtmlTextReader reader; string output; // no whitespace input = "class='red' "; sr = new StringReader(input); reader = new HtmlTextReader(sr); output = reader.ReadAttributeName(); Assert.AreEqual("class", output); Assert.AreEqual('=', (char)reader.Peek()); Assert.AreEqual(ParseState.AttributeValue, reader.ParseState); // whitespace input = " class='red' "; sr = new StringReader(input); reader = new HtmlTextReader(sr); output = reader.ReadAttributeName(); Assert.AreEqual("class", output); Assert.AreEqual('=', (char)reader.Peek()); // whitespace input = " class = 'red' "; sr = new StringReader(input); reader = new HtmlTextReader(sr); output = reader.ReadAttributeName(); Assert.AreEqual("class", output); Assert.AreEqual(' ', (char)reader.Peek()); // whitespace input = " class = \"red\" "; sr = new StringReader(input); reader = new HtmlTextReader(sr); output = reader.ReadAttributeName(); Assert.AreEqual("class", output); Assert.AreEqual(' ', (char)reader.Peek()); // missing attr. the rest is val input = " =red foo=bar "; sr = new StringReader(input); reader = new HtmlTextReader(sr); output = reader.ReadAttributeName(); Assert.AreEqual("=red", output); Assert.AreEqual(' ', (char)reader.Peek()); }
public void ReadText() { string input; HtmlTextReader reader; string output; // Text to a comment input = "Hello Text<!-- a comment"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadText(); Assert.AreEqual("Hello Text", output); Assert.AreEqual(ParseState.Comment, reader.ParseState); // Text to a comment with whitespace input = " Hello Text<!-- a comment"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadText(); Assert.AreEqual(" Hello Text", output); Assert.AreEqual(ParseState.Comment, reader.ParseState); // Text to an open tag input = "Hello Text<A>"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadText(); Assert.AreEqual("Hello Text", output); Assert.AreEqual(ParseState.OpenTag, reader.ParseState); // Text to an open tag (bad character for tag, so treated as text) input = "Hello Text<1>"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadText(); Assert.AreEqual("Hello Text<1>", output); Assert.AreEqual(ParseState.Done, reader.ParseState); // Text to a close tag input = "Hello Text</A>"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadText(); Assert.AreEqual("Hello Text", output); Assert.AreEqual(ParseState.CloseTag, reader.ParseState); // Text to a close tag (bad char) input = "Hello Text</_>"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadText(); Assert.AreEqual("Hello Text", output); Assert.AreEqual(ParseState.Comment, reader.ParseState); }
private static string ReadAllAttributes(string input) { StringBuilder output = new StringBuilder(); StringReader sr = new StringReader(input); HtmlTextReader reader = new HtmlTextReader(sr); while (sr.Peek() >= 0) { string name = reader.ReadAttributeName(); string value = reader.ReadAttributeValue(); if (!string.IsNullOrEmpty(name)) { output.Append(output.Length > 0 ? " " : ""); output.Append(name + "='" + value + "'"); } } return(output.ToString()); }
public void ReadNext() { string input; HtmlTextReader reader; StringReader sr; // Basic open close tag with text input = " <a href='www.foobar.com'>Click me</a> "; sr = new StringReader(input); reader = new HtmlTextReader(sr); // Starts in text Assert.AreEqual(ParseState.Text, reader.ParseState); // There was no text, so should be empty Assert.AreEqual(" ", reader.ReadNext()); // Open tag Assert.AreEqual(ParseState.OpenTag, reader.ParseState); Assert.AreEqual("a", reader.ReadNext()); // href Assert.AreEqual(ParseState.AttributeName, reader.ParseState); Assert.AreEqual("href", reader.ReadNext()); // www.foobar.com Assert.AreEqual(ParseState.AttributeValue, reader.ParseState); Assert.AreEqual("www.foobar.com", reader.ReadNext()); // Need to keep reading attributes until we get an empty one Assert.AreEqual(ParseState.AttributeName, reader.ParseState); Assert.AreEqual(String.Empty, reader.ReadNext()); // Click me Assert.AreEqual(ParseState.Text, reader.ParseState); Assert.AreEqual("Click me", reader.ReadNext()); // Close tag Assert.AreEqual(ParseState.CloseTag, reader.ParseState); Assert.AreEqual("a", reader.ReadNext()); Assert.AreEqual(ParseState.Text, reader.ParseState); }
public async Task <int> DownloadPageUsingGetAsTextReaderAsync(string url) { using (HtmlTextReader reader = await HtmlClient.GetHtmlTextReaderAsync(url)) { int c = 0; int charsRead = 0; while (true) { c = reader.BaseReader.Read(); if (c < 0) { break; } charsRead++; } return(charsRead); } }
public void ReadScript() { string input; HtmlTextReader reader; StringReader sr; // Basic open close tag with text input = "<Script type='javascript'> console.log('<a>some tag</a>') </script>"; sr = new StringReader(input); reader = new HtmlTextReader(sr); Assert.AreEqual(ParseState.Text, reader.ParseState); Assert.AreEqual("", reader.ReadNext()); Assert.AreEqual(ParseState.OpenTag, reader.ParseState); Assert.AreEqual("script", reader.ReadNext()); Assert.AreEqual(ParseState.AttributeName, reader.ParseState); Assert.AreEqual("type", reader.ReadNext()); Assert.AreEqual(ParseState.AttributeValue, reader.ParseState); Assert.AreEqual("javascript", reader.ReadNext()); Assert.AreEqual(ParseState.AttributeName, reader.ParseState); Assert.AreEqual("", reader.ReadNext()); Assert.AreEqual(ParseState.Text, reader.ParseState); Assert.AreEqual(" console.log('<a>some tag</a>') ", reader.ReadRCData("script")); Assert.AreEqual(ParseState.Text, reader.ParseState); Assert.AreEqual("", reader.ReadNext()); Assert.AreEqual(ParseState.Done, reader.ParseState); }
/// <summary> /// Returns true if the reader is positioned on an assessment item IMG tag and sets srcIndex to the index of the /// src attribute. /// </summary> private static bool IsAITag(HtmlTextReader reader, out int srcIndex) { if (reader.NodeType == HtmlNodeType.Element && String.Compare(reader.Name, "img", StringComparison.OrdinalIgnoreCase) == 0) { if (reader.HasAttributes) { for (int i = 0; i < reader.AttributeCount; i++) { if (String.Compare("src", reader.GetAttributeName(i), StringComparison.OrdinalIgnoreCase) == 0 && reader.GetAttributeValue(i).ToString().Contains("mslamrk")) { srcIndex = i; return(true); } } } } srcIndex = -1; return(false); }
public static async Task <HtmlTextReader> GetHtmlTextReaderAsync(this HttpContent content, Encoding defaultEncoding, bool detectEncoding) { // Try to get the stream's encoding from the Response Headers, or fall back on default. // We will also try to detect the encoding from the Byte Order Mark if there is no encoding supplied // by the headers. If both of these fail, the Parser should look for an encoding in the <meta> tags of // the html itself. Encoding encoding = defaultEncoding; // Try to detect the encoding from Http Headers bool gotEncodingFromHttpHeaders = false; if (detectEncoding) { var contentHeaders = content.Headers; string charset = (contentHeaders.ContentType != null) ? contentHeaders.ContentType.CharSet : null; encoding = EncodingUtils.GetEncoding(charset); gotEncodingFromHttpHeaders = encoding != null; encoding = (encoding == null ? defaultEncoding : encoding); System.Diagnostics.Debug.WriteLine("Detected encoding: charset: " + charset + ", got encoding from headers: " + gotEncodingFromHttpHeaders); } // Out of band encoding can be either passed in by clients, or found in the http headers... bool gotEncodingFromOutOfBandSource = !detectEncoding || gotEncodingFromHttpHeaders; EncodingConfidence encodingConfidence = gotEncodingFromOutOfBandSource ? EncodingConfidence.Certain : EncodingConfidence.Tentative; // If encoding was NOT supplied out of band, then we will try to detect it from the stream's BOM bool tryToDetectEncodingFromByteOrderMark = (encodingConfidence == EncodingConfidence.Tentative); // Get the stream from the network Stream networkStream = await content.ReadAsStreamAsync().ConfigureAwait(false); // If we are still tentative about the encoding, pop the stream into a wrapper that let's us re-wind. Stream baseStream = (encodingConfidence == EncodingConfidence.Tentative) ? new HtmlStream(networkStream) : networkStream; // Return a HtmlTextReader with the encoding as detected so far... HtmlTextReader htmlReader = new HtmlTextReader(baseStream, encoding, encodingConfidence); return(htmlReader); }
/// <summary> /// Render the requested view into the output stream. /// </summary> /// <param name="context">The context within which to render the page.</param> /// <remarks> /// When this method returns the <paramref name="context"/> OutputStream will contain /// the rendered file. /// <p> /// The following methods and properties must be return valid values from /// the <paramref name="context"/>: /// <ul> /// <li>EmbeddedUiResourcePath, must be non-null</li> /// <li>FormElementId</li> /// <li>GetInputStream</li> /// <li>OutputStream</li> /// <li>View</li> /// </ul> /// </p> /// <p> /// Additionally, if the following properties are set, they will be used: /// <ul> /// <li>FormElementAction</li> /// <li>HiddenControls</li> /// <li>ScriptToRender</li> /// </ul> /// </p> /// All other properties on <paramref name="context"/> are ignored. /// </remarks> /// <exception cref="FileNotFoundException">The requested file attachment can't be found.</exception> public override void Render(RloRenderContext context) { AIResources.Culture = LocalizationManager.GetCurrentCulture(); // string is the key (which is AssessmentItem.Id_AssessmentItem.Type) // int is the ordinal (0 based) which is the number of times the key has been processed Dictionary <string, int> assessmentItems = new Dictionary <string, int>(); // The most common case is that the file is in the package Stream inputStream = null; AssessmentItemManager.DataModelContext = context; LearningDataModel learningDataModel = context.LearningDataModel; try { int srcIndex; // represents the index of the "src" attribute on an <img> node. // If this is the first time the page is being rendered, parse the page and determine // the interactions on the page. if (context.View == SessionView.Execute) { if (!GetPageHasBeenVisited(learningDataModel)) { using (inputStream = context.GetInputStream()) { // If the file being requested is the default file for the current activity, if (context.IsResourceEntryPoint) { // find all the assessment items (<IMG> tags that contain the text "mslamrk" as part of the src attribute.) using (HtmlTextReader reader = new HtmlTextReader(inputStream)) { while (reader.Read()) { if (IsAITag(reader, out srcIndex)) { try { AssessmentItem ai = AssessmentItem.Parse(reader.GetAttributeValue(srcIndex)); AssessmentItemRenderer renderer = AssessmentItemManager.GetRenderer(ai); renderer.TryAddToDataModel(); } catch (FormatException) { // skip this one. This is mirrored below in the 2nd pass. } } } } } } SetPageHasBeenVisited(learningDataModel); } } // must get the input stream again since it may not be possible to seek back to the beginning using (inputStream = context.GetInputStream()) { if (context.Response != null) { // Clear the output response context.Response.Clear(); } // If the file being requested is the default file for the current activity, if (context.IsResourceEntryPoint) { if (context.View == SessionView.Execute) { // Set ExitMode to suspend so that when a student exits the activity it is left in a suspended state. // This way if the activity is reactivated, the student's previous answers are intact. learningDataModel.NavigationRequest.ExitMode = ExitMode.Suspended; } DetachableStream detachable = new DetachableStream(context.OutputStream); // Parse through the input stream again, this time rendering into the output as we go. using (StreamWriter writer = new StreamWriter(detachable)) { using (HtmlTextReader reader = new HtmlTextReader(inputStream)) { while (reader.Read()) { if (IsAITag(reader, out srcIndex)) { try { AssessmentItem ai = AssessmentItem.Parse(reader.GetAttributeValue(srcIndex)); AssessmentItemRenderer renderer = AssessmentItemManager.GetRenderer(ai); if (assessmentItems.ContainsKey(ai.RenderKey)) { assessmentItems[ai.RenderKey] += 1; } else { assessmentItems.Add(ai.RenderKey, 0); } writer.Write(renderer.Render(assessmentItems[ai.RenderKey]).ToString()); } catch (FormatException) { // skip this one. This is mirrored above in the 1st pass. } } else { HandleNode(reader, writer); } } } // don't allow closing the StreamWriter to close the context.OutputStream. writer.Flush(); detachable.Detach(); } // set the response type context.SetOutputStreamExtension(Path.GetExtension(context.RelativePath)); } else { // for a non-entry-point file, copy the file directly to the output stream context.WriteFileToResponse(context.RelativePath); } } return; } catch (FileNotFoundException) { // This means the requested file is not in the package. That's not necessarily a problem, since it // may be a request for an attachment. } // We got here because the file is not in the package. In that case, render it if it is a file attachment int beginAttachmentInfo = context.RelativePath.IndexOf("/~RLO/", StringComparison.Ordinal); if (beginAttachmentInfo != -1) { // attachmentInfo should be of the form <interactionId>/<attachmentIndex>, so split it into the parts string attachmentInfo = context.RelativePath.Substring(beginAttachmentInfo + 6); RenderFileAttachment(context, attachmentInfo); } else { // This means the requested file is not in the package, nor is it a request for an attachment. throw new FileNotFoundException(AIResources.FileNotFound); } }
/// <summary> /// Returns "true" if the reader's node is named the supplied name, case-insensitive. /// </summary> private static bool IsNamed(HtmlTextReader reader, string name) { return(0 == String.Compare(reader.Name, name, StringComparison.OrdinalIgnoreCase)); }
public void ReadComment() { string input; HtmlTextReader reader; string output; // Full comment input = "--Hello comment--> asdfaf"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadComment(); Assert.AreEqual("Hello comment", output); // Full comment input = "--Hello \n\tcomment--> asdfaf"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadComment(); Assert.AreEqual("Hello \n\tcomment", output); // Full comment input = "--Hello -> comment--> asdfaf"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadComment(); Assert.AreEqual("Hello -> comment", output); // Full comment input = "--Hello - comment--> asdfaf"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadComment(); Assert.AreEqual("Hello - comment", output); // Full comment input = "--Hello -- comment--> asdfaf"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadComment(); Assert.AreEqual("Hello -- comment", output); // Basic input = "Hello comment"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadComment(); Assert.AreEqual("Hello comment", output); // Basic input = "Hello comment>"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadComment(); Assert.AreEqual("Hello comment", output); // Basic input = "Hello comment> "; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadComment(); Assert.AreEqual("Hello comment", output); // Basic input = "Hello comment--"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadComment(); Assert.AreEqual("Hello comment--", output); // Basic input = "Hello comment-"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadComment(); Assert.AreEqual("Hello comment-", output); // Basic input = "-Hello comment->"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadComment(); Assert.AreEqual("-Hello comment-", output); }
/// <summary> /// Requests the RloHandler to do whatever is required to exit from the current activity. /// This request may only be issued when the session is in Execute view and is not active -- it is /// either Completed or Abandoned. /// </summary> /// <param name="context">The context within which the command is processed</param> /// <remarks> /// This method should only be called for the <c>SessionView.Execute</c> view. However, /// no checks are done internally to verify this - if this is called with other views, /// unexpected results will occur. /// </remarks> public override void ProcessSessionEnd(RloDataModelContext context) { LearningDataModel learningDataModel = context.LearningDataModel; // Set ExitMode to suspend so that when a student exits the activity it is left in a suspended state. // This way if the activity is reactivated, the student's previous answers are intact. learningDataModel.NavigationRequest.ExitMode = ExitMode.Suspended; // If the page has never been visited, "visit" it. if (!GetPageHasBeenVisited(learningDataModel)) { AssessmentItemManager.DataModelContext = context; // Get the input stream containing the primary file from the resource associated with the // current activity in the session. using (Stream inputStream = context.GetInputStream()) { // find all the assessment items (<IMG> tags that contain the text "mslamrk" as part of the src attribute.) using (HtmlTextReader reader = new HtmlTextReader(inputStream)) { int srcIndex; while (reader.Read()) { if (IsAITag(reader, out srcIndex)) { try { AssessmentItem ai = AssessmentItem.Parse(reader.GetAttributeValue(srcIndex)); AssessmentItemRenderer renderer = AssessmentItemManager.GetRenderer(ai); renderer.TryAddToDataModel(); } catch (FormatException) { // skip this one. } } } } } SetPageHasBeenVisited(learningDataModel); } // If the page has never been autograded, call ProcessSessionEnd on the form data processors if (!GetPageHasBeenAutograded(learningDataModel)) { AssessmentItemManager.ProcessFormContext = new RloProcessFormDataContext(SessionView.Execute, learningDataModel); float?totalPoints = null; foreach (Interaction interaction in learningDataModel.Interactions) { FormDataProcessor processor = m_assessmentItemMgr.GetFormDataProcessor(interaction); // must check that processor is non null, since GetFormDataProcessor() can return null. // If it is null, any item score associated with this interaction is not totalled into // EvaluationPoints. if (processor != null) { processor.ProcessSessionEnd(context); if (interaction.Evaluation.Points.HasValue) { if (totalPoints.HasValue) { totalPoints += interaction.Evaluation.Points; } else { totalPoints = interaction.Evaluation.Points; } } } } learningDataModel.EvaluationPoints = totalPoints; SetPageHasBeenAutograded(learningDataModel); } }
public void ReadAttrNameAndVal() { string input; StringReader sr; HtmlTextReader reader; input = "class='red' "; sr = new StringReader(input); reader = new HtmlTextReader(sr); Assert.AreEqual("class", reader.ReadAttributeName()); Assert.AreEqual("red", reader.ReadAttributeValue()); input = "class = \"red\" "; sr = new StringReader(input); reader = new HtmlTextReader(sr); Assert.AreEqual("class", reader.ReadAttributeName()); Assert.AreEqual("red", reader.ReadAttributeValue()); input = " class =red "; sr = new StringReader(input); reader = new HtmlTextReader(sr); Assert.AreEqual("class", reader.ReadAttributeName()); Assert.AreEqual("red", reader.ReadAttributeValue()); input = " class = red "; sr = new StringReader(input); reader = new HtmlTextReader(sr); Assert.AreEqual("class", reader.ReadAttributeName()); Assert.AreEqual("red", reader.ReadAttributeValue()); input = " class = 'red' "; sr = new StringReader(input); reader = new HtmlTextReader(sr); Assert.AreEqual("class", reader.ReadAttributeName()); Assert.AreEqual("red", reader.ReadAttributeValue()); // Make sure forward slashes are skipped in the right places... input = " /class = /red "; sr = new StringReader(input); reader = new HtmlTextReader(sr); Assert.AreEqual("class", reader.ReadAttributeName()); Assert.AreEqual("/red", reader.ReadAttributeValue()); // Make sure forward slashes are skipped in the right places... input = " class/ = red "; sr = new StringReader(input); reader = new HtmlTextReader(sr); Assert.AreEqual("class", reader.ReadAttributeName()); Assert.AreEqual("", reader.ReadAttributeValue()); Assert.AreEqual("=", reader.ReadAttributeName()); Assert.AreEqual("", reader.ReadAttributeValue()); Assert.AreEqual("red", reader.ReadAttributeName()); Assert.AreEqual("", reader.ReadAttributeValue()); // Make sure forward slashes are skipped in the right places... input = " /class /= /red "; sr = new StringReader(input); reader = new HtmlTextReader(sr); Assert.AreEqual("class", reader.ReadAttributeName()); Assert.AreEqual(String.Empty, reader.ReadAttributeValue()); Assert.AreEqual("=", reader.ReadAttributeName()); Assert.AreEqual(String.Empty, reader.ReadAttributeValue()); Assert.AreEqual("red", reader.ReadAttributeName()); Assert.AreEqual(String.Empty, reader.ReadAttributeValue()); }
public void ReadUnquotedAttribute() { string input; HtmlTextReader reader; string output; // no whitespace input = "=abc"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abc", output); // Starting whitespace input = " =abc"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abc", output); // Starting whitespace input = " \t\n\r=abc"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abc", output); // Ending whitespace input = "=abc "; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abc", output); // Whitespace start and end input = " = abc "; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abc", output); // Whitespace start and end input = " =\t\n\rabc \n\r"; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abc", output); // Whitespace end tag in the middle. Ensure // we don't consume the char. input = "= abc>def "; StringReader sr = new StringReader(input); reader = new HtmlTextReader(sr); output = reader.ReadAttributeValue(); Assert.AreEqual("abc", output); Assert.AreEqual('d', (char)reader.Peek()); Assert.AreEqual(ParseState.Text, reader.ParseState); // Ensure we don't consume the last space. input = " =abcdef "; sr = new StringReader(input); reader = new HtmlTextReader(sr); output = reader.ReadAttributeValue(); Assert.AreEqual("abcdef", output); Assert.AreEqual(' ', (char)reader.Peek()); }
public void ReadQuotedAttribute() { string input; HtmlTextReader reader; string output; // Ensure we parse to end of single quotes... input = " ='abc' "; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abc", output); // Ensure we parse to end of double quotes... input = " =\"abc\" "; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abc", output); // Ignore double quotes in the middle input = " ='abc\"def' "; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abc\"def", output); // Ignore end tag in the middle of quotes input = " ='abc>def' "; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abc>def", output); // Parse until end of string with open quote input = "= 'abcdef "; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abcdef ", output); // Parse until end of string with open quote input = "= \"abcdef "; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abcdef ", output); // Not checking whitespace inside quotes input = " =\"abcdef "; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abcdef ", output); // Ignore single quotes in the middle of double quotes input = " =\"abc'def\" "; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abc'def", output); // Ignore end tag in the middle of quotes input = " =\"abc>def\" "; reader = new HtmlTextReader(new StringReader(input)); output = reader.ReadAttributeValue(); Assert.AreEqual("abc>def", output); // Ensure we don't consume the >. input = " ='abcdef'>"; StringReader sr = new StringReader(input); reader = new HtmlTextReader(sr); output = reader.ReadAttributeValue(); Assert.AreEqual("abcdef", output); Assert.AreEqual('>', (char)reader.Peek()); }
/// <summary> /// Output the current node, or the changes required to the current node by the rendering code, to the writer. /// <img> nodes representing assessment items are handled elsewhere. /// </summary> private void HandleNode(HtmlTextReader reader, StreamWriter writer) { AIResources.Culture = LocalizationManager.GetCurrentCulture(); RloRenderContext context = AssessmentItemManager.RenderContext; if (reader.NodeType == HtmlNodeType.Element) { if (IsNamed(reader, "body")) { const string ecs = " ECS_ViewType=\"{0}\" leftmargin=0 topmargin=0 rightmargin=0 bottommargin=0 "; const string form = "<form NAME=\"{0}\" {1}METHOD=\"post\" ENCTYPE=\"multipart/form-data\" style=\"height:100%; width:100%; border:none; margin:0\">"; const string hidDetach = "<INPUT Name=\"hidDetach\" TYPE=\"HIDDEN\" value=\"0\">"; StringWriter bodyWriter = new StringWriter(CultureInfo.InvariantCulture); reader.CopyNode(bodyWriter); string body = bodyWriter.ToString(); bodyWriter.Close(); switch (context.View) { case SessionView.Execute: // update the <body> to include ECS_ViewType attribute and margin attributes body = body.Insert(5, String.Format(CultureInfo.InvariantCulture, ecs, "2")); break; case SessionView.RandomAccess: // update the <body> to include ECS_ViewType attribute and margin attributes body = body.Insert(5, String.Format(CultureInfo.InvariantCulture, ecs, "6")); break; case SessionView.Review: // update the <body> to include ECS_ViewType attribute and margin attributes body = body.Insert(5, String.Format(CultureInfo.InvariantCulture, ecs, "4")); break; } writer.Write(body); writer.Write(String.Format(CultureInfo.InvariantCulture, form, "frmPage", " ")); writer.Write(hidDetach); WriteFormHiddenControls(writer, context.FormHiddenControls); return; } // if ShowReviewerInformation is false, check all table elements for a bgColor="#ff99cb" // and remove them from display. else if (!context.ShowReviewerInformation && IsNamed(reader, "table") && IsBgColorFF99CB(reader)) { reader.Skip(); return; } } else if (reader.NodeType == HtmlNodeType.EndElement) { // insert a script section before the </head> if (IsNamed(reader, "head")) { switch (context.View) { case SessionView.Execute: writer.Write(AIResources.HeadExecuteViewScript); break; case SessionView.RandomAccess: // Security issue, FormElementId must be javascript safe. writer.Write(m_headGradingViewScript.Replace("<%=FormId%>", "frmPage")); break; case SessionView.Review: writer.Write(AIResources.ReviewViewScript); break; } reader.CopyNode(writer); return; } else if (IsNamed(reader, "body")) { // insert any RloRenderContext.ScriptToRender and the </form> before the </body> if (!String.IsNullOrEmpty(context.ScriptToRender)) { writer.WriteLine("<script>"); writer.WriteLine(context.ScriptToRender); writer.WriteLine("</script>"); } writer.Write("</form></body>"); return; } } reader.CopyNode(writer); }