Exemplo n.º 1
0
		public void TestDocUnformatted()
		{
			string docText = @"<doc
				><some
				one=""abc""
				two='123' 
				/></doc
				>";

			XmlLightDocument doc = new XmlLightDocument(docText);

			string content;
			TextWriter sw = new StringWriter();
			doc.WriteUnformatted(sw);
			content = sw.ToString();
			Assert.AreEqual(docText, content);

			using (MemoryStream ms = new MemoryStream())
			{
				sw = new StreamWriter(ms);
				doc.WriteUnformatted(sw);

				sw.Flush();
				ms.Position = 0;
				StreamReader sr = new StreamReader(ms);
				content = sr.ReadToEnd();
				Assert.AreEqual(docText, content);
			}
		}
Exemplo n.º 2
0
        private bool RewriteSearchForm(XmlLightDocument doc)
        {
            if (_config.Searching.FormXPath != null)
            {
                XmlLightElement selectFrom = doc.Root;
                if (_config.Searching.XPathBase != null)
                    selectFrom = selectFrom.SelectRequiredNode(_config.Searching.XPathBase.XPath);

                XmlLightElement found = selectFrom.SelectRequiredNode(_config.Searching.FormXPath.XPath);
                found.Attributes["method"] = "GET";
                found.Attributes["action"] = new Uri(_baseUri, "search/").AbsoluteUri;
                return true;
            }
            return false;
        }
Exemplo n.º 3
0
            private bool RewriteXmlDocument(XmlLightDocument doc)
            {
                foreach (HttpCloneXPath path in _xpaths)
                {
                    foreach (XmlLightElement found in doc.Select(path.XPath))
                    {
                        _elements.Add(found, path);
                    }
                }

                return false;
            }
Exemplo n.º 4
0
            XmlLightElement GetReplacementNode(XmlLightElement e, object key)
            {
                HttpCloneOptimizationReplace replacement = _replaces[key];
                if (String.IsNullOrEmpty(replacement.ReplacementValue))
                    return null;

                string replaceText = replacement.ReplacementValue;
                if (replacement.ExpandValue)
                {
                    replaceText = RegexPatterns.FormatNameSpecifier.Replace(replaceText,
                        m =>
                        {
                            string tmp;
                            if (_namedValues.TryGetValue(m.Groups["field"].Value, out tmp)
                                || e.Attributes.TryGetValue(m.Groups["field"].Value, out tmp))
                                return tmp;
                            return m.Value;
                        });
                }

                XmlLightElement newElem = new XmlLightDocument(replaceText).Root;
                newElem.Parent = null;
                return newElem;
            }
Exemplo n.º 5
0
        public IContentResponse Post(string method, string rawUrl, NameValueCollection headers, Stream inputStream)
        {
            try
            {
                try
                {
                    Assert("POST", method);
                    Assert("application/xml", headers["Content-Type"]);
                    if (int.Parse(headers["Content-Length"]) > 4096)
                        throw new ArgumentException("Content exceeds limit of 4096 bytes.");

                    string xmessage;
                    using (TextReader rdr = new StreamReader(inputStream, Encoding.UTF8, false))
                        xmessage = rdr.ReadToEnd();

                    XmlLightDocument doc = new XmlLightDocument(xmessage);
                    Assert("methodCall", doc.Root.LocalName);
                    Assert("pingback.ping", doc.SelectRequiredNode("/methodCall/methodName").InnerText);
                    XmlLightElement[] args = doc.Select("/methodCall/params/param").ToArray();
                    if (args.Length != 2)
                        throw new ArgumentException("Invalid number of arguments, expected: 2");

                    Uri source, dest;
                    if (!Uri.TryCreate(args[0].InnerText, UriKind.Absolute, out source) ||
                        !Uri.TryCreate(args[1].InnerText, UriKind.Absolute, out dest))
                        throw new ArgumentException("Invalid uri format.");

                    RecordPingback(source, dest);

                    return new DynamicResponse("application/xml",
                        Encoding.UTF8.GetBytes(@"<?xml version=""1.0""?><methodResponse><params><param><value>Accepted</value></param></params></methodResponse>")
                        );
                }
                catch (ArgumentException e)
                {
                    return new DynamicResponse("application/xml",
                        Encoding.UTF8.GetBytes(
                        String.Format(
@"<?xml version=""1.0""?>
<methodResponse>
  <fault>
    <value>
      <struct>
        <member><name>faultCode</name><value><int>{0}</int></value></member>
        <member><name>faultString</name><value><string>{1}</string></value></member>
      </struct>
    </value>
  </fault>
</methodResponse>", 0, HttpUtility.HtmlEncode(e.Message))));
                }
            }
            catch (Exception err)
            {
                Log.Error(err);
                return HttpErrorHandler.InternalServerError.GetResponse(method, rawUrl, headers, inputStream);
            }
        }
        public void ReadFrom(string versionInfo)
        {
            StringWriter asmInfo = new StringWriter();
            asmInfo.WriteLine("using System;");
            asmInfo.WriteLine();

            using (DisposingList disposable = new DisposingList())
            {
                if (versionInfo.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase))
                {
                    string dir = Path.GetDirectoryName(versionInfo);
                    XmlLightDocument proj = new XmlLightDocument(File.ReadAllText(versionInfo));
                    foreach (XmlLightElement xref in proj.Select("/Project/ItemGroup/Compile"))
                    {
                        if (!xref.Attributes.ContainsKey("Include") ||
                            !xref.Attributes["Include"].EndsWith("AssemblyInfo.cs", StringComparison.OrdinalIgnoreCase))
                            continue;
                        string include = xref.Attributes["Include"];
                        versionInfo = Path.Combine(dir, include);
                        break;
                    }
                    if (versionInfo.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase))
                        throw new ApplicationException("Unable to locate AssemblyInfo.cs");
                }
                if (versionInfo.EndsWith(".cs", StringComparison.OrdinalIgnoreCase))
                {
                    _assemblyInfo = File.ReadAllText(versionInfo);

                    TempFile dll = TempFile.FromExtension(".dll");
                    disposable.Add(dll);
                    dll.Delete();

                    CSharpCodeProvider csc = new CSharpCodeProvider();
                    CompilerParameters args = new CompilerParameters();
                    args.GenerateExecutable = false;
                    args.IncludeDebugInformation = false;
                    args.OutputAssembly = dll.TempPath;
                    args.ReferencedAssemblies.Add("System.dll");
                    CompilerResults results = csc.CompileAssemblyFromFile(args, versionInfo);

                    StringWriter sw = new StringWriter();
                    foreach (CompilerError ce in results.Errors)
                    {
                        if (ce.IsWarning) continue;
                        String line = String.Format("{0}({1},{2}): error {3}: {4}", ce.FileName, ce.Line, ce.Column,
                                                    ce.ErrorNumber, ce.ErrorText);
                        Trace.WriteLine(line);
                        sw.WriteLine(line);
                    }
                    string errorText = sw.ToString();
                    if (errorText.Length > 0)
                        throw new ApplicationException(errorText);
                    versionInfo = dll.TempPath;
                }
                if (!File.Exists(versionInfo) || (!versionInfo.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && !versionInfo.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)))
                    throw new ApplicationException("Expected an existing dll: " + versionInfo);

                try
                {
                    Regex truefalse = new Regex(@"(?<=[^\w_\.])(?:True)|(?:False)(?=[^\w_\.])");
                    _fileVersion = FileVersionInfo.GetVersionInfo(versionInfo);

                    if (_assemblyInfo == null)
                    {
                        Assembly asm = Assembly.ReflectionOnlyLoad(File.ReadAllBytes(versionInfo));
                        IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes(asm);
                        foreach (CustomAttributeData data in attrs)
                        {
                            if (!data.ToString().StartsWith("[System.Runtime.CompilerServices."))
                            {
                                string attribute = data.ToString().Trim();
                                if (attribute[0] != '[')
                                    continue; //unexpected...
                                attribute = attribute.Insert(1, "assembly: ");
                                attribute = StringUtils.Transform(attribute, truefalse,
                                                                  delegate(Match x) { return x.Value.ToLower(); });
                                asmInfo.WriteLine(attribute);
                            }
                        }
                    }
                }
                catch
                {
                }
            }

            _assemblyInfo = _assemblyInfo ?? asmInfo.ToString();
        }
Exemplo n.º 7
0
        public static bool SendPingback(Uri source, Uri target, Uri pingbackUri, Action<string> logError, out int errorCode, out string serverMessage)
        {
            HttpRequestUtil http = new HttpRequestUtil(pingbackUri);

            string xmlrpc = @"<?xml version=""1.0""?><methodCall><methodName>pingback.ping</methodName><params>" +
                            @"<param><value><string>{0}</string></value></param>" +
                            @"<param><value><string>{1}</string></value></param></params></methodCall>";

            xmlrpc = String.Format(xmlrpc, HttpUtility.HtmlEncode(source.AbsoluteUri), HttpUtility.HtmlEncode(target.AbsoluteUri));
            byte[] postdata = Encoding.UTF8.GetBytes(xmlrpc);

            if (http.Post(pingbackUri.PathAndQuery, "application/xml", postdata, postdata.Length) != HttpStatusCode.OK)
            {
                logError(String.Format("POST {0}: {1}/{2}", pingbackUri, (int)http.StatusCode, http.StatusCode));
                errorCode = (int)http.StatusCode;
                serverMessage = "The server returned an http error " + (int)http.StatusCode;
            }
            else
            {
                if (!http.ContentType.StartsWith("text/xml", StringComparison.OrdinalIgnoreCase) &&
                    !http.ContentType.StartsWith("application/xml", StringComparison.OrdinalIgnoreCase))
                {
                    logError("Expected content type: application/xml, found: " + http.ContentType);
                }

                try
                {
                    XmlLightDocument doc = new XmlLightDocument(Encoding.UTF8.GetString(http.Content));

                    XmlLightElement error = doc.SelectSingleNode("methodResponse/fault");
                    if (error != null)
                    {
                        XmlLightElement faultCode = error.SelectSingleNode("value/struct/member[name/text()='faultCode']/value/int");
                        XmlLightElement faultString = error.SelectSingleNode("value/struct/member[name/text()='faultString']/value");
                        if (faultCode == null || !int.TryParse(faultCode.InnerText, out errorCode))
                            errorCode = 0;
                        serverMessage = faultString != null ? faultString.InnerText : "Unknown Error";
                    }
                    else
                    {
                        serverMessage = doc.SelectRequiredNode("/methodResponse/params/param/value").InnerText;
                        errorCode = 0;
                        return true;
                    }
                }
                catch (Exception e)
                {
                    logError("Error parsing response: " + e.Message);
                    serverMessage = "Unable to parse xml response.";
                    errorCode = 0;
                }
            }
            return false;
        }
Exemplo n.º 8
0
 public void TestXmlNamespace()
 {
     string xml = @"<test xmlns=""urn:123"" />";
     XmlLightDocument doc = new XmlLightDocument(xml);
     Assert.AreEqual(xml, Normalize(doc.InnerXml));
 }
Exemplo n.º 9
0
		public void TestAttributes()
		{
			string xml = "<root id='a'></root>";
			XmlLightDocument doc = new XmlLightDocument(xml);
			Assert.AreEqual("root", doc.Root.LocalName);
			Assert.AreEqual(1, doc.Root.Attributes.Count);
			Assert.IsTrue(doc.Root.Attributes.GetEnumerator().MoveNext());
			Assert.IsTrue(((System.Collections.IEnumerable)doc.Root.Attributes).GetEnumerator().MoveNext());
			Assert.IsTrue(doc.Root.Attributes.Remove("id"));
			Assert.AreEqual(0, doc.Root.Attributes.Count);
        }
Exemplo n.º 10
0
        public void TestParsers()
        {
            string notxml = "<html id=a ><body foo='bar' bar=\"foo\" />";

            HtmlLightDocument html = new HtmlLightDocument();
            XmlLightParser.Parse(notxml, html);
            Assert.AreEqual("html", html.Root.TagName);
            Assert.AreEqual(1, html.Root.Attributes.Count);
            Assert.AreEqual("a", html.Root.Attributes["id"]);
            Assert.AreEqual(1, html.Root.Children.Count);
            Assert.AreEqual("body", html.Root.Children[0].TagName);
            Assert.AreEqual("foo", html.Root.Children[0].Attributes["bar"]);
            Assert.AreEqual("bar", html.Root.Children[0].Attributes["foo"]);

            XmlLightDocument xml = new XmlLightDocument();
            XmlLightParser.Parse(notxml, XmlLightParser.AttributeFormat.Xml, xml);
            Assert.AreEqual(2, xml.Root.Attributes.Count);
            //Not recognized: xml.Root.Attributes["id"]
            Assert.AreEqual("body", xml.Root.TagName);
            Assert.AreEqual("foo", xml.Root.Attributes["bar"]);
            Assert.AreEqual("bar", xml.Root.Attributes["foo"]);
        }
Exemplo n.º 11
0
		public void TestParseDocument()
		{
			XmlLightDocument doc = new HtmlLightDocument(document);
			XmlLightDocument doc2;
			using (TempFile t = new TempFile())
			{
				using (TextWriter tw = new StreamWriter(t.Open()))
					doc.WriteXml(tw);
				new XhtmlValidation(XhtmlDTDSpecification.XhtmlTransitional_10).Validate(t.TempPath);
				doc2 = new XmlLightDocument(t.ReadAllText());

				Assert.AreEqual(doc.InnerXml, doc2.InnerXml);
			}
		}
Exemplo n.º 12
0
        public void TestXmlNamespacePrefix()
        {
            string xml = @"<?xml version='1.0' encoding='ISO-8859-15'?>
<html:html xmlns:html='http://www.w3.org/TR/xhtml1/'>
<html:body>
<html:p html:align='left' class='test'>hello</html:p>
<p html:align='right' class='test'>world</p>
</html:body>
<health:body xmlns:health='http://www.example.org/health'>
<health:height>6ft</health:height>
<health:weight xmlns:a='urn:234' a:class='test'>155 lbs</health:weight>
</health:body>
</html:html>".Replace('\'', '"');

            XmlLightDocument doc = new XmlLightDocument(xml);
            Assert.AreEqual(Normalize(xml), Normalize(doc.InnerXml));
        }