/// <summary> /// Gets embedded content from the item /// </summary> /// <param name="seed"></param> public void Load(SyndicationItem item) { try { // read in content as xml StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter); item.Content.WriteTo(xmlWriter, "content", null); RawContent = xmlWriter.ToString(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(RawContent as string); // check if first node is <html> node // NOTE: Is there a better way to do this?? if (xmlDoc.FirstChild != null && xmlDoc.FirstChild.FirstChild != null && xmlDoc.FirstChild.FirstChild.LocalName == "html") { ContentType = "text/html"; } else { ContentType = "text/xml"; } } catch (Exception ex) { ServiceLocator.Current.GetInstance <IComboLog>().Error("Error loading content from item.", ex); } }
public void Serialization() { try { XmlDiff diff = new XmlDiff(); TemplateBox templateBox = new TemplateBox(TemplatingResources.TemplatesDefault); String result = templateBox.Serialize(); //Utils.WriteToFile(@"C:\temp\templates.xml", result); diff.IgnoreChildOrder = true; diff.IgnoreComments = true; diff.IgnoreDtd = true; diff.IgnoreNamespaces = true; diff.IgnorePI = true; diff.IgnorePrefixes = true; diff.IgnoreWhitespace = true; diff.IgnoreXmlDecl = true; StringWriter diffgramString = new StringWriter(); XmlTextWriter diffgramXml = new XmlTextWriter(diffgramString); bool diffBool = diff.Compare(new XmlTextReader(new StringReader(result)), new XmlTextReader(new StringReader(TemplatingResources.TemplatesDefault)), diffgramXml); //MessageBox.Show(diffgramString.ToString()); Assert.True(diffBool, diffgramXml.ToString()); } catch (Exception e) { Assert.Fail("Exception: " + e.GetType().Name + "\n" + e.Message + "\n" + e.StackTrace); } }
private XmlDocument GetXml(DataRow[] dtrows) { Stream w = new MemoryStream(); XmlTextWriter xmlTextWriter = new XmlTextWriter(w, Encoding.UTF8); xmlTextWriter.Formatting = Formatting.Indented; xmlTextWriter.WriteStartDocument(true); xmlTextWriter.WriteStartElement("Schema"); xmlTextWriter.WriteStartElement("TableName"); xmlTextWriter.WriteAttributeString("value", "Authors"); xmlTextWriter.WriteEndElement(); xmlTextWriter.WriteStartElement("FIELDS"); for (int i = 0; i < dtrows.Length; i++) { DataRow dataRow = dtrows[i]; string value = dataRow["ColumnName"].ToString(); string value2 = dataRow["TypeName"].ToString(); xmlTextWriter.WriteStartElement("FIELD"); xmlTextWriter.WriteAttributeString("Name", value); xmlTextWriter.WriteAttributeString("Type", value2); xmlTextWriter.WriteEndElement(); } xmlTextWriter.WriteEndElement(); xmlTextWriter.WriteEndElement(); xmlTextWriter.Flush(); xmlTextWriter.Close(); TextReader txtReader = new StringReader(xmlTextWriter.ToString()); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(txtReader); return(xmlDocument); }
public void RunXslTransformCommand() { if (string.IsNullOrEmpty(stylesheetFileName)) { stylesheetFileName = XmlEditorService.BrowseForStylesheetFile(); if (string.IsNullOrEmpty(stylesheetFileName)) { return; } } using (IProgressMonitor monitor = XmlEditorService.GetMonitor()) { try { string xsltContent; try { xsltContent = GetFileContent(stylesheetFileName); } catch (System.IO.IOException) { monitor.ReportError( GettextCatalog.GetString("Error reading file '{0}'.", stylesheetFileName), null); return; } System.Xml.Xsl.XslTransform xslt = XmlEditorService.ValidateStylesheet(monitor, xsltContent, stylesheetFileName); if (xslt == null) { return; } XmlDocument doc = XmlEditorService.ValidateXml(monitor, Editor.Text, FileName); if (doc == null) { return; } string newFileName = XmlEditorService.GenerateFileName(FileName, "-transformed{0}.xml"); monitor.BeginTask(GettextCatalog.GetString("Executing transform..."), 1); using (XmlTextWriter output = XmlEditorService.CreateXmlTextWriter(Document)) { xslt.Transform(doc, null, output); IdeApp.Workbench.NewDocument( newFileName, "application/xml", output.ToString()); } monitor.ReportSuccess(GettextCatalog.GetString("Transform completed.")); monitor.EndTask(); } catch (Exception ex) { string msg = GettextCatalog.GetString("Could not run transform."); monitor.ReportError(msg, ex); monitor.EndTask(); } } }
public string VuelcaXML() { using (var xw = new XmlTextWriter("vehiculos.xml", Encoding.UTF8)) { xw.WriteStartElement("vehiculos"); foreach (Vehiculo v in Vehiculos) { string matricula = v.Matricula; string tipo = v.Tipo; string marca = v.Marca; string modelo = v.Modelo; string consumo = v.Consumo; string fechaAdquisicion = v.FechaAdquisicion; string fechaFabricacion = v.FechaFabricacion; List <string> comodidades = v.Comodidades; xw.WriteStartElement("vehiculo"); xw.WriteStartElement("matricula"); xw.WriteString(matricula); xw.WriteEndElement(); xw.WriteStartElement("tipo"); xw.WriteString(tipo); xw.WriteEndElement(); xw.WriteStartElement("marca"); xw.WriteString(marca); xw.WriteEndElement(); xw.WriteStartElement("modelo"); xw.WriteString(modelo); xw.WriteEndElement(); xw.WriteStartElement("consumo"); xw.WriteString(consumo); xw.WriteEndElement(); xw.WriteStartElement("fecha_adquisicion"); xw.WriteString(fechaAdquisicion); xw.WriteEndElement(); xw.WriteStartElement("fecha_fabricacion"); xw.WriteString(fechaFabricacion); xw.WriteEndElement(); xw.WriteStartElement("comodidades"); foreach (string c in comodidades) { xw.WriteStartElement("comodidad"); xw.WriteString(c); xw.WriteEndElement(); } xw.WriteEndElement(); xw.WriteEndElement(); } xw.WriteEndElement(); xw.Close(); return(xw.ToString()); } }
public virtual String Render() { try { StringWriter sw = new StringWriter(); XmlTextWriter tw = new XmlTextWriter(sw); element.WriteContentTo(tw); return(tw.ToString()); } catch (System.Exception e) {} return(""); }
public string ProcessTextRequest(HttpContext context) { // Hiện nội dung ở context context.Response.ContentType = "text/xml"; using (XmlTextWriter writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8)) { writer.WriteStartDocument(); writer.WriteStartElement("urlset"); writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"); writer.WriteStartElement("url"); string connect = ConfigurationManager.ConnectionStrings["TVSConnect"].ConnectionString; string url = "http://www.yolooo.com/"; using (SqlConnection conn = new SqlConnection(connect)) { using (SqlCommand cmd = new SqlCommand("GetSiteMapContent", conn)) { cmd.CommandType = CommandType.StoredProcedure; conn.Open(); using (SqlDataReader rdr = cmd.ExecuteReader()) { // Get the date of the most recent article rdr.Read(); writer.WriteElementString("loc", string.Format("{0}Default.aspx", url)); writer.WriteElementString("lastmod", string.Format("{0:yyyy-MM-dd}", rdr[0])); writer.WriteElementString("changefreq", "weekly"); writer.WriteElementString("priority", "1.0"); writer.WriteEndElement(); // Move to the Facebook Article IDs rdr.NextResult(); while (rdr.Read()) { writer.WriteStartElement("url"); writer.WriteElementString("loc", string.Format("{0}Detailts.aspx?id={1}", url, rdr[0])); if (rdr[1] != DBNull.Value) { writer.WriteElementString("lastmod", string.Format("{0:yyyy-MM-dd}", rdr[1])); } writer.WriteElementString("changefreq", "monthly"); writer.WriteElementString("priority", "0.5"); writer.WriteEndElement(); } // and more writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); } context.Response.End(); // viết tài liệu } } return(writer.ToString()); } }
/// <summary> /// Takes the contents of an <see cref="IUPnPMedia"/> object /// casts the data into its XML string form and returns it. /// </summary> /// <param name="entry">the object to extract</param> /// <returns>everything under the item or container element</returns> private string GrabInnerText(IUPnPMedia entry) { StringBuilder sb = new StringBuilder(1000); StringWriter sw = new StringWriter(sb); XmlTextWriter xmlWriter = new XmlTextWriter(sw); // set up the ToXml() method to only provide the InnerText of the element entry.ToXml(ToXmlFormatter.DefaultFormatter, MediaObject.ToXmlData_AllInnerTextOnly, xmlWriter); xmlWriter.Flush(); string result = xmlWriter.ToString(); xmlWriter.Close(); return(result); }
///// <summary> ///// 根据模版得到生成的代码 ///// </summary> ///// <returns></returns> //public string GetCode() //{ // DataTable dt = dbobj.GetColumnInfoList(DbName, TableName); // System.IO.StringWriter stringWriter = new System.IO.StringWriter(); // if (dt != null) // { // DataRow[] dtrows; // if (Fieldlist.Count > 0) // { // dtrows = dt.Select("ColumnName in (" + Fields + ")", "colorder asc"); // } // else // { // dtrows = dt.Select(); // } // //XslCompiledTransform xslt = new XslCompiledTransform(); // XslTransform xslt = new XslTransform(); // //StreamReader srFile = new StreamReader(strXslt, Encoding.Default); // //XmlTextReader x = new XmlTextReader(srFile); // //xslt.Load(x); // xslt.Load(strXslt); // //XmlTextReader xtr = new XmlTextReader(GetXml(dtrows)); // //XmlTextWriter xtw = new XmlTextWriter(); // xslt.Transform(GetXml2(dtrows), null, stringWriter, null); // } // return stringWriter.ToString(); //} #endregion /// <summary> /// 得到数据的xml /// </summary> /// <returns></returns> private XmlDocument GetXml(DataRow[] dtrows) { //string xmlDoc = "temp.xml"; Stream w = new System.IO.MemoryStream(); XmlTextWriter writer = new XmlTextWriter(w, Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(true); writer.WriteStartElement("Schema"); writer.WriteStartElement("TableName"); writer.WriteAttributeString("value", "Authors"); writer.WriteEndElement(); writer.WriteStartElement("FIELDS"); foreach (DataRow row in dtrows) { string columnName = row["ColumnName"].ToString(); string columnType = row["TypeName"].ToString(); //string IsIdentity = row["IsIdentity"].ToString(); writer.WriteStartElement("FIELD"); writer.WriteAttributeString("Name", columnName); writer.WriteAttributeString("Type", columnType); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndElement(); writer.Flush(); writer.Close(); //return w; TextReader stringReader = new StringReader(writer.ToString()); XmlDocument xml = new XmlDocument(); xml.Load(stringReader); return(xml); }
public string VuelcaXML() { using (var xw = new XmlTextWriter("clientes.xml", Encoding.UTF8)) { xw.WriteStartElement("clientes"); foreach (Cliente c in Clientes) { string NIF = c.NIF; string nombre = c.Nombre; string telefono = c.Telefono; string email = c.Email; string direccion = c.Direccion; xw.WriteStartElement("cliente"); xw.WriteStartElement("NIF"); xw.WriteString(NIF); xw.WriteEndElement(); xw.WriteStartElement("Nombre"); xw.WriteString(nombre); xw.WriteEndElement(); xw.WriteStartElement("Telefono"); xw.WriteString(telefono); xw.WriteEndElement(); xw.WriteStartElement("Email"); xw.WriteString(email); xw.WriteEndElement(); xw.WriteStartElement("Direccion"); xw.WriteString(direccion); xw.WriteEndElement(); xw.WriteEndElement(); } xw.WriteEndElement(); xw.Close(); return(xw.ToString()); } }
public void MergeExisting() { StringWriter textWriter = new StringWriter(); XmlTextWriter xmlWriter = NiniWriter(textWriter); WriteSection(xmlWriter, "Pets"); WriteKey(xmlWriter, "cat", "muffy"); xmlWriter.WriteEndDocument(); StringReader reader = new StringReader(xmlWriter.ToString()); XmlTextReader xmlReader = new XmlTextReader(reader); XmlConfigSource xmlSource = new XmlConfigSource(xmlReader); StringWriter writer = new StringWriter(); writer.WriteLine("[People]"); writer.WriteLine(" woman = Jane"); IniConfigSource iniSource = new IniConfigSource(new StringReader(writer.ToString())); xmlSource.Merge(iniSource); xmlSource.Merge(iniSource); // exception }
public void saveTestToDB(Test test) { string employee = test.employee; DateTime testDate = test.date; int testType = test.testType; bool passed = test.passed; int totalPoints = test.totalPoints; int category1 = test.category1; int category2 = test.category2; int category3 = test.category3; XmlDocument xml = test.sourceFile; StringWriter sw = new StringWriter(); XmlTextWriter tw = new XmlTextWriter(sw); xml.WriteTo(tw); string xmlString = tw.ToString(); string sql = "INSERT INTO finished_tests (employee, date, type, passed, total_points, points_category1, points_category2, points_category3, xml)" + "values (@employee, @date, @type, @passed, @total, @cat1, @cat2, @cat3, @xml)"; openConn(); _cmd = new NpgsqlCommand(sql, _conn); _cmd.Parameters.AddWithValue("employee", employee); _cmd.Parameters.AddWithValue("date", testDate); _cmd.Parameters.AddWithValue("type", testType); _cmd.Parameters.AddWithValue("passed", passed); _cmd.Parameters.AddWithValue("total", totalPoints); _cmd.Parameters.AddWithValue("cat1", category1); _cmd.Parameters.AddWithValue("cat2", category2); _cmd.Parameters.AddWithValue("cat3", category3); _cmd.Parameters.AddWithValue("xml", xmlString); //Lite osäker på om den måste vara .ToString() för att databasen ska ta emot eller inte. Kan kolla upp detta. _cmd.ExecuteNonQuery(); closeConn(); }
/// <summary> /// Generates a list of sitemap url elements for the given list of urlbuilder instances. Use this within a file to keep outputting urls /// </summary> /// <param name="sitemapList"></param> /// <param name="isPublishing"></param> /// <returns></returns> public string GetSitemapXmlChunk(IEnumerable <SitemapItem> sitemapList, bool isPublishing = true) { var writer = new XmlTextWriter( new System.Xml.XmlWriterSettings() { Indent = true, IndentChars = "\t", ConformanceLevel = System.Xml.ConformanceLevel.Fragment } ); // if(WritingFull) // { // writer.WriteStartDocument(standalone: true); // //writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9"); // writer.WriteRaw(@"<urlset xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9"" //xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" //xsi:schemalocation=""http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"">"); // } foreach (var urlBuilder in sitemapList) { var url = urlBuilder.Create(); writer.WriteStartElement("url"); { writer.WriteStartElement("loc"); if (isPublishing == false) { writer.WriteString(string.Format("CMS Path: {0}", urlBuilder.Asset.AssetPath)); } else { if (ForceHttps) { if (url.loc.StartsWith("http://")) { url.loc = "https://" + url.loc.Substring(7); } } writer.WriteString(url.loc); } writer.WriteEndElement(); //loc writer.WriteStartElement("lastmod"); writer.WriteString(url.lastmod); writer.WriteEndElement(); if (string.IsNullOrEmpty(url.changefreq) == false) { writer.WriteStartElement("changefreq"); writer.WriteString(url.changefreq); writer.WriteEndElement(); } if (string.IsNullOrEmpty(url.priority) == false) { writer.WriteStartElement("priority"); writer.WriteString(url.priority); writer.WriteEndElement(); } } writer.WriteEndElement(); //url } //if(WritingFull) //{ // //writer.WriteEndElement("urlset"); // writer.WriteRaw("</urlset>"); //} return(writer.ToString()); }
public XmlNode call(XmlNode input) { XmlNode node = input; if (style == CallStyle.HTTP_GET || style == CallStyle.HTTP_POST) { node = input.FirstChild; WebRequest conn = null; string urlOperation = endpointURL + operationLocation; string parameters = ""; if (node != null) { if (contentType == HttpContentType.HTTP_XML && style == CallStyle.HTTP_POST) { if (node.ChildNodes.Count > 1) { throw new Exception("HTTP POST with text/xml encoding can handle only one part"); } System.IO.StringWriter sgwr = new System.IO.StringWriter(); XmlTextWriter xmlwr = new XmlTextWriter(sgwr); xmlwr.Formatting = Formatting.None; node.FirstChild.WriteTo(xmlwr); parameters = xmlwr.ToString(); } else if (contentType == HttpContentType.HTTP_URL_ENCODED) { for (int i = 0; i < node.ChildNodes.Count; i++) { if (i > 0) { parameters += "&"; } parameters += System.Web.HttpUtility.UrlEncode(node.ChildNodes[i].LocalName, Encoding.UTF8); parameters += "="; parameters += System.Web.HttpUtility.UrlEncode(node.ChildNodes[i].InnerText, Encoding.UTF8); } } else { throw new Exception("Unsupported mime type for HTTP binding"); } } if (style == CallStyle.HTTP_GET) { if (parameters.Length > 0) { urlOperation += ("?" + parameters); } conn = WebRequest.Create(urlOperation); conn.Method = "GET"; if (username.Length != 0 && password.Length != 0) { conn.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password)); } } else // post { conn = WebRequest.Create(urlOperation); conn.Method = "POST"; if (contentType == HttpContentType.HTTP_XML) { conn.ContentType = "text/xml; charset=" + encoding; } else if (contentType == HttpContentType.HTTP_URL_ENCODED) { conn.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; } else { throw new Exception("Unsupported mime type for HTTP binding"); } byte[] data = Encoding.UTF8.GetBytes(parameters); conn.ContentLength = data.Length; if (username.Length != 0 && password.Length != 0) { conn.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password)); } System.IO.Stream rqs = conn.GetRequestStream(); rqs.Write(data, 0, data.Length); rqs.Close(); } HttpWebResponse wre = null; try { wre = (HttpWebResponse)conn.GetResponse(); } catch (WebException wex) { wre = (HttpWebResponse)wex.Response; } if (wre.StatusCode == HttpStatusCode.OK) { XmlDocument respDoc = new XmlDocument(); respDoc.Load(wre.GetResponseStream()); return(respDoc); } else { throw new Exception("Failed: " + wre.StatusCode + " " + wre.StatusDescription); } } else if (style == CallStyle.SOAP_RPC_ENCODED || style == CallStyle.SOAP_DOCUMENT_LITERAL) { byte[] data = Encoding.UTF8.GetBytes(input.OuterXml); WebRequest conn = WebRequest.Create(endpointURL); conn.Method = "POST"; if (soapVersion == SoapVersion.SOAP12) { if (soapAction.Length > 0) { conn.ContentType = "application/soap+xml; action=" + soapAction; } else { conn.ContentType = "application/soap+xml"; } } else { conn.ContentType = "text/xml; charset=utf-8"; conn.Headers["SOAPAction"] = "\"" + soapAction + "\""; } conn.ContentLength = data.Length; if (username.Length != 0 && password.Length != 0) { conn.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password)); } System.IO.Stream rqs = conn.GetRequestStream(); rqs.Write(data, 0, data.Length); rqs.Close(); WebResponse wre = null; try { wre = conn.GetResponse(); } catch (WebException wex) { wre = wex.Response; } XmlDocument respDoc = new XmlDocument(); respDoc.Load(wre.GetResponseStream()); // check mustUnderstand XmlNodeList headers = respDoc.GetElementsByTagName("Header", soapEnvNs); if (headers.Count > 1) { throw new Exception("more than one SOAPENV:Header found"); } if (headers.Count == 1) { // if header has any children that have mustUnderstand==1, throw "don' understand" for (XmlNode headerNode = headers[0].FirstChild; headerNode != null; headerNode = headerNode.NextSibling) { if (headerNode.NodeType == XmlNodeType.Element) { XmlNode muAttr = headerNode.Attributes.GetNamedItem("mustUnderstand", soapEnvNs); if (muAttr.Value == "1" || muAttr.Value == "true") { throw new Exception("Cannot process messages with mustUnderstand headers"); } } } } return(respDoc); } else { throw new Exception("Unsupported style"); } }
public override void Process(HttpRequestArgs args) { Assert.ArgumentNotNull((object)args, "args"); if (Context.Site == null || string.IsNullOrEmpty(Context.Site.RootPath.Trim())) { return; } if (Context.Page.FilePath.Length > 0) { return; } if (!args.Url.FilePath.Contains(sitemapUrl)) { return; } // Important to return qualified XML (text/xml) for sitemaps args.Context.Response.ClearHeaders(); args.Context.Response.ClearContent(); args.Context.Response.ContentType = "text/xml"; // Checking the cache first var sitemapXmlCache = args.Context.Cache["sitemapxml"]; if (sitemapXmlCache != null) { args.Context.Response.Write(sitemapXmlCache.ToString()); args.Context.Response.End(); return; } // var options = LinkManager.GetDefaultUrlOptions(); options.AlwaysIncludeServerUrl = true; // Creating the XML Header var xml = new XmlTextWriter(args.Context.Response.Output); xml.WriteStartDocument(); xml.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9"); // Creating the XML Body try { var items = Context.Database.SelectItems("fast:" + Context.Site.RootPath + "//*"); foreach (var item in items) { if (IsPage(item)) { if (!item.Paths.IsContentItem) { continue; } if (excludedPaths.Split('|').Any(p => item.Paths.ContentPath.Contains(p))) { continue; } xml.WriteStartElement("url"); xml.WriteElementString("loc", LinkManager.GetItemUrl(item, options)); xml.WriteElementString("lastmod", item.Statistics.Updated.ToString("yyyy-MM-ddThh:mm:sszzz")); xml.WriteEndElement(); } } } finally { xml.WriteEndElement(); xml.WriteEndDocument(); xml.Flush(); // Cache XML content args.Context.Cache.Add("sitemapxml", xml.ToString(), null, DateTime.Now.AddSeconds(int.Parse(cacheTime)), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); args.Context.Response.Flush(); args.Context.Response.End(); } }
public bool call(XmlNode input, XmlNode output) { XmlNode node = input; if (style == CallStyle.HTTP_GET || style == CallStyle.HTTP_POST) { node = input.FirstChild; WebRequest conn = null; string urlOperation = endpointURL + operationLocation; string parameters = ""; if (node != null) { if (contentType == HttpContentType.HTTP_XML && style == CallStyle.HTTP_POST) { if (node.ChildNodes.Count > 1) { throw new Exception("HTTP POST with text/xml encoding can handle only one part"); } System.IO.StringWriter sgwr = new System.IO.StringWriter(); XmlTextWriter xmlwr = new XmlTextWriter(sgwr); xmlwr.Formatting = Formatting.None; node.FirstChild.WriteTo(xmlwr); parameters = xmlwr.ToString(); } else if (contentType == HttpContentType.HTTP_URL_ENCODED) { for (int i = 0; i < node.ChildNodes.Count; i++) { if (i > 0) { parameters += "&"; } parameters += System.Web.HttpUtility.UrlEncode(node.ChildNodes[i].LocalName, Encoding.UTF8); parameters += "="; parameters += System.Web.HttpUtility.UrlEncode(node.ChildNodes[i].InnerText, Encoding.UTF8); } } else { throw new Exception("Unsupported mime type for HTTP binding"); } } if (style == CallStyle.HTTP_GET) { if (parameters.Length > 0) { urlOperation += ("?" + parameters); } conn = WebRequest.Create(urlOperation); conn.Method = "GET"; if (username.Length != 0 && password.Length != 0) { conn.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password)); } } else // post { conn = WebRequest.Create(urlOperation); conn.Method = "POST"; if (contentType == HttpContentType.HTTP_XML) { conn.ContentType = "text/xml; charset=" + encoding; } else if (contentType == HttpContentType.HTTP_URL_ENCODED) { conn.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; } else { throw new Exception("Unsupported mime type for HTTP binding"); } byte[] data = Encoding.UTF8.GetBytes(parameters); conn.ContentLength = data.Length; if (username.Length != 0 && password.Length != 0) { conn.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password)); } System.IO.Stream rqs = conn.GetRequestStream(); rqs.Write(data, 0, data.Length); rqs.Close(); } HttpWebResponse wre = null; try { wre = (HttpWebResponse)conn.GetResponse(); } catch (WebException wex) { wre = (HttpWebResponse)wex.Response; } if (wre.StatusCode == HttpStatusCode.OK) { XmlDocument respDoc = new XmlDocument(); respDoc.Load(wre.GetResponseStream()); output.AppendChild(output.OwnerDocument.ImportNode(respDoc.DocumentElement, true)); return(true); } else { throw new Exception("Failed: " + wre.StatusCode + " " + wre.StatusDescription); } } else if (style == CallStyle.SOAP_RPC_ENCODED || style == CallStyle.SOAP_DOCUMENT_LITERAL) { XmlDocument soapDoc = new XmlDocument(); XmlElement envelope = soapDoc.CreateElement("SOAP-ENV:Envelope", soapEnvNs); envelope.SetAttribute("xmlns:SOAP-ENV", soapEnvNs); envelope.SetAttribute("xmlns:SOAP-ENC", soapEncNs); envelope.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); envelope.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema"); XmlNode body = soapDoc.CreateElement("SOAP-ENV:Body", soapEnvNs); XmlNode header = soapDoc.CreateElement("SOAP-ENV:Header", soapEnvNs); if (style == CallStyle.SOAP_RPC_ENCODED) { // create rpcEnvelope XmlElement rpcEnvelope = soapDoc.CreateElement("m:" + operationName, WSDLTargetNamespace); rpcEnvelope.SetAttribute("xmlns:m", WSDLTargetNamespace); rpcEnvelope.SetAttribute("encodingStyle", soapEnvNs, soapEncNs); // take all attributes from root element, insert them into rpcEnvelope for (int i = 0; i < node.FirstChild.Attributes.Count; i++) { rpcEnvelope.SetAttribute(node.Attributes[i].Name, node.Attributes[i].Value); } // and add children of root node to rpcEnvelope if (node != null) { int count = node.ChildNodes.Count; // headers first: 0..n-1 for (int i = 0; i < count - 1; i++) { header.AppendChild(soapDoc.ImportNode(node.ChildNodes[i], true)); } // message is last XmlNode dummyMsgRoot = node.ChildNodes[count - 1]; for (int i = 0; i < dummyMsgRoot.ChildNodes.Count; i++) { rpcEnvelope.AppendChild(soapDoc.ImportNode(dummyMsgRoot.ChildNodes[i], true)); } } body.AppendChild(rpcEnvelope); } else { // just add all children if (node != null) { int count = node.ChildNodes.Count; // headers first: 0..n-1 for (int i = 0; i < count - 1; i++) { header.AppendChild(soapDoc.ImportNode(node.ChildNodes[i], true)); } // message is last XmlNode dummyMsgRoot = node.ChildNodes[count - 1]; for (int i = 0; i < dummyMsgRoot.ChildNodes.Count; i++) { body.AppendChild(soapDoc.ImportNode(dummyMsgRoot.ChildNodes[i], true)); } } } if (header.ChildNodes.Count > 0) { envelope.AppendChild(header); } envelope.AppendChild(body); soapDoc.AppendChild(envelope); byte[] data = Encoding.UTF8.GetBytes(soapDoc.DocumentElement.OuterXml); WebRequest conn = WebRequest.Create(endpointURL); conn.Method = "POST"; conn.ContentType = "text/xml; charset=utf-8"; conn.Headers["SOAPAction"] = soapAction; conn.ContentLength = data.Length; if (username.Length != 0 && password.Length != 0) { conn.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password)); } System.IO.Stream rqs = conn.GetRequestStream(); rqs.Write(data, 0, data.Length); rqs.Close(); WebResponse wre = null; try { wre = conn.GetResponse(); } catch (WebException wex) { wre = wex.Response; } soapDoc.Load(wre.GetResponseStream()); // check mustUnderstand XmlNodeList headers = soapDoc.GetElementsByTagName("Header", soapEnvNs); if (headers.Count > 1) { throw new Exception("more than one SOAPENV:Header found"); } if (headers.Count == 1) { // if header has any children that have mustUnderstand==1, throw "don' understand" for (XmlNode headerNode = headers[0].FirstChild; headerNode != null; headerNode = headerNode.NextSibling) { if (headerNode.NodeType == XmlNodeType.Element) { XmlNode muAttr = headerNode.Attributes.GetNamedItem("mustUnderstand", soapEnvNs); if (muAttr.Value == "1" || muAttr.Value == "true") { throw new Exception("Cannot process messages with mustUnderstand headers"); } } } } XmlNodeList bodies = soapDoc.GetElementsByTagName("Body", soapEnvNs); if (bodies.Count == 0) { throw new Exception("Body not present"); } body = bodies[0]; node = output; XmlNode bodyChild = null; for (int i = 0; i < body.ChildNodes.Count; ++i) { if (body.ChildNodes[i].NodeType == XmlNodeType.Element) { bodyChild = body.ChildNodes[i]; break; } } if (bodyChild == null) { throw new Exception("Body has no children"); } if (bodyChild.LocalName == "Fault" && bodyChild.NamespaceURI == soapEnvNs) { XmlElement faultEnvelope = node.OwnerDocument.CreateElement("soapenv:Fault", soapEnvNs); XmlNode detailNode = bodyChild.SelectSingleNode("detail"); if (detailNode != null) { for (int i = 0; i < detailNode.ChildNodes.Count; i++) { if (detailNode.ChildNodes[i].NodeType == XmlNodeType.Element) { faultEnvelope.AppendChild(faultEnvelope.OwnerDocument.ImportNode(detailNode.ChildNodes[i], true)); } } } for (XmlNode faultInfoNode = bodyChild.FirstChild; faultInfoNode != null; faultInfoNode = faultInfoNode.NextSibling) { if (faultInfoNode.LocalName != "detail") { faultEnvelope.AppendChild(faultEnvelope.OwnerDocument.ImportNode(faultInfoNode, true)); } } node.AppendChild(faultEnvelope); return(false); } if (style == CallStyle.SOAP_DOCUMENT_LITERAL) { // bodyChildren are parts for (int i = 0; i < body.ChildNodes.Count; ++i) { if (body.ChildNodes[i].NodeType == XmlNodeType.Element) { node.AppendChild(node.OwnerDocument.ImportNode(body.ChildNodes[i], true)); } } } else if (style == CallStyle.SOAP_RPC_ENCODED) { for (int i = 0; i < bodyChild.ChildNodes.Count; i++) { if (bodyChild.ChildNodes[i].NodeType == XmlNodeType.Element) { node.AppendChild(node.OwnerDocument.ImportNode(bodyChild.ChildNodes[i], true)); } } // handle references for (int i = 0; i < body.ChildNodes.Count; ++i) { if (body.ChildNodes[i].NodeType == XmlNodeType.Element) { node.AppendChild(node.OwnerDocument.ImportNode(body.ChildNodes[i], true)); } } } return(true); } else { throw new Exception("Unsupported style"); } }
public string ProcessFileRequest(HttpContext context) { // không tạo ra context using (XmlTextWriter writer = new XmlTextWriter(context.Server.MapPath("~/sitemap.xml"), Encoding.UTF8)) { // khai báo tên tài liệu writer.WriteStartDocument(); writer.WriteStartElement("urlset"); //Các thuộc tính của tài liệu chuẩn của google writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"); writer.WriteStartElement("url"); string connect = ConfigurationManager.ConnectionStrings["TVSConnect"].ConnectionString; string url = "http://www.yolooo.com/"; using (SqlConnection conn = new SqlConnection(connect)) { using (SqlCommand cmd = new SqlCommand("GetSiteMapContent", conn)) { // Chạy procedure được tạo cmd.CommandType = CommandType.StoredProcedure; conn.Open(); using (SqlDataReader rdr = cmd.ExecuteReader()) { // Get the date of the most recent article rdr.Read(); // Lấy dử liệu từ dòng lệnh select đầu tiên writer.WriteElementString("loc", string.Format("trang-chu", url)); /* * Trang chủ * */ writer.WriteElementString("lastmod", string.Format("{0:yyyy-MM-dd}", rdr[0])); writer.WriteElementString("changefreq", "weekly"); writer.WriteElementString("priority", "1.0"); writer.WriteEndElement(); // Move to the Facebook Article IDs rdr.NextResult(); // Lấy dử liệu từ dòng lệnh select thứ 2 while (rdr.Read()) { writer.WriteStartElement("url"); writer.WriteElementString("loc", string.Format("{0}Detailts.aspx?id={1}", url, rdr[0])); /* * Bài viết * */ if (rdr[1] != DBNull.Value) { writer.WriteElementString("lastmod", string.Format("{0:yyyy-MM-dd}", rdr[1])); } writer.WriteElementString("changefreq", "monthly"); writer.WriteElementString("priority", "0.5"); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndDocument(); XmlDocument doc = new XmlDocument(); writer.Formatting = Formatting.Indented; doc.Save(writer); writer.Flush(); } } } return(writer.ToString()); } }