public static string EnsurePrefixRegistrationOfNamespace([NotNull] this XElement element,
                                                                 [NotNull] XNamespace @namespace)
        {
            if (element == null)
            {
                throw new ArgumentNullException(nameof(element));
            }
            if (@namespace == null)
            {
                throw new ArgumentNullException(nameof(@namespace));
            }

            string result;

            if (@namespace.Equals(XNamespace.None))
            {
                result = null;
            }
            else
            {
                var document = element.Document;

                result = document.Root.GetPrefixOfNamespace(@namespace);
                if (result == null)
                {
                    result = document.Root.FindUnusedPrefixForNamespace();

                    document.Root.SetAttributeValue(XNamespace.Xmlns + result,
                                                    @namespace);
                }
            }

            return(result);
        }
예제 #2
0
        public void NamespaceOperators()
        {
            // Implicit conversion from string.
            XNamespace ns = (XNamespace)(string)null;

            Assert.Null(ns);

            ns = (XNamespace)"foo";
            Assert.Equal("foo", ns.NamespaceName);

            // Operator +
            XName name;

            Assert.Throws <ArgumentNullException>(() => (XNamespace)null + "localname");
            Assert.Throws <ArgumentNullException>(() => ns + (string)null);

            name = ns + "localname";
            Assert.Equal("localname", name.LocalName);
            Assert.Equal("foo", name.Namespace.NamespaceName);

            // Equality, which should be based on reference equality.
            XNamespace ns1 = (XNamespace)"foo";
            XNamespace ns2 = (XNamespace)"foo";
            XNamespace ns3 = (XNamespace)"bar";
            XNamespace ns4 = null;

            Assert.NotNull(ns1);
            Assert.NotNull(ns2);
            Assert.NotNull(ns3);

            Assert.Same(ns1, ns2);
            Assert.True(ns1.Equals(ns2));

            Assert.NotSame(ns1, ns3);
            Assert.False(ns1.Equals(ns3));

            Assert.NotSame(ns2, ns3);
            Assert.False(ns2.Equals(ns3));

            Assert.True(ns1 == ns2);  // equal
            Assert.False(ns1 == ns3); // not equal
            Assert.False(ns1 == ns4); // not equal

            Assert.False(ns1 != ns2); // false
            Assert.True(ns1 != ns3);  // true
            Assert.True(ns1 != ns4);  // true
        }
예제 #3
0
 public void GetDefaultNamespace(string xml, string defNSString)
 {
     XNamespace defNS = defNSString == null ? null : XNamespace.Get(defNSString);
     XElement e = XElement.Parse(xml);
     XNamespace df = ((XElement)e.LastNode).GetDefaultNamespace();
     Assert.Same(defNS, df);
     Assert.True(defNS.Equals(df));
 }
예제 #4
0
 public void NamespaceForPrefix(string xml, string prefix, string ns)
 {
     XNamespace NS = ns == null ? null : XNamespace.Get(ns);
     XElement e = XElement.Parse(xml);
     XNamespace df = (e.FirstNode as XElement).GetNamespaceOfPrefix(prefix);
     Assert.Same(NS, df);
     if (NS != null)
     {
         Assert.True(NS.Equals(df));
     }
 }
        private static XElement CopyWithoutNamespace(XElement source, XNamespace namespaceToRemove)
        {
            XNamespace sourceNs = source.Name.Namespace;
            XName      newName  = sourceNs.Equals(namespaceToRemove) ? source.Name.LocalName : source.Name;
            XElement   copy     = new XElement(newName);

            if (!sourceNs.Equals(namespaceToRemove) &&
                sourceNs != source.Parent.Name.Namespace &&
                source.Attribute(XName_Xmlns) == null &&
                (sourceNs == Namespaces.Xhtml.NamespaceName || sourceNs == Namespaces.Svg.NamespaceName))
            {
                copy.Add(new XAttribute(XName_Xmlns, source.Name.Namespace));
            }

            copy.Add(source.Attributes().Where(a => a.Name.Namespace == namespaceToRemove)
                     .Select(a => new XAttribute(a.Name.LocalName, a.Value)));

            Func <XAttribute, bool> isNotHtmlRelatedNsDeclaration =
                ns => !ns.IsNamespaceDeclaration ||
                (ns.Value != Namespaces.Xhtml.NamespaceName && ns.Value != Namespaces.Svg.NamespaceName);

            copy.Add(source.Attributes().Where(a => a.Name.Namespace != namespaceToRemove && isNotHtmlRelatedNsDeclaration(a))
                     .Select(a => new XAttribute(a.Name, a.Value)));

            foreach (XNode child in source.Nodes())
            {
                if (child is XElement)
                {
                    copy.Add(CopyWithoutNamespace(child as XElement, namespaceToRemove));
                }
                else
                {
                    copy.Add(child);
                }
            }

            return(copy);
        }
예제 #6
0
        private static void EnsureValidFindPackagesResponse(Stream stream, string uri)
        {
            var message = $"Response from {uri} is not a valid NuGet v2 service response.";

            try
            {
                var xDoc = XDocument.Load(stream);
                if (!_defaultNamespace.Equals(xDoc.Root.Name.Namespace))
                {
                    throw new InvalidDataException(
                              $"{message} Namespace of root element is not {_defaultNamespace.NamespaceName}.");
                }
            }
            catch (XmlException e)
            {
                throw new InvalidDataException(message, innerException: e);
            }
        }
예제 #7
0
파일: Utils.cs 프로젝트: pgovind/runtime
    private static bool CompareXElements(XElement baselineXElement, XElement actualXElement)
    {
        // Check whether the XName is the same, this can be done by comparing the two XNames.

        if (!baselineXElement.Name.Equals(actualXElement.Name))
        {
            // Two nodes could be same even if their localName is not the same.
            // For example-

            // Desktop
            //<GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2zbP0weY4 xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" xmlns="http://schemas.datacontract.org/2004/07/SerializationTypes">
            //  <genericData1 z:Id="i2">
            //    <BaseData></BaseData>
            //    <DerivedData></DerivedData>
            //  </genericData1>
            //  <genericData2 z:Id="i3">
            //    <BaseData></BaseData>
            //    <DerivedData></DerivedData>
            //  </genericData2>
            //</GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2zbP0weY4>

            // vs CoreCLR.
            //<GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2RkuXKXCQ z:Id="i1" xmlns="http://schemas.datacontract.org/2004/07/SerializationTypes" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
            //  <genericData1 z:Id="i2">
            //    <BaseData />
            //    <DerivedData />
            //  </genericData1>
            //  <genericData2 z:Id="i3">
            //    <BaseData />
            //    <DerivedData />
            //  </genericData2>
            //</GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2RkuXKXCQ>

            // Note the incorrect padding in the end of GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2RkuXKXCQ
            // The difference is MD5 hashcode applied to the Type.FullName and is because full typeName in desktop and CoreCLR returns different value.

            // Hack for the above reason.
            int deskIdx, coreCLRIdx;
            if (-1 != (deskIdx = baselineXElement.Name.LocalName.IndexOf("zbP0weY4")))
            {
                // Check if the CoreCLR string contains the other.
                if (-1 != (coreCLRIdx = actualXElement.Name.LocalName.IndexOf("RkuXKXCQ")))
                {
                    // Check whether the substring before this matches
                    if (0 == string.Compare(baselineXElement.Name.LocalName.Substring(0, deskIdx), actualXElement.Name.LocalName.Substring(0, coreCLRIdx)))
                    {
                        // Check if the namespace matched.
                        if (baselineXElement.Name.Namespace.Equals(actualXElement.Name.Namespace))
                        {
                            return(true);
                        }
                    }
                }
            }
            string message = string.Format("Namespace difference \n[expected]:{0}\n[actual  ]:{1}\n Padding expected elements is {2}",
                                           baselineXElement.Name.Namespace,
                                           actualXElement.Name.Namespace,
                                           actualXElement.Name.LocalName
                                           );
            Debug.WriteLine("Either padding is different or namespace is not matching.\n" + message);

            return(false);
        }

        // Comparing attributes
        XAttribute[] deskAtrs    = baselineXElement.Attributes().OrderBy(m => m.Value).ToArray();
        XAttribute[] coreCLRAtrs = actualXElement.Attributes().OrderBy(m => m.Value).ToArray();

        if (deskAtrs.Length != coreCLRAtrs.Length)
        {
            Debug.WriteLine("Number of attributes differ.Expected number of attributes are " + deskAtrs.Length.ToString() + " Actual number of attributes are " + coreCLRAtrs.Length.ToString());
            return(false);
        }

        // At this point the attributes should be all in the same order.
        for (int i = 0; i < deskAtrs.Length; i++)
        {
            if (deskAtrs[i].IsNamespaceDeclaration != coreCLRAtrs[i].IsNamespaceDeclaration)
            {
                Debug.WriteLine("Either expected attribute {0} is not namespace declaration or actual attribute {1}", deskAtrs[i].ToString(), coreCLRAtrs[i].ToString());
                return(false);
            }
            if (deskAtrs[i].IsNamespaceDeclaration)
            {
                if (0 != string.Compare(deskAtrs[i].Name.NamespaceName, coreCLRAtrs[i].Name.NamespaceName))
                {
                    Debug.WriteLine("Namespaces are different.Expected {0} namespace doesn't match with actual {1} namespace ", deskAtrs[i].Name.NamespaceName, coreCLRAtrs[i].Name.NamespaceName);
                    return(false);
                }
                if (0 != string.Compare(deskAtrs[i].Value, coreCLRAtrs[i].Value))
                {
                    Debug.WriteLine("Attribute values are different. Expected {0} attribute values doesn't match with actual {1} attribute value.", deskAtrs[i].Value, coreCLRAtrs[i].Value);
                    return(false);
                }

                // Update the dictionaries
                s_prefixToNamespaceDesk[deskAtrs[i].Name.LocalName]       = deskAtrs[i].Value;
                s_prefixToNamespaceCoreCLR[coreCLRAtrs[i].Name.LocalName] = coreCLRAtrs[i].Value;
            }
            else
            {
                if (!deskAtrs[i].Name.Equals(coreCLRAtrs[i].Name))
                {
                    Debug.WriteLine("Attribute names are different. Expected name is {0} but actual name is {1}", deskAtrs[i].Name, coreCLRAtrs[i].Name);
                    return(false);
                }

                string deskPrefix, coreCLRPrefix;
                if (IsPrefixedAttributeValue(deskAtrs[i].Value, out deskPrefix))
                {
                    if (IsPrefixedAttributeValue(coreCLRAtrs[i].Value, out coreCLRPrefix))
                    {
                        // Check if they both have the same namespace.
                        XNamespace deskns    = baselineXElement.GetNamespaceOfPrefix(deskPrefix);
                        XNamespace coreclrns = actualXElement.GetNamespaceOfPrefix(coreCLRPrefix);
                        if (!deskns.Equals(coreclrns))
                        {
                            Debug.WriteLine("XML namespace of attribute is different. Expected is {0} but actual is {1}", deskns.NamespaceName, coreclrns.NamespaceName);
                            return(false);
                        }
                        // Update the dictionaries
                        s_prefixToNamespaceDesk[deskPrefix]       = deskns.NamespaceName;
                        s_prefixToNamespaceCoreCLR[coreCLRPrefix] = coreclrns.NamespaceName;
                    }
                    else
                    {
                        Debug.WriteLine("Either expected {0} or actual {1} attribute value doesn't have prefix :", deskAtrs[i].Value, coreCLRAtrs[i].Value);
                        return(false);
                    }
                }
            }
        }

        if (!CompareValue(baselineXElement.Value, actualXElement.Value))
        {
            return(false);
        }


        // Serialized values can only have XElement and XText and hence we do not traverse the complete node structures and only the descendants.
        XElement[] deskChildElems    = baselineXElement.Descendants().OrderBy(m => m.Name.NamespaceName).ToArray();
        XElement[] coreCLRChildElems = actualXElement.Descendants().OrderBy(m => m.Name.NamespaceName).ToArray();

        if (deskChildElems.Length != coreCLRChildElems.Length)
        {
            return(false);
        }

        for (int i = 0; i < deskChildElems.Length; i++)
        {
            if (!CompareXElements(deskChildElems[i], coreCLRChildElems[i]))
            {
                return(false);
            }
        }

        // If we have reached here, XML is same.
        return(true);
    }
        private static Dictionary <string, MexPolicy> ReadPolicies(XContainer mexDocument)
        {
            var policies = new Dictionary <string, MexPolicy>();
            IEnumerable <XElement> policyElements = mexDocument.Elements().First().Elements(XmlNamespace.Wsp + "Policy");

            foreach (XElement policy in policyElements)
            {
                XElement exactlyOnePolicy = policy.Elements(XmlNamespace.Wsp + "ExactlyOne").FirstOrDefault();
                if (exactlyOnePolicy == null)
                {
                    continue;
                }

                IEnumerable <XElement> all = exactlyOnePolicy.Descendants(XmlNamespace.Wsp + "All");
                foreach (XElement element in all)
                {
                    XNamespace securityPolicy = XmlNamespace.Sp;
                    XElement   auth           = element.Elements(XmlNamespace.Http + "NegotiateAuthentication").FirstOrDefault();
                    if (auth != null)
                    {
                        AddPolicy(policies, policy, UserAuthType.IntegratedAuth, securityPolicy.Equals(XmlNamespace.Sp2005));
                    }

                    auth = element.Elements(securityPolicy + "SignedEncryptedSupportingTokens").FirstOrDefault();
                    if (auth == null)
                    {
                        //switch to sp2005
                        securityPolicy = XmlNamespace.Sp2005;
                        if ((auth = element.Elements(securityPolicy + "SignedSupportingTokens").FirstOrDefault()) ==
                            null)
                        {
                            continue;
                        }
                    }

                    XElement wspPolicy = auth.Elements(XmlNamespace.Wsp + "Policy").FirstOrDefault();
                    if (wspPolicy == null)
                    {
                        continue;
                    }

                    XElement usernameToken = wspPolicy.Elements(securityPolicy + "UsernameToken").FirstOrDefault();
                    if (usernameToken == null)
                    {
                        continue;
                    }

                    XElement wspPolicy2 = usernameToken.Elements(XmlNamespace.Wsp + "Policy").FirstOrDefault();
                    if (wspPolicy2 == null)
                    {
                        continue;
                    }

                    XElement wssUsernameToken10 = wspPolicy2.Elements(securityPolicy + "WssUsernameToken10").FirstOrDefault();
                    if (wssUsernameToken10 != null)
                    {
                        AddPolicy(policies, policy, UserAuthType.UsernamePassword, securityPolicy.Equals(XmlNamespace.Sp2005));
                    }
                }
            }

            return(policies);
        }