Пример #1
0
 public void BeforeEachTest()
 {
     _id = "theId";
     _label = null;
     _result = null;
     _value = null;
 }
Пример #2
0
 public ElementBuilder(HTMLTag tag)
 {
     if (tag == HTMLTag.a)
     {
         this.tag = "a";
     }
     if (tag == HTMLTag.img)
     {
         this.tag = "img";
     }
     if (tag == HTMLTag.input)
     {
         this.tag = "input"; 
     }
 }
Пример #3
0
            /// <summary>
            /// Takes in a list of HTMLTag objects, merges them into a paired tag object based upon the value of their position parameters.
            /// </summary>
            /// <param name="HTMLTags">List of HTML Tags</param>
            /// <returns>List of Paired HTML Tags</returns>
            public static List <HTMLTagPair> PairHTMLTags(List <HTMLTag> HTMLTags)
            {
                // Create tag pair list
                List <HTMLTagPair> TagPairs = new List <HTMLTagPair>();

                // loop through tags
                for (int i = HTMLTags.Count - 1; i > -1; --i)
                {
                    HTMLTag openTag  = new HTMLTag();
                    HTMLTag closeTag = new HTMLTag();
                    bool    paired   = false;

                    // if we found an opening tag
                    if (HTMLTags[i].OpeningTag)
                    {
                        openTag = HTMLTags[i];
                        // loop through our list again (starting at idx i)
                        for (int j = 0; j < HTMLTags.Count; ++j)
                        {
                            // if we found a closing tag
                            if (!HTMLTags[j].OpeningTag)
                            {
                                // if our tag text matches and start position is lower
                                if (string.Equals(HTMLTags[i].TagText, HTMLTags[j].TagText, StringComparison.InvariantCultureIgnoreCase) &&
                                    (HTMLTags[i].StartPos < HTMLTags[j].StartPos))
                                {
                                    // if we already have a match
                                    if (paired)
                                    {
                                        // check if this match is closer
                                        if ((HTMLTags[j].StartPos - HTMLTags[i].StartPos) < (openTag.StartPos - closeTag.StartPos))
                                        {
                                            closeTag = HTMLTags[j];
                                        }
                                    }
                                    else
                                    {
                                        // no match, this matching tag is closest by default
                                        closeTag = HTMLTags[j];
                                        paired   = true;
                                    }
                                }
                            }
                        }
                        // if we found a match during the ?bubble sort.
                        if (paired)
                        {
                            HTMLTagPair tagPair = new HTMLTagPair()
                            {
                                OpenStartPos    = openTag.StartPos,
                                OpenEndPos      = openTag.EndPos,
                                ClosingStartPos = closeTag.StartPos,
                                ClosingEndPos   = closeTag.EndPos,
                                isOpenOnly      = false,
                                isCloseOnly     = false
                            };
                            TagPairs.Add(tagPair);
                            // Remove tags from list to prevent re-matching
                            HTMLTags.Remove(openTag);
                            HTMLTags.Remove(closeTag);
                        }
                        else
                        {
                            // if no match, add our open tag and set the isOpenOnly flag (could not find a matching closing html tag).
                            HTMLTagPair tagPair = new HTMLTagPair()
                            {
                                OpenStartPos    = openTag.StartPos,
                                OpenEndPos      = openTag.EndPos,
                                ClosingStartPos = -1,
                                ClosingEndPos   = -1,
                                isOpenOnly      = true,
                                isCloseOnly     = false
                            };
                            TagPairs.Add(tagPair);
                            // remove the open tag from our list
                            HTMLTags.Remove(openTag);
                        }
                    }
                }
                // Whatever is left in our list can be copied across as an unmatched close tag. Implicit conversion might look a bit cleaner?
                if (HTMLTags.Count > 0)
                {
                    foreach (HTMLTag tag in HTMLTags)
                    {
                        TagPairs.Add(new HTMLTagPair()
                        {
                            ClosingStartPos = tag.StartPos,
                            ClosingEndPos   = tag.EndPos,
                            OpenStartPos    = -1,
                            OpenEndPos      = -1,
                            isCloseOnly     = true,
                            isOpenOnly      = false,
                        });
                    }
                }
                return(TagPairs);
            }
Пример #4
0
        // Return DOMElement instead of Tag, since we -could- return
        private DOMElement _ParseTag(int startPosition)
        {
            // Initialize new Tag and empty Attribute
            HTMLTag          tag = new HTMLTag(startPosition);
            HTMLTagAttribute currentAttribute = null;

            // Start looping through the HTML (skip 1 char since we're already at the '<'
            tagParserState = TagParserState.ExpectingTagName;
            int currentPosition = startPosition + 1;

            while (currentPosition < _HTML.Length)
            {
                // Read char and advance
                char chr = _HTML[currentPosition];

                switch (tagParserState)
                {
                    #region TagParserState.ExpectingTagName - Look for an optional '/' and/or a tag name and possibly an ending '>' (if there's a '/' found)

                /*
                 * MATCHES:
                 * <DIV ATTRIBUTE="FOO" ATTR = 'BAR'> or </DIV>
                 *  ‾‾‾                                   ‾‾‾‾‾
                 */

                // When we're start a tag and waiting for the tag name...
                case TagParserState.ExpectingTagName:
                {
                    if (isAlphaNumericChar(chr))
                    {
                        // A letter in the tag name - add it to sbTemp and read the rest of the tag name
                        tag.TagName = _readAlphaNumericWord(currentPosition);

                        if (tag.TagName.StartsWith("!--"))
                        {
                            // HTML comment
                            HTMLContent comment = new HTMLContent(startPosition, _readUntil(startPosition, "-->"));
                            return(comment);
                        }
                        else
                        {
                            // Any tag conversions?
                            switch (tag.TagName.ToLower())
                            {
                            case "form":
                                tag = new HTMLForm(tag.StartPosition)
                                {
                                    TagName = tag.TagName
                                };
                                break;

                            case "input":
                                tag = new HTMLInput(tag.StartPosition)
                                {
                                    TagName = tag.TagName
                                };
                                break;

                            case "select":
                                tag = new HTMLSelect(tag.StartPosition)
                                {
                                    TagName = tag.TagName
                                };
                                break;

                            case "option":
                                tag = new HTMLSelectOption(tag.StartPosition)
                                {
                                    TagName = tag.TagName
                                };
                                break;

                            case "textarea":
                                tag = new HTMLTextarea(tag.StartPosition)
                                {
                                    TagName = tag.TagName
                                };
                                break;
                            }

                            // Advance position by name length
                            currentPosition += tag.TagName.Length;
                            tagParserState   = TagParserState.ExpectingTagContentsOrEnd;
                        }
                    }
                    else if (chr == '/')
                    {
                        // This is a closing tag like </div> - read the tag name and close it
                        tag.IsClosingTag = true;

                        // Advance to the start of the tag name and read it
                        currentPosition  = this._indexOfNextNonWhitespaceChar(currentPosition + 1);
                        tag.TagName      = _readAlphaNumericWord(currentPosition);
                        currentPosition += tag.TagName.Length;

                        // Advance to end of tag '>'
                        currentPosition += _readUntil(currentPosition, '>').Length - 1;
                        tagParserState   = TagParserState.TagEnded;
                    }
                }
                break;
                    #endregion

                    #region TagParserState.ExpectingAttributeNameOrTagEnd - Inside the tag, looking for either alpha chars (start of an attribute), or a '/' self-closing flag, or the closing '>' character
                case TagParserState.ExpectingTagContentsOrEnd:

                    // Advance to the next non-whitespace char
                    currentPosition = _indexOfNextNonWhitespaceChar(currentPosition);
                    chr             = _HTML[currentPosition];

                    if (chr == '/')
                    {
                        /* MATCHES: <IMG />
                         *               ‾‾
                         */

                        // Self-closing tag
                        tag.SelfClosed = true;

                        // Advance to end of tag '>'
                        currentPosition += _readUntil(currentPosition, '>').Length - 1;
                        tagParserState   = TagParserState.TagEnded;
                    }
                    else if (chr == '>')
                    {
                        /* MATCHES: <DIV>
                         *              ‾
                         */

                        // End of tag
                        tagParserState = TagParserState.TagEnded;
                    }
                    else if ((chr == '"') || (chr == '\''))
                    {
                        // Unnamed, quoted attribute value, like a DOCTYPE dtd path <!DOCTYPE html "blah blah">

                        // Read the quoted value
                        string attributeValue = _readValue(currentPosition);

                        // Build a new attribute
                        currentAttribute = new HTMLTagAttribute(currentPosition, null, attributeValue, chr.ToString());

                        // Advance the position
                        currentPosition += attributeValue.Length;

                        // Finish the attribute and clear it
                        currentAttribute.EndPosition = currentPosition;
                        tag.Attributes.Add(currentAttribute);
                        currentAttribute = null;
                    }
                    else if (isAlphaChar(chr))
                    {
                        /*
                         * MATCHES:
                         * <DIV ATTRIBUTE="FOO" ATTR = 'BAR'>
                         *      ‾‾‾‾‾‾‾‾‾       ‾‾‾‾
                         */
                        // A letter in the attribute name - read the rest of the attribute
                        string attributeName = _readAlphaNumericWord(currentPosition);
                        currentAttribute = new HTMLTagAttribute(currentPosition, attributeName);

                        // Advance position to the end of the name
                        currentPosition += attributeName.Length;

                        // Do we have an attribute value?
                        int nextNonWhitespaceChar = _indexOfNextNonWhitespaceChar(currentPosition);
                        if (_HTML[nextNonWhitespaceChar] == '=')
                        {
                            // tagParserState = TagParserState.ExpectingAttributeValue;
                            currentPosition = nextNonWhitespaceChar + 1;

                            // Advance to the next non-whitespace char (in case of space-separated values like 'foo = "bar"'
                            nextNonWhitespaceChar = _indexOfNextNonWhitespaceChar(currentPosition);
                            string rawAttributeValue = _readValue(currentPosition);
                            currentAttribute.Value = rawAttributeValue;

                            // Advance position to end of the value
                            currentPosition += rawAttributeValue.Length;
                        }
                        else
                        {
                            // A standalone attributelike <!DOCTYPE html "foobar">
                            //                                      ‾‾‾‾
                        }

                        // End of attribute - mark the end position and add to the tag
                        currentAttribute.EndPosition = currentPosition;
                        tag.Attributes.Add(currentAttribute);

                        // Reset attribute
                        currentAttribute = null;
                    }
                    break;
                    #endregion
                }

                // End the tag?
                if (tagParserState == TagParserState.TagEnded)
                {
                    // Apply transformations?
                    if (_transforms == Transformations.LowercaseNames)
                    {
                        tag.TagName = tag.TagName.ToLower();
                        foreach (HTMLTagAttribute attr in tag.Attributes)
                        {
                            if (attr.Name != null)
                            {
                                attr.Name = attr.Name.ToLower();
                            }
                        }
                    }
                    else if (_transforms == Transformations.UppercaseNames)
                    {
                        tag.TagName = tag.TagName.ToUpper();
                        foreach (HTMLTagAttribute attr in tag.Attributes)
                        {
                            if (attr.Name != null)
                            {
                                attr.Name = attr.Name.ToUpper();
                            }
                        }
                    }

                    // Remove empty attributes list
                    if (tag.Attributes.Count == 0)
                    {
                        tag.Attributes = null;
                    }

                    // Mark the end position of the tag and return it
                    tag.MarkEndPosition(currentPosition);
                    return(tag);
                }
            }

            // Shouldn't really get here...
            return(tag);
        }
        private DOMContainer Raw2Hierarchy(List <DOMElement> rawResults)
        {
            // Create a DOM container
            DOMContainer domObject = new DOMContainer();

            // Define the current parent element
            HTMLTag currentParent = domObject;

            // Define our starting stack
            List <HTMLTag> openTagStack = new List <HTMLTag>()
            {
                currentParent
            };

            // Keep a running reference to any active <form> tags and <select> tags
            HTMLForm   currentForm   = null;
            HTMLSelect currentSelect = null;

            // Pre-processing - find and update self-closing tags like <IMG> and <BR> and eliminate any
            // unnecessary closing tags like </IMG> or </BR>
            List <DOMElement> elementsToRemove = new List <DOMElement>();

            foreach (DOMElement element in rawResults)
            {
                if (element is HTMLTag)
                {
                    HTMLTag elementTag     = (HTMLTag)element;
                    string  elementTagName = elementTag.TagName.ToUpper();
                    switch (elementTagName)
                    {
                    case "AREA":
                    case "BASE":
                    case "BR":
                    case "COL":
                    case "COMMAND":
                    case "EMBED":
                    case "HR":
                    case "IMG":
                    case "INPUT":
                    case "KEYGEN":
                    case "LINK":
                    case "META":
                    case "PARAM":
                    case "SOURCE":
                    case "TRACK":
                    case "WBR":
                        if (elementTag.IsClosingTag)
                        {
                            // </IMG> and </BR> and so on are invalid closing tags...
                            domObject.Warnings.Add("Marking " + element + " to be deleted (REASON: Self-closed tag)");
                            elementsToRemove.Add(elementTag);
                        }
                        else if (!elementTag.SelfClosed)
                        {
                            // <IMG> and <BR> and so on are self-closed tags...
                            domObject.Warnings.Add("Marking " + element + " as self-closed (REASON: Self-closed tag)");
                            elementTag.SelfClosed = true;
                        }
                        break;
                    }
                }
            }

            // Remove bad tags
            if (elementsToRemove.Count > 0)
            {
                foreach (DOMElement element in elementsToRemove)
                {
                    Console.WriteLine("Removing " + element);
                    rawResults.Remove(element);
                }
            }

            List <string> domErrors   = new List <string>();
            List <string> domWarnings = new List <string>();

            while (rawResults.Count > 0)
            {
                // Shift off the beginning
                DOMElement nextElement = rawResults[0];
                rawResults.RemoveAt(0);

                // string indent = "".PadLeft(openTagStack.Count,'\t');

                // If it's an opening tag, let's update the parentElement
                if (nextElement is HTMLTag)
                {
                    // Cast once
                    HTMLTag nextElementTag = (HTMLTag)nextElement;

                    // Console.Write(indent + nextElementTag + ": ");

                    // If it's an opening tag
                    if (nextElementTag.IsClosingTag)
                    {
                        // Closing tag - try to match to parent
                        // Console.Write("Closing tag, trying to match to current parent " + currentParent + "... ");

                        // If this is a closing </form>, then null out currentForm
                        if (nextElementTag.TagName == "form")
                        {
                            currentForm = null;
                        }
                        // Else If this is a closing </select>, then null out currentSelect
                        else if (nextElementTag.TagName == "select")
                        {
                            currentSelect = null;
                        }

                        // Check to see if the current parent matches the current element (<td><p></p></td> and not malformed HTML like <p><td></p></td>)
                        if (nextElementTag.TagName == currentParent.TagName)
                        {
                            // Mark current parent as successfully closing
                            // currentParent.Closes = true;

                            // Closing tag - pop the stack
                            openTagStack.Remove(currentParent);
                            currentParent = openTagStack.Last();

                            // Console.WriteLine("Match - popped the stack and adding to end of new currentParent " + currentParent + ".");

                            // REMOVED - So the hierarchy only lists the open node and the closed can be
                            //           inferred from the hierarchy.
                            // Move to current parent
                            // currentParent.Children.Add(nextElement);
                        }
                        else
                        {
                            // Console.WriteLine("Not a match - searching stack for a match...");

                            // Malformed HTML detected, try to find a matching open parent from the bottom to the top
                            bool foundStackSearchMatch = false;
                            for (int j = openTagStack.Count - 1; j >= 0; j--)
                            {
                                // Found it!
                                // Console.Write(indent + "  " + nextElementTag + " == " + openTagStack[j] + " ? ");
                                if (openTagStack[j].TagName == nextElementTag.TagName)
                                {
                                    domObject.Warnings.Add(nextElementTag + " was out of sequence. Current parent tag is " + currentParent + " but matching " + openTagStack[j] + " was found further outside.");

                                    // Console.WriteLine("Match! Moving to its parent.");
                                    foundStackSearchMatch = true;

                                    // REMOVED - See above reason.
                                    // Add to parent
                                    // openTagStack[j - 1].Children.Add(nextElement);
                                    // openTagStack[j - 1].Closes = true;

                                    // Remove that element from the open stack
                                    openTagStack.RemoveAt(j);
                                    break;
                                }
                            }
                            if (!foundStackSearchMatch)
                            {
                                // Uh-oh.... add it to the current parent
                                domObject.Errors.Add(nextElementTag + " did not match up to any open tag! Position in HTML: " + nextElementTag.StartPosition);
                                // currentParent.Children.Add(nextElement);
                                // Console.Write(indent + "  No matches found - adding to the currentParent " + currentParent);
                            }
                        }
                    }
                    else if (nextElementTag.SelfClosed)
                    {
                        // Self-closed tag
                        // Console.WriteLine("Self-closed tag, adding to current parent " + currentParent + "");

                        // Move to current parent
                        currentParent.Children.Add(nextElement);

                        // <input>s
                        if ((nextElement is HTMLInput) && (currentForm != null))
                        {
                            currentForm.Inputs.Add((HTMLInput)nextElement);
                            if (((HTMLInput)nextElement).Name != null)
                            {
                                currentForm.NamedInputs.Add((HTMLInput)nextElement);
                            }
                        }

                        // <option />s
                        else if ((nextElement is HTMLSelectOption) && (currentSelect != null))
                        {
                            currentSelect.Options.Add((HTMLSelectOption)nextElement);
                        }
                    }
                    else
                    {
                        // Open tag - push onto the stack
                        // Console.WriteLine("Open tag, adding to currentParent " + currentParent + ", adding to stack, and setting as new currentParent.");

                        // Move to current parent
                        currentParent.Children.Add(nextElementTag);

                        // <select>s and <textarea>s
                        if ((nextElement is HTMLInput) && (currentForm != null))
                        {
                            currentForm.Inputs.Add((HTMLInput)nextElement);
                            if (((HTMLInput)nextElement).Name != null)
                            {
                                currentForm.NamedInputs.Add((HTMLInput)nextElement);
                            }

                            // Indicate we're in a <select> (for easier <option> association)
                            if (nextElement is HTMLSelect)
                            {
                                currentSelect = (HTMLSelect)nextElement;
                            }
                        }
                        // <option />s
                        else if ((nextElement is HTMLSelectOption) && (currentSelect != null))
                        {
                            currentSelect.Options.Add((HTMLSelectOption)nextElement);
                        }

                        // Make this the new currentParent
                        openTagStack.Add(nextElementTag);
                        currentParent = nextElementTag;

                        // Initialize children list
                        currentParent.Children = new List <DOMElement>();

                        // Update current form
                        if (currentParent is HTMLForm)
                        {
                            currentForm = (HTMLForm)currentParent;
                        }
                    }
                }
                else
                {
                    // Content goes into current parent
                    currentParent.Children.Add(nextElement);
                }
            }

            // Return final result
            return(domObject);
        }
Пример #6
0
 private void with_a_tag_that_has_content()
 {
     const string html = "<html><head><title>" + TitleHtml + "</title></head><body>Hello World</body></html>";
     _tag = HTMLParser.Parse(html)
         .DescendantTags
         .OfType("title")
         .First();
 }
Пример #7
0
 private void when_asked_for_its_parent_tag()
 {
     _result = _tag.Parent;
 }
Пример #8
0
        public string OpenWordTags( int pageIndex, int lineIndex, int wordIndex )
        {
            HTMLTag [] tags = new HTMLTag[5];
            string ret = "";
            foreach ( HTMLTag tag in m_Body )
                tags[(int)tag.Type] = tag;
            if ( m_Pages.ContainsKey( pageIndex ) )
                foreach ( HTMLTag tag in m_Pages[pageIndex] )
                    tags[(int)tag.Type] = tag;

            int index = GetLineIndex( pageIndex, lineIndex );
            if ( m_Lines.ContainsKey( index ) )
                foreach ( HTMLTag tag in m_Lines[index] )
                    tags[(int)tag.Type] = tag;

            index = GetWordIndex( pageIndex, lineIndex, wordIndex );
            if ( m_Words.ContainsKey( index ) )
                foreach ( HTMLTag tag in m_Words[index] )
                    tags[(int)tag.Type] = tag;

            string basefont = ""; // basefont must always come first
            for ( int i = 0; i < tags.Length; i++ )
            {
                if ( tags[i] != null )
                {
                    if ( tags[i].Type == TagType.Color )
                        basefont = tags[i].OpenTag();
                    else if ( tags[i].Type != TagType.Alignment )
                        ret += tags[i].OpenTag();
                }
            }

            return basefont + ret;
        }
Пример #9
0
 private void when_asked_to_create_a_span()
 {
     var span = new SpanData(_value)
         .WithLabel(_label)
         .WithId(_id);
     var resultHtml = span.ToString();
     _result = HTMLParser.Parse("<all>" + resultHtml + "</all>");
 }
        /// <summary>
        /// This method will download an amortization table for the
        /// specified parameters.
        /// </summary>
        /// <param name="interest">The interest rate for the loan.</param>
        /// <param name="term">The term(in months) of the loan.</param>
        /// <param name="principle">The principle amount of the loan.</param>
        public void process(double interest, int term, int principle)
        {
            Uri        url  = new Uri("http://www.httprecipes.com/1/9/loan.php");
            WebRequest http = HttpWebRequest.Create(url);

            http.Timeout     = 30000;
            http.ContentType = "application/x-www-form-urlencoded";
            http.Method      = "POST";
            Stream ostream = http.GetRequestStream();



            FormUtility form = new FormUtility(ostream, null);

            form.Add("interest", "" + interest);
            form.Add("term", "" + term);
            form.Add("principle", "" + principle);
            form.Complete();
            ostream.Close();
            WebResponse response = http.GetResponse();

            Stream        istream = response.GetResponseStream();
            ParseHTML     parse   = new ParseHTML(istream);
            StringBuilder buffer  = new StringBuilder();
            List <String> list    = new List <String>();
            bool          capture = false;

            Advance(parse, "table", 3);

            int ch;

            while ((ch = parse.Read()) != -1)
            {
                if (ch == 0)
                {
                    HTMLTag tag = parse.Tag;
                    if (String.Compare(tag.Name, "tr", true) == 0)
                    {
                        list.Clear();
                        capture       = false;
                        buffer.Length = 0;
                    }
                    else if (String.Compare(tag.Name, "/tr", true) == 0)
                    {
                        if (list.Count > 0)
                        {
                            ProcessTableRow(list);
                            list.Clear();
                        }
                    }
                    else if (String.Compare(tag.Name, "td", true) == 0)
                    {
                        if (buffer.Length > 0)
                        {
                            list.Add(buffer.ToString());
                        }
                        buffer.Length = 0;
                        capture       = true;
                    }
                    else if (String.Compare(tag.Name, "/td", true) == 0)
                    {
                        list.Add(buffer.ToString());
                        buffer.Length = 0;
                        capture       = false;
                    }
                    else if (String.Compare(tag.Name, "/table", true) == 0)
                    {
                        break;
                    }
                }
                else
                {
                    if (capture)
                    {
                        buffer.Append((char)ch);
                    }
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Use the session to search for the specified state or capital.  The search
        /// method can be called multiple times per login.
        /// </summary>
        /// <param name="session">The session to use.</param>
        /// <param name="search">The search string to use.</param>
        /// <param name="type">What to search for(s=state,c=capital).</param>
        /// <returns>A list of states or capitals.</returns>
        public List <String> Search(String session, String search, String type)
        {
            String        listType    = "ul";
            String        listTypeEnd = "/ul";
            StringBuilder buffer      = new StringBuilder();
            bool          capture     = false;
            List <String> result      = new List <String>();

            // Build the URL.
            MemoryStream mstream = new MemoryStream();
            FormUtility  form    = new FormUtility(mstream, null);

            form.Add("search", search);
            form.Add("type", type);
            form.Add("action", "Search");
            form.Complete();

            Uri url = new Uri("http://www.httprecipes.com/1/8/menunc.php?session="
                              + session);
            WebRequest http = HttpWebRequest.Create(url);

            http.Timeout     = 30000;
            http.ContentType = "application/x-www-form-urlencoded";
            http.Method      = "POST";
            Stream ostream = http.GetRequestStream();

            // Perform the post.
            byte[] b = mstream.GetBuffer();
            ostream.Write(b, 0, b.Length);
            ostream.Close();

            // Read the results.
            WebResponse response = http.GetResponse();
            Stream      istream  = response.GetResponseStream();

            ParseHTML parse = new ParseHTML(istream);

            // Parse from the URL.
            Advance(parse, listType, 0);

            int ch;

            while ((ch = parse.Read()) != -1)
            {
                if (ch == 0)
                {
                    HTMLTag tag = parse.Tag;
                    if (String.Compare(tag.Name, "li", true) == 0)
                    {
                        if (buffer.Length > 0)
                        {
                            result.Add(buffer.ToString());
                        }
                        buffer.Length = 0;
                        capture       = true;
                    }
                    else if (String.Compare(tag.Name, "/li", true) == 0)
                    {
                        result.Add(buffer.ToString());
                        buffer.Length = 0;
                        capture       = false;
                    }
                    else if (String.Compare(tag.Name, listTypeEnd, true) == 0)
                    {
                        result.Add(buffer.ToString());
                        break;
                    }
                }
                else
                {
                    if (capture)
                    {
                        buffer.Append((char)ch);
                    }
                }
            }

            return(result);
        }
Пример #12
0
        /**
         * Access the website and perform a search for either states or capitals.
         * @param search A search string.
         * @param type What to search for(s=state, c=capital)
         * @throws IOException Thrown if an IO exception occurs.
         */
        public void Process(String search, String type)
        {
            String        listType    = "ul";
            String        listTypeEnd = "/ul";
            StringBuilder buffer      = new StringBuilder();
            bool          capture     = false;

            // Build the URL and POST.
            Uri        url  = new Uri("http://www.httprecipes.com/1/7/post.php");
            WebRequest http = HttpWebRequest.Create(url);

            http.Timeout     = 30000;
            http.ContentType = "application/x-www-form-urlencoded";
            http.Method      = "POST";
            Stream ostream = http.GetRequestStream();

            FormUtility form = new FormUtility(ostream, null);

            form.Add("search", search);
            form.Add("type", type);
            form.Add("action", "Search");
            form.Complete();
            ostream.Close();

            // read the results
            HttpWebResponse response = (HttpWebResponse)http.GetResponse();
            Stream          istream  = response.GetResponseStream();

            ParseHTML parse = new ParseHTML(istream);

            // parse from the URL

            Advance(parse, listType, 0);

            int ch;

            while ((ch = parse.Read()) != -1)
            {
                if (ch == 0)
                {
                    HTMLTag tag = parse.Tag;
                    if (String.Compare(tag.Name, "li", true) == 0)
                    {
                        if (buffer.Length > 0)
                        {
                            ProcessItem(buffer.ToString());
                        }
                        buffer.Length = 0;
                        capture       = true;
                    }
                    else if (String.Compare(tag.Name, "/li", true) == 0)
                    {
                        ProcessItem(buffer.ToString());
                        buffer.Length = 0;
                        capture       = false;
                    }
                    else if (String.Compare(tag.Name, listTypeEnd, true) == 0)
                    {
                        ProcessItem(buffer.ToString());
                        break;
                    }
                }
                else
                {
                    if (capture)
                    {
                        buffer.Append((char)ch);
                    }
                }
            }
        }
Пример #13
0
        /// <summary>
        /// Setup the login status control
        /// </summary>
        protected override void Setup()
        {
            base.Setup();

            HTMLTag <object> listItem = Helpers.HTMLTag("li");

            listItem.AddClass("dropdown");

            string loginUrl   = VirtualPathUtility.ToAbsolute(FormsAuthentication.LoginUrl);
            string defaultUrl = VirtualPathUtility.ToAbsolute(FormsAuthentication.DefaultUrl);

            // Logged in
            if (Singular.Security.Security.HasAuthenticatedUser)
            {
                MEIdentity identity = MEWebSecurity.CurrentIdentity();

                var aTagUserName = listItem.Helpers.HTMLTag("a");
                aTagUserName.AddClass("dropdown-toggle count-info");
                aTagUserName.Attributes["data-toggle"] = "dropdown";
                {
                    aTagUserName.Helpers.HTML(MELib.CommonData.Lists.ROUserList.GetItem(identity.UserID).FullName);
                    var iTagUserName = aTagUserName.Helpers.HTMLTag("i");
                    iTagUserName.AddClass("fa fa-angle-down fa-lg");
                }

                var ulTagDropDown = listItem.Helpers.HTMLTag("ul");
                ulTagDropDown.AddClass("dropdown-menu animated fadeInRight");
                {
                    var liTagEditProfile = ulTagDropDown.Helpers.HTMLTag("li");
                    {
                        var aTagEditProfile = liTagEditProfile.Helpers.HTMLTag("a");
                        aTagEditProfile.Attributes["href"] = VirtualPathUtility.ToAbsolute("~/Users/UserProfile.aspx?UserID=" + HttpUtility.UrlEncode(Singular.Encryption.EncryptString(identity.UserID.ToString())));
                        {
                            var iTagEditProfile = aTagEditProfile.Helpers.HTMLTag("i");
                            iTagEditProfile.AddClass("fa fa-user pad_5_right");
                        }
                        aTagEditProfile.Helpers.HTML("Edit Profile");
                    }

                    var liDivider = ulTagDropDown.Helpers.HTMLTag("li");
                    liDivider.AddClass("divider");

                    var liTagChangePassword = ulTagDropDown.Helpers.HTMLTag("li");
                    {
                        var aTagChangePassword = liTagChangePassword.Helpers.HTMLTag("a");
                        aTagChangePassword.Attributes["href"] = VirtualPathUtility.ToAbsolute("~/Account/ChangePassword.aspx");
                        {
                            var iTagChangePassword = aTagChangePassword.Helpers.HTMLTag("i");
                            iTagChangePassword.AddClass("fa fa-lock pad_5_right");
                        }
                        aTagChangePassword.Helpers.HTML("Change Password");
                    }

                    var liDivider1 = ulTagDropDown.Helpers.HTMLTag("li");
                    liDivider1.AddClass("divider");

                    var liTagLogout = ulTagDropDown.Helpers.HTMLTag("li");
                    {
                        var aTagLogout = liTagLogout.Helpers.HTMLTag("a");
                        aTagLogout.Attributes["href"] = defaultUrl + "?SCmd=Logout";
                        {
                            var iTagLogout = aTagLogout.Helpers.HTMLTag("i");
                            iTagLogout.AddClass("fa fa-sign-out pad_5_right");
                        }
                        aTagLogout.Helpers.HTML("Log Out");
                    }
                }
            }
            else
            {
                // Logged out
                var aLogin = listItem.Helpers.HTMLTag("a");
                {
                    var iTagUserName = aLogin.Helpers.HTMLTag("i");
                    iTagUserName.AddClass("fa fa-sign-in fa-lg");
                    aLogin.Attributes["href"] = loginUrl;
                    aLogin.Helpers.HTML("Log In");
                }
            }
        }
Пример #14
0
 private void when_asked_for_the_BODY_tag()
 {
     _result = HTMLParser.Parse(_html).Body;
 }
Пример #15
0
        public string CloseWordTags( int pageIndex, int lineIndex, int wordIndex )
        {
            HTMLTag [] tags = new HTMLTag[5];
            string ret = "";
            foreach ( HTMLTag tag in m_Body )
                tags[(int)tag.Type] = tag;
            if ( m_Pages.ContainsKey( pageIndex ) )
                foreach ( HTMLTag tag in m_Pages[pageIndex] )
                    tags[(int)tag.Type] = tag;

            int index = GetLineIndex( pageIndex, lineIndex );
            if ( m_Lines.ContainsKey( index ) )
                foreach ( HTMLTag tag in m_Lines[index] )
                    tags[(int)tag.Type] = tag;

            index = GetWordIndex( pageIndex, lineIndex, wordIndex );
            if ( m_Words.ContainsKey( index ) )
                foreach ( HTMLTag tag in m_Words[index] )
                    tags[(int)tag.Type] = tag;

            for ( int i = tags.Length-1; i >=0; i-- )
                if ( tags[i] != null && tags[i].Type != TagType.Alignment )
                    ret += tags[i].CloseTag();

            return ret;
        }
Пример #16
0
 private void when_asked_for_the_HEAD_tag()
 {
     _result = HTMLParser.Parse(_html).Head;
 }
Пример #17
0
 private void when_asked_to_parse_the_string()
 {
     _result = HTMLParser.Parse(_html);
 }