Exemplo n.º 1
0
 protected virtual bool HasRelCanonicalPointingToDifferentUrl(IDomElement e, string orginalUrl)
 {
     return e.HasAttribute("rel") && !string.IsNullOrWhiteSpace(e.Attributes["rel"]) &&
             string.Equals(e.Attributes["rel"], "canonical", StringComparison.OrdinalIgnoreCase) &&
             e.HasAttribute("href") && !string.IsNullOrWhiteSpace(e.Attributes["href"]) &&
             !string.Equals(e.Attributes["href"], orginalUrl, StringComparison.OrdinalIgnoreCase);
 }
Exemplo n.º 2
0
        private static bool ElementIsItselfHidden(IDomElement el)
        {
            if (el.NodeNameID == HtmlData.tagINPUT && el.Type == "hidden")
            {
                return true;
            }

            if (el.HasStyles)
            {
                if (el.Style["display"] == "none" || el.Style.NumberPart("opacity") == 0)
                {
                    return true;
                }
                double? wid = el.Style.NumberPart("width");
                double? height = el.Style.NumberPart("height");
                if (wid == 0 || height == 0)
                {
                    return true;
                }
            }
            string widthAttr, heightAttr;
            widthAttr = el.GetAttribute("width");
            heightAttr = el.GetAttribute("height");

            return widthAttr == "0" || heightAttr == "0";
        }
Exemplo n.º 3
0
        public override MatchResult Match <TDependencyObject>(StyleSheet styleSheet, ref IDomElement <TDependencyObject> domElement, SelectorMatcher[] fragments, ref int currentIndex)
        {
            var tagName      = domElement.TagName;
            var namespaceUri = domElement.AssemblyQualifiedNamespaceName;

            return(domElement.Parent?.ChildNodes
                   .Where(x => x.TagName == tagName && x.AssemblyQualifiedNamespaceName == namespaceUri)
                   .Count() == 1 ? MatchResult.Success : MatchResult.ItemFailed);
        }
Exemplo n.º 4
0
 /// <summary>
 /// Has "rel" canonical pointing To different url
 /// </summary>
 /// <param name="element"></param>
 /// <param name="orginalUrl"></param>
 /// <returns></returns>
 protected virtual bool HasRelCanonicalPointingToDifferentUrl(IDomElement element, string orginalUrl)
 {
     return(element.HasAttribute(Rel) &&
            !string.IsNullOrWhiteSpace(element.Attributes[Rel]) &&
            string.Equals(element.Attributes[Rel], Canonical, StringComparison.OrdinalIgnoreCase) &&
            element.HasAttribute(Href) &&
            !string.IsNullOrWhiteSpace(element.Attributes[Href]) &&
            !string.Equals(element.Attributes[Href], orginalUrl, StringComparison.OrdinalIgnoreCase));
 }
Exemplo n.º 5
0
        public HtmlOptionsCollection(IDomElement parent)
        {
            if (parent.NodeNameID != HtmlData.tagOPTION)
            {
                throw new ArgumentException("The parent node for an HtmlOptionsCollection must be an Option node.");
            }

            Parent = (IDomElementSelect)parent;
        }
Exemplo n.º 6
0
        private bool IsValidOGNode(IDomElement elem)
        {
            if (!elem.HasAttribute("property"))
            {
                return(false);
            }

            return(elem.GetAttribute("property").StartsWith("og:"));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Parses the key/value pair from a node, and adds them to the result.
        /// </summary>
        /// <param name="elem">Element to get info from.</param>
        /// <param name="res">Result object to extract data to.</param>
        private void AddDataToResult(IDomElement elem, OpenGraphData res)
        {
            var key = ParseKeyFromNode(elem);

            if (!res.ContainsKey(key))
            {
                res.Add(key, ParseValueFromNode(elem));
            }
        }
Exemplo n.º 8
0
        public void Add()
        {
            Assert.AreEqual(jQuery("#sndp").Add("#en").Add("#sap").Get(), q("sndp", "en", "sap"), "Check elements from document");
            Assert.AreEqual(jQuery("#sndp").Add(jQuery("#en")[0]).Add(jQuery("#sap")).Get(), q("sndp", "en", "sap"), "Check elements from document");

            // We no longer support .Add(form.elements), unfortunately.
            // There is no way, in browsers, to reliably determine the difference
            // between form.elements and form - and doing .Add(form) and having it
            // add the form elements is way to unexpected, so this gets the boot.
            // ok( jQuery([]).Add(jQuery("#form")[0].elements).Length >= 13, "Check elements from array" );

            // For the time being, we're discontinuing support for jQuery(form.elements) since it's ambiguous in IE
            // use jQuery([]).Add(form.elements) instead.
            //Assert.AreEqual(jQuery([]).Add(jQuery("#form")[0].elements).Length, jQuery(jQuery("#form")[0].elements).Length, "Array in constructor must equals array in add()" );

            //TODO: It would be nice to have a ParentNode exist & be typed to 11 for disconnected nodes. However this creates some complexity
            //b/c we still need to keep the nodes conceptually bound to another domain. I think that we may want a special "disconnected" heirarchy
            //within and IDomRoot. For now just compare to null instead.

            var divs = jQuery("<div/>").Add("#sndp");

            //Assert.IsTrue( (int)divs[0].ParentNode.NodeType ==11, "Make sure the first element is still the disconnected node." );
            Assert.IsTrue(divs[0].ParentNode == null, "Make sure the first element is still the disconnected node.");

            divs = jQuery("<div>test</div>").Add("#sndp");
            //Assert.AreEqual((int)divs[0].ParentNode.NodeType, 11, "Make sure the first element is still the disconnected node." );
            Assert.AreEqual(divs[0].ParentNode, null, "Make sure the first element is still the disconnected node.");

            divs = jQuery("#sndp").Add("<div/>");
            Assert.IsTrue(divs[1].ParentNode == null, "Make sure the first element is still the disconnected node.");

            var tmp = jQuery("<div/>");

            var x = CQ.Create().Add(jQuery("<p id='x1'>xxx</p>").AppendTo(tmp)).Add(jQuery("<p id='x2'>xxx</p>").AppendTo(tmp));

            Assert.AreEqual(x[0].Id, "x1", "Check on-the-fly element1");
            Assert.AreEqual(x[1].Id, "x2", "Check on-the-fly element2");

            x = CQ.Create().Add(jQuery("<p id='x1'>xxx</p>").AppendTo(tmp)[0]).Add(jQuery("<p id='x2'>xxx</p>").AppendTo(tmp)[0]);
            Assert.AreEqual(x[0].Id, "x1", "Check on-the-fly element1");
            Assert.AreEqual(x[1].Id, "x2", "Check on-the-fly element2");

            x = CQ.Create().Add(jQuery("<p id='x1'>xxx</p>")).Add(jQuery("<p id='x2'>xxx</p>"));
            Assert.AreEqual(x[0].Id, "x1", "Check on-the-fly element1");
            Assert.AreEqual(x[1].Id, "x2", "Check on-the-fly element2");

            x = CQ.Create().Add("<p id='x1'>xxx</p>").Add("<p id='x2'>xxx</p>");
            Assert.AreEqual(x[0].Id, "x1", "Check on-the-fly element1");
            Assert.AreEqual(x[1].Id, "x2", "Check on-the-fly element2");

            IDomElement notDefined = null;

            Assert.AreEqual(CQ.Create().Add(notDefined).Length, 0, "Check that undefined adds nothing");

            Assert.AreEqual(CQ.Create().Add(document.GetElementById("form")).Length, 1, "Add a form");
            Assert.AreEqual(CQ.Create().Add(document.GetElementById("select1")).Length, 1, "Add a select");
        }
Exemplo n.º 9
0
        /// <summary>
        /// Return the last child of the parent
        /// </summary>
        ///
        /// <param name="element">
        /// The parent element.
        /// </param>
        ///
        /// <returns>
        /// A sequence of children that match.
        /// </returns>

        public override IEnumerable <IDomObject> ChildMatches(IDomContainer element)
        {
            IDomElement child = element.LastElementChild;

            if (child != null)
            {
                yield return(child);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates an HTMLOptionsCollection from the children of a Select element.
        /// </summary>
        ///
        /// <exception cref="ArgumentException">
        /// Thrown when one or more arguments have unsupported or illegal values.
        /// </exception>
        ///
        /// <param name="parent">
        /// The parent element for this collection.
        /// </param>

        public HTMLOptionsCollection(IDomElement parent)
        {
            if (parent.NodeNameID != HtmlData.tagSELECT)
            {
                throw new ArgumentException("The parent node for an HtmlOptionsCollection must be a SELECT node.");
            }

            Parent = (IHTMLSelectElement)parent;
        }
Exemplo n.º 11
0
        public HtmlOptionsCollection(IDomElement parent)
        {
            if (parent.NodeNameID != HtmlData.tagOPTION)
            {
                throw new ArgumentException("The parent node for an HtmlOptionsCollection must be an Option node.");
            }

            Parent = (IDomElementSelect)parent;
        }
Exemplo n.º 12
0
        public string LookupPrefix(IDomElement <UIElement> dependencyObject, string namespaceUri)
        {
            if (prefixToNamespaceUri.Any(x => x.Value == namespaceUri))
            {
                return(prefixToNamespaceUri.FirstOrDefault(x => x.Value == namespaceUri).Key);
            }

            return(null);
        }
Exemplo n.º 13
0
        public string LookupNamespaceUri(IDomElement <UIElement> dependencyObject, string prefix)
        {
            if (prefixToNamespaceUri.ContainsKey(prefix))
            {
                return(prefixToNamespaceUri[prefix]);
            }

            return(null);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Creates an HTMLOptionsCollection from the children of a Select element.
        /// </summary>
        ///
        /// <exception cref="ArgumentException">
        /// Thrown when one or more arguments have unsupported or illegal values.
        /// </exception>
        ///
        /// <param name="parent">
        /// The parent element for this collection.
        /// </param>

        public HTMLOptionsCollection(IDomElement parent)
        {
            if (parent.NodeNameID != HtmlData.tagSELECT)
            {
                throw new ArgumentException("The parent node for an HtmlOptionsCollection must be a SELECT node.");
            }

            Parent = (IHTMLSelectElement)parent;
        }
Exemplo n.º 15
0
        private void SetCurrentStyleSheet(IDomElement <UIElement, PropertyInfo> domElement, StyleSheet styleSheet)
        {
            domElement.StyleInfo.CurrentStyleSheet = styleSheet;
            domElement.StyleInfo.DoMatchCheck      = SelectorType.LogicalTree | SelectorType.VisualTree;

            foreach (var child in domElement.ChildNodes)
            {
                SetCurrentStyleSheet(child, styleSheet);
            }
        }
Exemplo n.º 16
0
        public ElementCollectionBase(IDomElement <TDependencyObject> node, ITreeNodeProvider <TDependencyObject> treeNodeProvider)
        {
            this.treeNodeProvider = treeNodeProvider;

            var children = GetChildren(node.Element)
                           .Select(x => CreateElement(x, node))
                           .ToList();

            this.AddRange(children);
        }
        public virtual void RemoveValue()
        {
            IDomElement         domElement    = DomElement;
            IList <IDomElement> childElements = domElement.ChildElements;

            foreach (IDomElement childElement in childElements)
            {
                domElement.RemoveChild(childElement);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Sets a child text for this element, using the text node type appropriate for this element's type
        /// </summary>
        ///
        /// <param name="el">
        /// The element to add text to
        /// </param>
        /// <param name="text">
        /// The text.
        /// </param>

        private void SetChildText(IDomElement el, string text)
        {
            if (el.ChildrenAllowed)
            {
                el.ChildNodes.Clear();

                IDomText textEl = new DomText(text);
                el.ChildNodes.Add(textEl);
            }
        }
Exemplo n.º 19
0
        public void MatchesSizzleSelect()
        {
            var opt = document.GetElementById("option1a");

            opt.SetAttribute("test", "");

            Assert.IsTrue(match(opt, "[id*=option1][type!=checkbox]"), "Attribute Is Not Equal Matches");
            Assert.IsTrue(match(opt, "[id*=option1]"), "Attribute With No Quotes Contains Matches");
            Assert.IsTrue(match(opt, "[test=]"), "Attribute With No Quotes No Content Matches");
            Assert.IsTrue(!match(opt, "[test^='']"), "Attribute with empty string value does not match startsWith selector (^=)");
            Assert.IsTrue(match(opt, "[id=option1a]"), "Attribute With No Quotes Equals Matches");
            Assert.IsTrue(match(document.GetElementById("simon1"), "a[href*=#]"), "Attribute With No Quotes Href Contains Matches");

            t("Empty values", "#select1 option[value='']", Arrays.String("option1a"));
            t("Empty values", "#select1 option[value!='']", Arrays.String("option1b", "option1c", "option1d"));

            t("Select options via :selected", "#select1 option:selected", Arrays.String("option1a"));
            t("Select options via :selected", "#select2 option:selected", Arrays.String("option2d"));
            t("Select options via :selected", "#select3 option:selected", Arrays.String("option3b", "option3c"));

            t("Grouped Form Elements", "input[name='foo[bar]']", Arrays.String("hidden2"));

            //Uncomment if the boolHook is removed
            // [CsQuery] checked should match the selector after checked is set to true

            IDomElement check2 = document.GetElementById("check2");

            check2.Checked = true;
            // the sizzle test said assert.AreNotEqual
            Assert.IsTrue(match(check2, "[checked]"), "Dynamic boolean attributes match when they should with Sizzle.matches (#11115)");

            //Make sure attribute value quoting works correctly. See: #6093

            var attrbad = jQuery("<input type=\"hidden\" value=\"2\" name=\"foo.baz\" id=\"attrbad1\"/><input type=\"hidden\" value=\"2\" name=\"foo[baz]\" id=\"attrbad2\"/>")
                          .AppendTo("body");

            t("Find escaped attribute value", "input[name=foo\\.baz]", Arrays.String("attrbad1"));
            t("Find escaped attribute value", "input[name=foo\\[baz\\]]", Arrays.String("attrbad2"));

            t("input[type=text]", "#form input[type=text]", Arrays.String("text1", "text2", "hidden2", "name"));
            t("input[type=search]", "#form input[type=search]", Arrays.String("search"));

            attrbad.Remove();

            //   #6428
            t("Find escaped attribute value", "#form input[name=foo\\[bar\\]]", Arrays.String("hidden2"));

            //#3279
            var div = document.CreateElement("div");

            div.InnerHTML = "<div id='foo' xml:test='something'></div>";

            CollectionAssert.AreEqual(Sizzle["[xml\\:test]", div], Arrays.Create <IDomObject>(div.FirstChild), "Finding by attribute with escaped characters.");
            div = null;
        }
 public static BindingPropertyBinderAction CreateBinderAction(string actionType, IDomElement parentElement, string selector, string attribute)
 {
     if (attribute == null)
     {
         return Activator.CreateInstance(Assembly.GetCallingAssembly().GetType("actionType"), new object[] { parentElement, selector }) as BindingPropertyBinderAction;
     }
     else
     {
         return Activator.CreateInstance(Assembly.GetCallingAssembly().GetType("actionType"), new object[] { parentElement, selector, attribute }) as BindingPropertyBinderAction;
     }
 }
 public void SetDomElement(BindableObject obj, IDomElement <BindableObject> value, SelectorType selectorType)
 {
     if (selectorType == SelectorType.LogicalTree)
     {
         Css.SetDomElement(obj, value);
     }
     else
     {
         Css.SetDomElement(obj, value);
     }
 }
 public static BindingPropertyBinderAction CreateBinderAction(Type actionType, IDomElement parentElement, string selector, string attribute)
 {
     if (attribute == null)
     {
         return Activator.CreateInstance(actionType, new object[] { parentElement, selector }) as BindingPropertyBinderAction;
     }
     else
     {
         return Activator.CreateInstance(actionType, new object[] { parentElement, selector, attribute }) as BindingPropertyBinderAction;
     }
 }
Exemplo n.º 23
0
 public override bool IsCorrectTreeNode(IDomElement <DependencyObject> node)
 {
     if (selectorType == SelectorType.LogicalTree)
     {
         return(logicalTreeNodeProvider.IsCorrectTreeNode(node));
     }
     else
     {
         return(visualTreeNodeProvider.IsCorrectTreeNode(node));
     }
 }
Exemplo n.º 24
0
 /// <summary>
 /// Determine if an element matches a position-type filter
 /// </summary>
 /// <param name="elm"></param>
 /// <param name="selector"></param>
 /// <returns></returns>
 protected IEnumerable <IDomObject> GetDomPositionMatches(IDomElement elm, Selector selector)
 {
     if (selector.PositionType == PositionType.NthChild)
     {
         return(NthChildMatcher.GetMatchingChildren(elm, selector.Criteria));
     }
     else
     {
         return(GetSimpleDomPostionMatches(elm, selector.PositionType));
     }
 }
 public void SetDomElement(DependencyObject obj, IDomElement <DependencyObject> value, SelectorType selectorType)
 {
     if (selectorType == SelectorType.LogicalTree)
     {
         Css.SetDomElement(obj, value);
     }
     else
     {
         Css.SetVisualDomElement(obj, value);
     }
 }
Exemplo n.º 26
0
        /// <summary>
        /// Enumerates only the IDomElements in the sequence provided. Any other elemnent types are excluded..
        /// </summary>
        ///
        /// <param name="objects">
        /// The objects.
        /// </param>
        ///
        /// <returns>
        /// An enumerator that allows foreach to be used to process only elements in this collection.
        /// </returns>

        protected IEnumerable <IDomElement> OnlyElements(IEnumerable <IDomObject> objects)
        {
            foreach (var item in objects)
            {
                IDomElement el = item as IDomElement;
                if (el != null)
                {
                    yield return(el);
                }
            }
        }
Exemplo n.º 27
0
        private StyleSheet GetStyleSheet(IDomElement <TDependencyObject> domElement)
        {
            var element = GetStyleSheetHolder(domElement)?.Element;

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

            return(dependencyPropertyService.GetStyleSheet(element));
        }
Exemplo n.º 28
0
        public override MatchResult Match <TDependencyObject>(StyleSheet styleSheet, ref IDomElement <TDependencyObject> domElement, SelectorMatcher[] fragments, ref int currentIndex)
        {
            if (initializedWith != styleSheet)
            {
                Initialize(styleSheet);
            }

            var isMatch = domElement.TagName == TagName && (Alias == "*" || domElement.AssemblyQualifiedNamespaceName == NamespaceUri);

            return(isMatch ? MatchResult.Success : MatchResult.ItemFailed);
        }
 protected internal override bool IsCorrectTreeNode(IDomElement <DependencyObject> node)
 {
     if (currentSelectorType == SelectorType.LogicalTree)
     {
         return(logicalTreeNodeProvider.IsCorrectTreeNode(node));
     }
     else
     {
         return(visualTreeNodeProvider.IsCorrectTreeNode(node));
     }
 }
Exemplo n.º 30
0
        //TODO 入口 IModelElementInstance解析
        /// <summary>
        /// Returns the <seealso cref="ModelElementInstanceImpl ModelElement"/> for a DOM element.
        /// If the model element does not yet exist, it is created and linked to the DOM.
        /// </summary>
        /// <param name="domElement"> the child element to create a new <seealso cref="ModelElementInstanceImpl ModelElement"/> for </param>
        /// <returns> the child model element </returns>
        public static IModelElementInstance GetModelElement(IDomElement domElement, IModelInstance modelInstance)
        {
            IModelElementInstance modelElement = domElement.ModelElementInstance;

            if (modelElement == null)
            {
                IModelElementType modelType = GetModelElement(domElement, modelInstance, domElement.NamespaceUri);
                modelElement = ((ModelElementTypeImpl)modelType).NewInstance(modelInstance, domElement);
                domElement.ModelElementInstance = modelElement;
            }
            return(modelElement);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Insert content, specified by the parameter, to the end of each element in the set of matched
        /// elements.
        /// </summary>
        ///
        /// <param name="func">
        /// A delegate to a function that returns an IDomElement to insert at the end of each element in
        /// the set of matched elements. Receives the index position of the element in the set and the
        /// old HTML value of the element as arguments. Within the function, this refers to the current
        /// element in the set.
        /// </param>
        ///
        /// <returns>
        /// The current CQ object.
        /// </returns>
        ///
        /// <url>
        /// http://api.jquery.com/append/
        /// </url>

        public CQ Append(Func <int, string, IDomElement> func)
        {
            int index = 0;

            foreach (IDomElement obj in Elements)
            {
                IDomElement clientValue = func(index, obj.InnerHTML);
                obj.Cq().Append(clientValue);
                index++;
            }
            return(this);
        }
Exemplo n.º 32
0
        private IDomElement <TDependencyObject> GetStyleSheetHolder(IDomElement <TDependencyObject> domElement)
        {
            var current = domElement;

            while (current != null &&
                   dependencyPropertyService.GetStyleSheet(current.Element) == null)
            {
                current = current.Parent;
            }

            return(current);
        }
Exemplo n.º 33
0
        private static StyleUpdateInfo GetNewStyleUpdateInfo(IDomElement <TDependencyObject, TDependencyProperty> domElement,
                                                             IDependencyPropertyService <TDependencyObject, TStyle, TDependencyProperty> dependencyPropertyService,
                                                             INativeStyleService <TStyle, TDependencyObject, TDependencyProperty> nativeStyleService)
        {
            var initialStyle = nativeStyleService.GetStyle(domElement.Element);

            return(new StyleUpdateInfo
            {
                MatchedType = domElement.Element.GetType(),
                InitialStyle = initialStyle
            });
        }
Exemplo n.º 34
0
        private void Visit(IDomElement element, UserDefinedClass currentClass, bool isNew, bool isRoot, bool metaExists)
        {
            if (element.HasElements) // if element has child elements
            {
                if (!isRoot) // if this is not the root element
                {
                    var property = element.CreateProperty(_repository);
                    currentClass.AddProperty(property, isNew, metaExists);
                }

                currentClass = _repository.GetOrAdd(element.GetDomPath(_factory), out isNew);
                isRoot = element.ActsAsRootElement;

                foreach (var childElement in element.Elements)
                {
                    Visit(childElement, currentClass, isNew, isRoot, metaExists);
                }

                foreach (var orphanedProperty in
                        currentClass.Properties.Where(
                            property => metaExists && !element.ActsAsRootElement && element.Elements.All(childElement => !property.DomPath.Equals(childElement.GetDomPath(_factory)))))
                {
                    // If there's a property that exists, but isn't present in our element's children, it should be nullable.
                    orphanedProperty.MakeNullable();
                }
            }
            else // if element has no child elements
            {
                if (isRoot) // if this is the root element
                {
                    // Make sure a class exists for the root element, no matter what.
                    _repository.GetOrAdd(element.GetDomPath(_factory));
                }
                else
                {
                    var property = element.CreateProperty(_repository);
                    currentClass.AddProperty(property, isNew, metaExists);
                }

                if (metaExists)
                {
                    // If we're refining, and this element has no children, there is a
                    // possibility that it had previous contained children. Make those
                    // children nullable.
                    currentClass = _repository.GetOrAdd(element.GetDomPath(_factory));
                    foreach (var property in currentClass.Properties)
                    {
                        property.MakeNullable();
                    }
                }
            }
        }
Exemplo n.º 35
0
        private void Visit(IDomElement element, UserDefinedClass currentClass, bool isNew, bool isRoot, bool metaExists)
        {
            if (element.HasElements) // if element has child elements
            {
                if (!isRoot)         // if this is not the root element
                {
                    var property = element.CreateProperty(_repository);
                    currentClass.AddProperty(property, isNew, metaExists);
                }

                currentClass = _repository.GetOrAdd(element.GetDomPath(_factory), out isNew);
                isRoot       = element.ActsAsRootElement;

                foreach (var childElement in element.Elements)
                {
                    Visit(childElement, currentClass, isNew, isRoot, metaExists);
                }

                foreach (var orphanedProperty in
                         currentClass.Properties.Where(
                             property => metaExists && !element.ActsAsRootElement && element.Elements.All(childElement => !property.DomPath.Equals(childElement.GetDomPath(_factory)))))
                {
                    // If there's a property that exists, but isn't present in our element's children, it should be nullable.
                    orphanedProperty.MakeNullable();
                }
            }
            else // if element has no child elements
            {
                if (isRoot) // if this is the root element
                {
                    // Make sure a class exists for the root element, no matter what.
                    _repository.GetOrAdd(element.GetDomPath(_factory));
                }
                else
                {
                    var property = element.CreateProperty(_repository);
                    currentClass.AddProperty(property, isNew, metaExists);
                }

                if (metaExists)
                {
                    // If we're refining, and this element has no children, there is a
                    // possibility that it had previous contained children. Make those
                    // children nullable.
                    currentClass = _repository.GetOrAdd(element.GetDomPath(_factory));
                    foreach (var property in currentClass.Properties)
                    {
                        property.MakeNullable();
                    }
                }
            }
        }
Exemplo n.º 36
0
        private StyleSheet GetStyleSheetFromTree(IDomElement <TDependencyObject, TDependencyProperty> domElement)
        {
            var        current    = domElement;
            StyleSheet styleSheet = null;

            while (current != null &&
                   (styleSheet = dependencyPropertyService.GetStyleSheet(current.Element)) == null)
            {
                current = current.Parent;
            }

            return(styleSheet);
        }
Exemplo n.º 37
0
        public override MatchResult Match <TDependencyObject>(StyleSheet styleSheet, ref IDomElement <TDependencyObject> domElement, SelectorMatcher[] fragments, ref int currentIndex)
        {
            if (string.IsNullOrWhiteSpace(Text))
            {
                return(MatchResult.ItemFailed);
            }

            var thisPosition = domElement.Parent?.ChildNodes.IndexOf(domElement) ?? -1;

            thisPosition++;

            return(CalcIsNth(factor, distance, ref thisPosition) ? MatchResult.Success : MatchResult.ItemFailed);
        }
Exemplo n.º 38
0
        public TwitterWall(string screenName, int maxItems)
        {
            _screenName = screenName;
            _maxItems = maxItems;
            _tweets = new List<ISearchResultTweet>();
            _index = new Dictionary<int, ISearchResultTweet>();
            _container = DomManager.Document.GetElementById("twitter-wall-container");

            _toMeSearchParameters = "&callback=" + ToMeCallback + "&count=" + maxItems;
            _toMeSearchUrl = SearchUrl + "?q=to:" + _screenName + _toMeSearchParameters;

            _fromMeSearchParameters = "&callback=" + FromMeCallback + "&count=" + maxItems;
            _fromMeSearchUrl = SearchUrl + "?q=from:" + _screenName + _fromMeSearchParameters;
        }
        /// <summary>
        /// Returns the form data of the provided form.
        /// </summary>
        /// <param name="form">The form.</param>
        /// <param name="submitter">The validated submitter element.</param>
        /// <param name="implicitSubmission">
        /// Whether or not to use implicit submission. Implicit submission takes precedence over
        /// the provided submitter.
        /// </param>
        /// <returns>A lazy list of form field data.</returns>
        public static IEnumerable<NameValueType> GetNameValueTypes(IHTMLFormElement form, IDomElement submitter, bool implicitSubmission)
        {
            // ensure the submitter node is valid
            if (submitter != null && !IsValidSubmitter(form, submitter))
            {
                throw new ArgumentException("The provided submitter node is not a button or does not belong to the provided form.");
            }

            // find the first valid submitter if we are doing implicit submission
            if (implicitSubmission)
            {
                submitter = form
                    .Document
                    .GetDescendentElements()
                    .FirstOrDefault(e => IsValidSubmitter(form, e));
            }

            return GetNameValueTypes(form, submitter).ToArray();
        }
        /// <summary>
        /// Returns the form data of the provided form.
        /// </summary>
        /// <param name="form">The form.</param>
        /// <param name="submitter">The validated submitter element.</param>
        /// <returns>A lazy list of form field data.</returns>
        private static IEnumerable<NameValueType> GetNameValueTypes(IHTMLFormElement form, IDomElement submitter)
        {
            // walk the form fields
            foreach (IDomElement e in form.Document.GetDescendentElements().Where(e => !IsExcludedFromDataSet(form, e, submitter)))
            {
                // TODO: handle dirname
                // TODO: handle file uploads
                // TODO: handle plugin objects
                // TODO: handle keygen

                if (e is IHTMLInputElement && e.Type == "image")
                {
                    string name = e.GetAttribute("name", string.Empty);
                    if (name != string.Empty)
                    {
                        name += ".";
                    }

                    yield return new NameValueType(name + "x", "0", e.Type);
                    yield return new NameValueType(name + "y", "0", e.Type);
                }
                else if (e is IHTMLSelectElement)
                {
                    foreach (NameValueType pair in GetOptionKeyValueTuples(e as IHTMLSelectElement))
                    {
                        yield return pair;
                    }
                }
                else if (e is IHTMLInputElement && (e.Type == "checkbox" || e.Type == "radio"))
                {
                    yield return new NameValueType(e.Name, e.GetAttribute("value", "on"), e.Type);
                }
                else if (e is IHTMLTextAreaElement)
                {
                    // TODO: handle textarea properly
                    yield return new NameValueType(e.Name, WebUtility.HtmlDecode(e.Value), e.Type);
                }
                else
                {
                    yield return new NameValueType(e.Name, e.GetAttribute("value", string.Empty), e.Type);
                }
            }
        }
Exemplo n.º 41
0
        private void BuildUI()
        {
            _processViewerArea = DomManager.Document.GetElementById("process-viewer-area");
            _mainTable = DomManager.CreateElement("table");
            _mainTable.SetAttribute("cellspacing", "2");
            _mainTable.SetAttribute("cellpadding", "2");

            IDomElement tr = DomManager.CreateElement("tr");
            tr.SetAttribute("valign", "top");

            IDomElement td = DomManager.CreateElement("td");
            IDomElement sipTableHeader = DomManager.CreateElement("span");
            sipTableHeader.InnerHtml = "Processes:<br />----------------------------------------<br />";
            td.AppendChild(sipTableHeader);
            IDomElement sipTable = BuildSIPTable();
            _sipTableBody = DomManager.CreateElement("tbody");
            sipTable.AppendChild(_sipTableBody);
            td.AppendChild(sipTable);
            tr.AppendChild(td);

            td = DomManager.CreateElement("td");
            IDomElement threadTableHeader = DomManager.CreateElement("span");
            threadTableHeader.InnerHtml = "Threads:<br />---------------------------------------------------------------<br />";
            td.AppendChild(threadTableHeader);
            IDomElement threadTable = BuildThreadTable();
            _threadTableBody = DomManager.CreateElement("tbody");
            threadTable.AppendChild(_threadTableBody);
            td.AppendChild(threadTable);
            tr.AppendChild(td);

            _mainTable.AppendChild(tr);

            _processViewerArea.AppendChild(DomManager.CreateElement("br"));

            _lastUpdatedElement = DomManager.CreateElement("span");
            _processViewerArea.AppendChild(_lastUpdatedElement);

            _processViewerArea.AppendChild(DomManager.CreateElement("br"));

            _processViewerArea.AppendChild(_mainTable);
        }
Exemplo n.º 42
0
        public IEnumerable<IDomObject> GetMatchingChildren(IDomElement obj)
        {
            if (!obj.HasChildren)
            {
                yield break;
            }
            else if (IsJustNumber)
            {
                int index = 1;
                IDomElement child = obj.FirstChild.NodeType == NodeType.ELEMENT_NODE ?
                    (IDomElement)obj.FirstChild :
                    obj.FirstChild.NextElementSibling;

                while (index++ < MatchOnlyIndex && child != null)
                {
                    child = child.NextElementSibling;
                }
                if (child != null)
                {
                    yield return child;
                }
                else
                {
                    yield break;
                }
            }
            else
            {

                int index = 1;
                UpdateCacheInfo(obj.ChildNodes.Count);
                foreach (var child in obj.ChildElements)
                {
                    if (cacheInfo.MatchingIndices.Contains(index))
                    {
                        yield return child;
                    }
                    index++;
                }
            }
        }
Exemplo n.º 43
0
        /// <summary>
        /// Test whether a single element matches a specific attribute selector.
        /// </summary>
        ///
        /// <param name="element">
        /// The element to test.
        /// </param>
        /// <param name="selector">
        /// The selector.
        /// </param>
        ///
        /// <returns>
        /// true if the element matches, false if not.
        /// </returns>

        public static bool Matches(IDomElement element, SelectorClause selector)
        {

            string value;
            bool match = ((DomElement)element).TryGetAttributeForMatching(selector.AttributeNameTokenID,out value);

            if (!match)
            {
                switch (selector.AttributeSelectorType)
                {
                    case AttributeSelectorType.Exists:
                        return false;
                    case AttributeSelectorType.NotEquals:
                    case AttributeSelectorType.NotExists:
                        return true;
                    default:
                        return false;
                }
            }
            else
            {
               // bool isCaseSensitive = HtmlData.
                switch (selector.AttributeSelectorType)
                {
                    case AttributeSelectorType.Exists:
                        return true;
                    case AttributeSelectorType.Equals:
                        return selector.AttributeValue.Equals(value,selector.AttributeValueStringComparison);

                    case AttributeSelectorType.StartsWith:
                        return value != null &&
                            value.Length >= selector.AttributeValue.Length &&
                            value.Substring(0, selector.AttributeValue.Length)
                                .Equals(selector.AttributeValue, selector.AttributeValueStringComparison);

                    case AttributeSelectorType.Contains:
                        return value != null && value.IndexOf(selector.AttributeValue,
                            selector.AttributeValueStringComparison)>=0;

                    case AttributeSelectorType.ContainsWord:
                        return value != null && ContainsWord(value, selector.AttributeValue, 
                                                           selector.AttributeValueStringComparer);

                    case AttributeSelectorType.NotEquals:
                        return !selector.AttributeValue
                                .Equals(value, selector.AttributeValueStringComparison);

                    case AttributeSelectorType.NotExists:
                        return false;

                    case AttributeSelectorType.EndsWith:
                        int len = selector.AttributeValue.Length;
                        return value != null && value.Length >= len &&
                            value.Substring(value.Length - len)
                                .Equals(selector.AttributeValue, 
                                        selector.AttributeValueStringComparison);

                    case AttributeSelectorType.StartsWithOrHyphen:
                        if (value == null)
                        {
                            return false;
                        }
                        int dashPos = value.IndexOf("-");
                        string beforeDash = value;

                        if (dashPos >= 0)
                        {
                            // match a dash that's included in the match attribute according to common browser behavior
                            beforeDash = value.Substring(0, dashPos);
                        }

                        return selector.AttributeValue.Equals(beforeDash,selector.AttributeValueStringComparison) || 
                            selector.AttributeValue.Equals(value,selector.AttributeValueStringComparison);

                    default:
                        throw new InvalidOperationException("No AttributeSelectorType set");

                }

            }
        }
Exemplo n.º 44
0
 private bool HasRelNoFollow(IDomElement e)
 {
     return _isRespectAnchorRelNoFollowEnabled && (e.HasAttribute("rel") && e.GetAttribute("rel").ToLower().Trim() == "nofollow");
 }
Exemplo n.º 45
0
        /// <summary>
        /// Constructor.
        /// </summary>
        ///
        /// <param name="ownerNode">
        /// The node that owns this item.
        /// </param>

        public CSSStyleSheet(IDomElement ownerNode)
        {
            OwnerNode = ownerNode;
        }
        /// <summary>
        /// Determines whether an element is excluded from a form data set.
        /// </summary>
        /// <param name="form"></param>
        /// <param name="e"></param>
        /// <param name="submitter"></param>
        /// <returns></returns>
        private static bool IsExcludedFromDataSet(IHTMLFormElement form, IDomElement e, IDomElement submitter)
        {
            var submittable = e as IFormSubmittableElement;
            if (submittable == null || submittable.Form != form)
            {
                return true;
            }

            return (e.GetAncestors().Any(a => a.NodeName == "DATALIST")) ||
                   (e.Disabled) ||
                   (IsButton(e) && e != submitter) ||
                   (e is IHTMLInputElement && e.Type == "checkbox" && !e.Checked) ||
                   (e is IHTMLInputElement && e.Type == "radio" && !e.Checked) ||
                   (e.Name.IsNullOrEmpty() && !(e is IHTMLInputElement && e.Type == "image")) ||
                   (e.NodeName == "OBJECT");
        }
Exemplo n.º 47
0
        /// <summary>
        /// Return true if an element matches a specific filter.
        /// </summary>
        ///
        /// <param name="element">
        /// The element to test
        /// </param>
        /// <param name="selector">
        /// A selector clause
        /// </param>
        ///
        /// <returns>
        /// true if matches pseudo class, false if not.matches the selector, false if not
        /// </returns>

        protected bool MatchesPseudoClass(IDomElement element, SelectorClause selector)
        {
            return ((IPseudoSelectorChild)selector.PseudoSelector).Matches(element);       
        }
Exemplo n.º 48
0
        /// <summary>
        /// Ouptuts the deepest-nested object, it's root element from the list of elements passed, and
        /// returns the depth, given a structure. Helper method for Wrap.
        /// </summary>
        ///
        /// <param name="elements">
        /// The sequence to analyze
        /// </param>
        /// <param name="element">
        /// [ouy] The innermost element container
        /// </param>
        /// <param name="rootElement">
        /// [out] The root element.
        /// </param>
        ///
        /// <returns>
        /// The innermost container.
        /// </returns>

        protected int GetInnermostContainer(IEnumerable<IDomElement> elements,
            out IDomElement element,
            out IDomElement rootElement)
        {
            int depth = 0;
            element = null;
            rootElement = null;
            foreach (IDomElement el in elements)
            {
                if (el.HasChildren)
                {
                    IDomElement innerEl;
                    IDomElement root;
                    int innerDepth = GetInnermostContainer(el.ChildElements,
                        out innerEl,
                        out root);
                    if (innerDepth > depth)
                    {
                        depth = innerDepth + 1;
                        element = innerEl;
                        rootElement = el;
                    }
                }
                if (depth == 0)
                {
                    depth = 1;
                    element = el;
                    rootElement = el;
                }
            }
            return depth;
        }
Exemplo n.º 49
0
        /// <summary>
        /// Implementation for Children. The bool part of the tuple indicates if the element inherits a
        /// "disabled" property.
        /// </summary>
        ///
        /// <param name="parent">
        /// The parent element for this collection.
        /// </param>
        ///
        /// <returns>
        /// An enumerator that allows foreach to be used to process children in this collection.
        /// </returns>

        private IEnumerable<OptionElement> Children(IDomElement parent)
        {
            return Children(parent, false);
        }
        public ValuePropertyBinderAction(IDomElement parentElement, string selector) : base(parentElement, selector)
        {

        }
Exemplo n.º 51
0
 protected virtual bool HasRelNoFollow(IDomElement e)
 {
     return _config.IsRespectAnchorRelNoFollowEnabled && (e.HasAttribute("rel") && e.GetAttribute("rel").ToLower().Trim() == "nofollow");
 }
Exemplo n.º 52
0
        /// <summary>
        /// Return true if an object matches a specific selector. If the selector has a desecendant or child traversal type, it must also
        /// match the specificed depth.
        /// </summary>
        /// <param name="selector">The jQuery/CSS selector</param>
        /// <param name="obj">The target object</param>
        /// <param name="depth">The depth at which the target must appear for descendant or child selectors</param>
        /// <returns></returns>
        protected bool Matches(SelectorClause selector, IDomElement obj, int depth)
        {
            switch (selector.TraversalType)
            {
                case TraversalType.Child:
                    if (selector.ChildDepth != depth)
                    {
                        return false;
                    }
                    break;
                case TraversalType.Descendent:
                    // Special case because this code is jacked up: when only "AttributeValue" it's ALWAYS a filter, it means
                    // the AttributeExists was handled previously by the index.

                    // This engine at some point should be reworked so that the "And" combinator is just a subselector, this logic has 
                    // become too brittle.

                    if (depth == 0)
                    {
                        return false;
                    }
                    break;
            }

            if (selector.SelectorType.HasFlag(SelectorType.All))
            {
                return true;
            }

            if (selector.SelectorType.HasFlag(SelectorType.PseudoClass))
            {
                return MatchesPseudoClass(obj, selector);
            }

            if (obj.NodeType != NodeType.ELEMENT_NODE)
            {
                return false;
            }
            
            // Check each selector from easier/more specific to harder. e.g. ID is going to eliminate a lot of things.

            if (selector.SelectorType.HasFlag(SelectorType.ID) &&
                selector.ID != obj.Id)
            {
                return false;
            }
            if (selector.SelectorType.HasFlag(SelectorType.Class) &&
                !obj.HasClass(selector.Class))
            {
                return false;
            }

            if (selector.SelectorType.HasFlag(SelectorType.Tag) &&
                !String.Equals(obj.NodeName, selector.Tag, StringComparison.CurrentCultureIgnoreCase))
            {
                return false;
            }

            
            if ((selector.SelectorType & SelectorType.AttributeValue)>0)
            {
                return AttributeSelectors.Matches((IDomElement)obj,selector);
            }

            if (selector.SelectorType == SelectorType.None)
            {
                return false;
            }

            return true;
        }
Exemplo n.º 53
0
 public void Visit(IDomElement element, bool metaExists)
 {
     bool isNew;
     _repository.GetOrAdd(element.GetDomPath(_factory), out isNew);
     Visit(element, null, isNew, true, metaExists);
 }
Exemplo n.º 54
0
        /// <summary>
        /// Return all child elements matching a DOM-position type selector
        /// </summary>
        /// <param name="elm"></param>
        /// <param name="selector"></param>
        /// <returns></returns>
        protected IEnumerable<IDomObject> GetPseudoClassMatches(IDomElement elm, SelectorClause selector)
        {
            IEnumerable<IDomObject> results;
           
            results = ((IPseudoSelectorChild)selector.PseudoSelector).ChildMatches(elm);

            foreach (var item in results)
            {
                yield return item;
            }

            // Traverse children if needed

            if (selector.TraversalType == TraversalType.Descendent || 
                selector.TraversalType == TraversalType.All)
            {
                foreach (var child in elm.ChildElements)
                {
                    foreach (var item in GetPseudoClassMatches(child, selector))
                    {
                        yield return item;
                    }
                }
            }
          
        }    
Exemplo n.º 55
0
        private static bool TryLoadDocument(string arg, IFactory factory, out IDomElement domElement, out DocumentType documentType)
        {
            try
            {
                var xDocument = XDocument.Load(arg);
                domElement = factory.CreateXmlDomElement(xDocument.Root);
                documentType = DocumentType.Xml;
                return true;
            }
            catch
            {
                try
                {
                    JToken jToken;
                    using (var streamReader = new StreamReader(arg))
                    {
                        using (var jsonReader = new JsonTextReader(streamReader))
                        {
                            jToken = JToken.Load(jsonReader);
                        }
                    }

                    domElement = factory.CreateJsonDomElement(jToken);
                    documentType = DocumentType.Json;
                    return true;
                }
                catch
                {
                    domElement = null;
                    documentType = DocumentType.Invalid;
                    return false;
                }
            }
        }
        /// <summary>
        /// Determines whether the provided element is a valid submitter of the provided form.
        /// </summary>
        /// <param name="form">The form to test.</param>
        /// <param name="e">The element to test.</param>
        /// <returns>True if the provided element is a valid submitter of the provided for. False otherwise.</returns>
        private static bool IsValidSubmitter(IHTMLFormElement form, IDomElement e)
        {
            var formElement = e as IFormSubmittableElement;
            if (formElement != null)
            {
                return IsButton(e) && formElement.Form == form;
            }

            return false;
        }
Exemplo n.º 57
0
        private IEnumerable<OptionElement> Children(IDomElement parent, bool disabled)
        {
            foreach (var item in parent.ChildElements)
            {
                switch (item.NodeNameID)
                {
                    case HtmlData.tagOPTION:
                        yield return new OptionElement
                        {
                            Element = (DomElement)item,
                            Disabled = disabled || item.HasAttribute("disabled")
                        };
                        break;

                    case HtmlData.tagOPTGROUP:
                        foreach (var child in Children(item, disabled || item.HasAttribute("disabled")))
                        {
                            yield return child;
                        }
                        break;
                }
            }
        }
Exemplo n.º 58
0
 private static bool TryParseDocument(string arg, IFactory factory, out IDomElement domElement, out DocumentType documentType)
 {
     try
     {
         var xDocument = XDocument.Parse(arg);
         domElement = factory.CreateXmlDomElement(xDocument.Root);
         documentType = DocumentType.Xml;
         return true;
     }
     catch
     {
         try
         {
             var jToken = JToken.Parse(arg);
             domElement = factory.CreateJsonDomElement(jToken);
             documentType = DocumentType.Json;
             return true;
         }
         catch
         {
             domElement = null;
             documentType = DocumentType.Invalid;
             return false;
         }
     }
 }
Exemplo n.º 59
0
 protected string WriteDOMObject(IDomElement obj)
 {
     string result = "";
     foreach (var kvp in obj.Attributes)
     {
         if (kvp.Value != null)
         {
             result += kvp.Key + "=" + kvp.Value + ",";
         }
         else
         {
             result += kvp.Value + ",";
         }
     }
     result += "InnerHtml=" + obj.InnerHTML;
     return result;
 }
Exemplo n.º 60
0
 /// <summary>
 /// Deals with tbody as the target of appends
 /// </summary>
 /// <param name="apparentTarget"></param>
 /// <returns></returns>
 protected IDomElement getTrueTarget(IDomElement target)
 {
     //Special handling for tables: make sure we add to the TBODY
     IDomElement element = target;
     if (target.NodeName == "table")
     {
         bool addBody = false;
         if (target.HasChildren)
         {
             IDomElement body = target.ChildElements.FirstOrDefault(item => item.NodeName == "tbody");
             if (body != null) {
                 element = body;
             }
             else if (target.FirstElementChild == null)
             {
                 // Add a body if there are no elements in this table yet
                 addBody = true;
             }
             // default = leave it alone, they've already added elements. don't worry whether it's valid or not,
             // assume they know what they're doing.
         }
         else
         {
             addBody = true;
         }
         if (addBody)
         {
             element = Document.CreateElement("tbody");
             target.AppendChild(element);
         }
     }
     return element;
 }