/// <summary> /// To Create Xml file for every multiselect list to pass data of xml type in database /// </summary> /// <param name="DtXml"></param> /// <param name="Text"></param> /// <param name="Value"></param> /// <param name="XmlFileName"></param> /// <returns></returns> public string GetXml(DataTable DtXml, String Text, String Value,string XmlFileName) { XmlDocument xmldoc = new XmlDocument(); //To create Xml declarartion in xml file XmlDeclaration decl = xmldoc.CreateXmlDeclaration("1.0", "UTF-16", ""); xmldoc.InsertBefore(decl, xmldoc.DocumentElement); XmlElement RootNode = xmldoc.CreateElement("Root"); xmldoc.AppendChild(RootNode); for (int i = 0; i < DtXml.Rows.Count; i++) { XmlElement childNode = xmldoc.CreateElement("Row"); childNode.SetAttribute(Value, DtXml.Rows[i][1].ToString()); childNode.SetAttribute(Text, DtXml.Rows[i][0].ToString()); RootNode.AppendChild(childNode); } //Check if directory already exist or not otherwise //create directory if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("XML"))) Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("XML")); XmlFileName = "XML" + "\\" + XmlFileName; //To save xml file on respective path xmldoc.Save(System.Web.HttpContext.Current.Server.MapPath(XmlFileName)); xmldoc.RemoveChild(xmldoc.FirstChild); string RetXml = xmldoc.InnerXml; return RetXml; }
public static void InsertCDataNodeToDocumentNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<a/>"); var cDataSection = xmlDocument.CreateCDataSection("data"); Assert.Throws<InvalidOperationException>(() => xmlDocument.InsertBefore(cDataSection, null)); }
public static void SaveToXML(IntFontInfo fnt, string outPath) { XmlDocument doc = new XmlDocument(); XmlDeclaration decl = doc.CreateXmlDeclaration("1.0","utf-8",null); XmlElement root = doc.CreateElement("font"); doc.InsertBefore(decl, doc.DocumentElement); doc.AppendChild(root); XmlElement common = doc.CreateElement("common"); common.SetAttribute("lineHeight", fnt.lineHeight.ToString()); common.SetAttribute("scaleW", fnt.scaleW.ToString()); common.SetAttribute("scaleH", fnt.scaleH.ToString()); common.SetAttribute("pages", "1"); root.AppendChild(common); XmlElement pages = doc.CreateElement("pages"); XmlElement page1 = doc.CreateElement("page"); page1.SetAttribute("id", "0"); page1.SetAttribute("file", fnt.texName); pages.AppendChild(page1); root.AppendChild(pages); XmlElement chars = doc.CreateElement("chars"); chars.SetAttribute("count", fnt.chars.Count.ToString()); foreach(IntChar c in fnt.chars){ XmlElement cNode = doc.CreateElement("char"); cNode.SetAttribute("id", c.id.ToString()); cNode.SetAttribute("x", c.x.ToString()); cNode.SetAttribute("y", c.y.ToString()); cNode.SetAttribute("width", c.width.ToString()); cNode.SetAttribute("height", c.height.ToString()); cNode.SetAttribute("xoffset", c.xoffset.ToString()); cNode.SetAttribute("yoffset", c.yoffset.ToString()); cNode.SetAttribute("xadvance", c.xadvance.ToString()); chars.AppendChild(cNode); } root.AppendChild(chars); XmlElement kernings = doc.CreateElement("kernings"); kernings.SetAttribute("count", fnt.kernings.Count.ToString()); foreach(IntKerning k in fnt.kernings){ XmlElement kNode = doc.CreateElement("kerning"); kNode.SetAttribute("first", k.first.ToString()); kNode.SetAttribute("second", k.second.ToString()); kNode.SetAttribute("amount", k.amount.ToString()); kernings.AppendChild(kNode); } root.AppendChild(kernings); doc.Save(outPath); }
protected void Page_Load(object sender, EventArgs e) { string sSiteMapFilePath = HttpRuntime.AppDomainAppPath + "sitemap.xml"; var fi = new FileInfo(sSiteMapFilePath); //if (fi.Exists && fi.LastWriteTime < DateTime.Now.AddHours(-1)) //{ // only allow it to be written once an hour in case someone spams this page (so it doesnt crash the site) _xd = new XmlDocument(); XmlNode rootNode = _xd.CreateElement("urlset"); // add namespace var attrXmlNS = _xd.CreateAttribute("xmlns"); attrXmlNS.InnerText = "http://www.sitemaps.org/schemas/sitemap/0.9"; rootNode.Attributes.Append(attrXmlNS); //add img namespace var attrXmlNS2 = _xd.CreateAttribute("xmlns:image"); attrXmlNS2.InnerText = "http://www.google.com/schemas/sitemap-image/1.1"; rootNode.Attributes.Append(attrXmlNS2); // home page rootNode.AppendChild(GenerateUrlNode("http://www.how-to-asp.net", DateTime.Now, "hourly", "1.00", "http://myimage.com")); // ADD THE REST OF YOUR URL'S HERE // append all nodes to the xmldocument and save it to sitemap.xml _xd.AppendChild(rootNode); _xd.InsertBefore(_xd.CreateXmlDeclaration("1.0", "UTF-8", null), rootNode); _xd.Save(sSiteMapFilePath); // PING SEARCH ENGINES TO LET THEM KNOW YOU UPDATED YOUR SITEMAP // resubmit to google //System.Net.WebRequest reqGoogle = System.Net.WebRequest.Create("http://www.google.com/webmasters/tools/ping?sitemap=" + HttpUtility.UrlEncode("http://www.how-to-asp.net/sitemap.xml")); //reqGoogle.GetResponse(); //// resubmit to ask //System.Net.WebRequest reqAsk = System.Net.WebRequest.Create("http://submissions.ask.com/ping?sitemap=" + HttpUtility.UrlEncode("http://www.how-to-asp.net/sitemap.xml")); //reqAsk.GetResponse(); //// resubmit to yahoo //System.Net.WebRequest reqYahoo = System.Net.WebRequest.Create("http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=YahooDemo&url=" + HttpUtility.UrlEncode("http://www.how-to-asp.net/sitemap.xml")); //reqYahoo.GetResponse(); //// resubmit to bing //System.Net.WebRequest reqBing = System.Net.WebRequest.Create("http://www.bing.com/webmaster/ping.aspx?siteMap=" + HttpUtility.UrlEncode("http://www.how-to-asp.net/sitemap.xml")); //reqBing.GetResponse(); }
public static XmlDocument ToXmlDocument(this XDocument xDocument) { var xmlDocument = new XmlDocument(); using (var xmlReader = xDocument.CreateReader()) { xmlDocument.Load(xmlReader); } var xDeclaration = xDocument.Declaration; if (xDeclaration != null) { var xmlDeclaration = xmlDocument.CreateXmlDeclaration( xDeclaration.Version, xDeclaration.Encoding, xDeclaration.Standalone); xmlDocument.InsertBefore(xmlDeclaration, xmlDocument.FirstChild); } return xmlDocument; }
public void Write_Computer_List(string[] filenames) { XmlDocument xd = new XmlDocument(); XmlDeclaration xdec = xd.CreateXmlDeclaration("1.0", "utf-8", null); xd.InsertBefore(xdec, xd.DocumentElement); XmlElement xeroot = xd.CreateElement("Computers"); xd.AppendChild(xeroot); foreach (string K in filenames) { string fname; fname = K.ToString(); //getSerialNo(fname); XmlElement xeComputer = xd.CreateElement("Computer"); xeroot.AppendChild(xeComputer); XmlAttribute xa = xd.CreateAttribute("Name"); xa.Value = K.ToString(); xeComputer.Attributes.Append(xa); } xd.Save(Server.MapPath("..//Files//Asset.xml")); }
//Method used to write out the log file once the game has completed //takes bool that indicates whether the session was properly completed public void WriteOut(bool completed) { //Generate the file name GenerateNewTimestamp(); //Set up the xml document XmlDocument xml = new XmlDocument(); //Create declaration XmlDeclaration dec = xml.CreateXmlDeclaration("1.0", "utf-8",null); xml.AppendChild(dec); // Create the root element "session" XmlElement session = xml.CreateElement("session"); xml.InsertBefore(dec, xml.DocumentElement); xml.AppendChild(session); if(gm.SType == GameManager.SessionType.Spatial) WriteOutSpatial(xml,session); else if(gm.SType == GameManager.SessionType.Inhibition) WriteOutInhibition(xml,session); else if (gm.SType == GameManager.SessionType.Star) WriteOutStar(xml,session); else if (gm.SType == GameManager.SessionType.Implicit) WriteOutImplicit(xml,session); else if (gm.SType == GameManager.SessionType.Associate) WriteOutAssociate(xml,session); else if (gm.SType == GameManager.SessionType.Stopping) WriteOutStopping(xml,session); //Save the file in the correct spot if(completed){ NeuroLog.Debug("Saving log file: "+ Path.Combine(LogFilesPath, statsXML)); xml.Save(Path.Combine(LogFilesPath, statsXML)); } else{ NeuroLog.Debug("Saving unfinished log file: "+ Path.Combine(UnfinishedSessionPath, statsXML)); xml.Save(Path.Combine(UnfinishedSessionPath,statsXML)); } }
private void GenerateSitemapIndex() { string sSiteMapFilePath = HttpRuntime.AppDomainAppPath + "sitemap_index.xml"; if (!File.Exists(HttpRuntime.AppDomainAppPath + "sitemap_index.xml")) { List<SitemapInfo> items = MenuManagerDataController.GetSiteMapPages(GetUsername, GetCurrentCultureName); FileInfo fi = new FileInfo(sSiteMapFilePath); xd = new XmlDocument(); XmlNode rootNode = xd.CreateElement("urlset"); XmlAttribute attrXmlNS = xd.CreateAttribute("xmlns"); attrXmlNS.InnerText = "http://www.sitemaps.org/schemas/sitemap/0.9"; rootNode.Attributes.Append(attrXmlNS); XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8); rootNode.AppendChild(GenerateIndexNode(Page.Request.Url.Scheme + "://" + Request.Url.Authority + GetApplicationName + "/sitemap_" + GetPortalID + ".xml")); xd.AppendChild(rootNode); xd.InsertBefore(xd.CreateXmlDeclaration("1.0", "UTF-8", null), rootNode); xd.Save(sSiteMapFilePath); } else { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(HttpRuntime.AppDomainAppPath + "sitemap_index.xml"); XmlNode node = GenerateIndexNode(Page.Request.Url.Scheme + "://" + Request.Url.Authority + GetApplicationName + "/sitemap_" + GetPortalID + ".xml"); XmlNode childNode = xmlDoc.DocumentElement; childNode.InsertAfter(node, childNode.LastChild); xmlDoc.Save(sSiteMapFilePath); } }
private void GenerateSitemap() { if (!File.Exists(HttpRuntime.AppDomainAppPath + "sitemap_" + GetPortalID + ".xml")) { GenerateSitemapIndex(); } else { XmlDocument doc = new XmlDocument(); doc.Load(HttpRuntime.AppDomainAppPath + "sitemap_index.xml"); XmlNodeList nodeList = doc.GetElementsByTagName("lastmod"); foreach (XmlNode xmlNode in nodeList) { xmlNode.InnerText = DateTime.Now.ToString(); } } string sSiteMapFilePath = HttpRuntime.AppDomainAppPath + "sitemap_" + GetPortalID + ".xml"; List<SitemapInfo> items = MenuManagerDataController.GetSiteMapPages(GetUsername, GetCurrentCultureName); FileInfo fi = new FileInfo(sSiteMapFilePath); xd = new XmlDocument(); XmlNode rootNode = xd.CreateElement("urlset"); XmlAttribute attrXmlNS = xd.CreateAttribute("xmlns"); attrXmlNS.InnerText = "http://www.sitemaps.org/schemas/sitemap/0.9"; rootNode.Attributes.Append(attrXmlNS); ChangeFreuency = ddlChangeFrequency.SelectedItem.ToString(); PriorityValues = ddlPriorityValues.SelectedItem.ToString(); XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8); foreach (SitemapInfo info in items) { DateTime Updated; if (info.UpdatedOn == null || info.UpdatedOn == "") { Updated = DateTime.Parse(info.AddedOn); } else { Updated = DateTime.Parse(info.UpdatedOn); } //Valid option for changefreq:(always,hourly,daily,weekly,monthly,yearly,never) //Valid priority values have range interval [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]. string urlpath = info.PortalID > 1 ? string.Format("/portal/{0}{1}", info.PortalName, info.TabPath) : info.TabPath; rootNode.AppendChild(GenerateUrlNode(Page.Request.Url.Scheme + "://" + Request.Url.Authority + GetApplicationName + urlpath + SageFrameSettingKeys.PageExtension, Updated, ChangeFreuency, PriorityValues)); } xd.AppendChild(rootNode); xd.InsertBefore(xd.CreateXmlDeclaration("1.0", "UTF-8", null), rootNode); xd.Save(sSiteMapFilePath); }
public static void InsertAttributeNodeToAttributeNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root attr='value'/>"); var attribute = xmlDocument.CreateAttribute("attr"); Assert.Throws<InvalidOperationException>(() => xmlDocument.InsertBefore(attribute, null)); }
public XmlDocument GetXmlDoc() { XmlDocument doc = new XmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(xmlDeclaration, doc.DocumentElement); XmlElement root = GetXmlNode(doc); doc.AppendChild(root); return doc; }
// Test adding an element to the document. public void TestXmlDocumentAddElement() { XmlDocument doc = new XmlDocument(); // Add an element to the document. XmlElement element = doc.CreateElement("foo"); AssertNull("XmlElement (1)", element.ParentNode); AssertEquals("XmlElement (2)", doc, element.OwnerDocument); doc.AppendChild(element); AssertEquals("XmlElement (3)", doc, element.ParentNode); AssertEquals("XmlElement (4)", doc, element.OwnerDocument); // Try to add it again, which should fail this time. try { doc.AppendChild(element); Fail("adding XmlElement node twice"); } catch(InvalidOperationException) { // Success } try { doc.PrependChild(element); Fail("prepending XmlElement node twice"); } catch(InvalidOperationException) { // Success } // Adding an XmlDeclaration after should fail. XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", null, null); try { doc.AppendChild(decl); Fail("appending XmlDeclaration after XmlElement"); } catch(InvalidOperationException) { // Success } // But adding XmlDeclaration before should succeed. doc.PrependChild(decl); // Adding a document type after should fail. XmlDocumentType type = doc.CreateDocumentType("foo", null, null, null); try { doc.AppendChild(type); Fail("appending XmlDocumentType"); } catch(InvalidOperationException) { // Success } // Adding a document type before should succeed. doc.InsertBefore(type, element); }
// Test adding an XML declaration to the document. public void TestXmlDocumentAddXmlDeclaration() { XmlDocument doc = new XmlDocument(); // Add the declaration. XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", null, null); AssertNull("XmlDeclaration (1)", decl.ParentNode); AssertEquals("XmlDeclaration (2)", doc, decl.OwnerDocument); doc.AppendChild(decl); AssertEquals("XmlDeclaration (3)", doc, decl.ParentNode); AssertEquals("XmlDeclaration (4)", doc, decl.OwnerDocument); // Try to add it again, which should fail this time. try { doc.AppendChild(decl); Fail("adding XmlDeclaration node twice"); } catch(InvalidOperationException) { // Success } try { doc.PrependChild(decl); Fail("prepending XmlDeclaration node twice"); } catch(InvalidOperationException) { // Success } // Adding a document type before should fail. XmlDocumentType type = doc.CreateDocumentType("foo", null, null, null); try { doc.PrependChild(type); Fail("prepending XmlDocumentType"); } catch(InvalidOperationException) { // Success } // Adding a document type after should succeed. doc.AppendChild(type); // Adding an element before should fail. XmlElement element = doc.CreateElement("foo"); try { doc.PrependChild(element); Fail("prepending XmlElement"); } catch(InvalidOperationException) { // Success } // Adding the element between decl and type should fail. try { doc.InsertAfter(element, decl); Fail("inserting XmlElement between XmlDeclaration " + "and XmlDocumentType"); } catch(InvalidOperationException) { // Success } try { doc.InsertBefore(element, type); Fail("inserting XmlElement between XmlDeclaration " + "and XmlDocumentType (2)"); } catch(InvalidOperationException) { // Success } // Adding an element after should succeed. doc.AppendChild(element); }
protected void btnsave_Click(object sender, EventArgs e) { try { if (txtinv.Text != "") { DirectoryInfo di = new DirectoryInfo("C://Asset//NetworkData"); FileInfo[] fi = di.GetFiles(); bool statusFile; statusFile = false; int countfile = fi.GetLength(0); //int i = 0; //filenames = new string[countfile]; string currentfilename; string txtcurrentfilename; txtcurrentfilename = txtinv.Text + "."; foreach (FileInfo K in fi) { string[] fname = K.Name.Split(new char[] { 'x' }); currentfilename = fname[0].ToString(); if (currentfilename.Trim() == txtcurrentfilename.Trim()) { statusFile = true; } } if (!statusFile) { XmlDocument xd = new XmlDocument(); XmlDeclaration xdec = xd.CreateXmlDeclaration("1.0", "utf-8", null); xd.InsertBefore(xdec, xd.DocumentElement); XmlElement xeroot = xd.CreateElement("Devices"); xd.AppendChild(xeroot); string tempfilename; tempfilename = txtinv.Text + ".xml"; xd.Save("c://Asset//NetworkData//" + tempfilename); //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml(("<Device><Created_on>" + txtInvntDate.Text + "</Created_on> <Computer_name>" + txtdeviceName.Text + "</Computer_name><System> <Description>" + txtDesc.Text + "</Description><Up_time>" + txtuptime.Text + "</Up_time><Platform_ID>" + txtPlatform.Text + " </Platform_ID><Contact>" + txtContact.Text + "</Contact><Location>" + txtLocation.Text + "</Location></System><Ip_addresses><Ip_address><Ip_address>" + txtinv.Text + "</Ip_address></Ip_address></Ip_addresses></Device>")); //Save the document to a file. doc.Save("c://Asset//NetworkData//" + tempfilename); txtinv.Text = ""; txtInvntDate.Text = ""; txtdeviceName.Text = ""; txtDesc.Text = ""; txtuptime.Text = ""; txtPlatform.Text = ""; txtContact.Text = ""; txtLocation.Text = ""; } else { string myScript; myScript = "<script language=javascript>alert('Following IP Address already Exist,Enter different IP Address'); </script>"; Page.RegisterClientScriptBlock("MyScript", myScript); } } } catch (Exception ex) { string myScript; myScript = "<script language=javascript>alert('Exception - '" + ex + "');</script>"; Page.RegisterClientScriptBlock("MyScript", myScript); return; } }
public NewsRSS() { _rss = new XmlDocument(); XmlDeclaration xmlDeclaration = _rss.CreateXmlDeclaration("1.0", "utf-8", null); _rss.InsertBefore(xmlDeclaration, _rss.DocumentElement); XmlElement rssElement = _rss.CreateElement("rss"); XmlAttribute rssVersionAttribute = _rss.CreateAttribute("version"); rssVersionAttribute.InnerText = "2.0"; rssElement.Attributes.Append(rssVersionAttribute); _rss.AppendChild(rssElement); }
private XmlDocument DoGetXml() { XmlDocument doc = new XmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(xmlDeclaration, doc.DocumentElement); XmlElement fractal = doc.CreateElement("fractal"); fractal.SetAttribute("exponent", string.Format("{0:0.00}", m_paletteExponent)); fractal.SetAttribute("name", m_palette.Name); doc.AppendChild(fractal); XmlElement settings = m_settings.GetXmlNode(doc); fractal.AppendChild(settings); XmlElement palette = m_palette.GetXmlNode(doc); fractal.AppendChild(palette); return doc; }
/* Create New File */ private static void ResetScoresFile() { XmlDocument doc = new XmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", null); XmlNode rootNode = doc.CreateNode(XmlNodeType.Element, "LouGames", ""); doc.InsertBefore(xmlDeclaration, doc.DocumentElement); doc.AppendChild(rootNode); //Bejeweled XmlNode node = doc.ChildNodes[1].AppendChild(doc.CreateNode(XmlNodeType.Element, "Bejeweled", "")); XmlNode child, innerChild1, innerChild2; node = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "Scores", "")); child = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "SimpleScores", "")); int score = 8000; for (int i = 0; i < 10; i++) { innerChild1 = child.AppendChild(doc.CreateNode(XmlNodeType.Element, "Player", "")); innerChild2 = innerChild1.AppendChild(doc.CreateNode(XmlNodeType.Element, "Name", "")); innerChild2.InnerText = EncryptString("Bob McBoberson", encPassword); innerChild2 = innerChild1.AppendChild(doc.CreateNode(XmlNodeType.Element, "Score", "")); innerChild2.InnerText = EncryptString(score.ToString(), encPassword); score = score / 2; } child = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "TimedScores", "")); score = 8000; for (int i = 10; i < 20; i++) { innerChild1 = child.AppendChild(doc.CreateNode(XmlNodeType.Element, "Player", "")); innerChild2 = innerChild1.AppendChild(doc.CreateNode(XmlNodeType.Element, "Name", "")); innerChild2.InnerText = EncryptString("Bob McBoberson", encPassword); innerChild2 = innerChild1.AppendChild(doc.CreateNode(XmlNodeType.Element, "Score", "")); innerChild2.InnerText = EncryptString(score.ToString(), encPassword); score = score / 2; } //FreeCell node = doc.ChildNodes[1].AppendChild(doc.CreateNode(XmlNodeType.Element, "FreeCell", "")); node = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "Options", "")); child = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "AllowRightClick", "")); child.InnerText = EncryptString("True", encPassword); child = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "GamesPlayed", "")); child.InnerText = EncryptString("0", encPassword); child = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "GamesWon", "")); child.InnerText = EncryptString("0", encPassword); child = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "GamesLost", "")); child.InnerText = EncryptString("0", encPassword); child = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "GamesForfiet", "")); child.InnerText = EncryptString("0", encPassword); //Hearts node = doc.ChildNodes[1].AppendChild(doc.CreateNode(XmlNodeType.Element, "Hearts", "")); node = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "Names", "")); child = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "Computer1", "")); child.InnerText = EncryptString("Player1", encPassword); child = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "Computer2", "")); child.InnerText = EncryptString("Player2", encPassword); child = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "Computer3", "")); child.InnerText = EncryptString("Player3", encPassword); //Minesweeper node = doc.ChildNodes[1].AppendChild(doc.CreateNode(XmlNodeType.Element, "Minesweeper", "")); node = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "Times", "")); child = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "Beginner", "")); innerChild1 = child.AppendChild(doc.CreateNode(XmlNodeType.Element, "Time", "")); innerChild1.InnerText = EncryptString("9999", encPassword); innerChild1 = child.AppendChild(doc.CreateNode(XmlNodeType.Element, "Name", "")); innerChild1.InnerText = EncryptString("Anonymous", encPassword); child = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "Intermediate", "")); innerChild1 = child.AppendChild(doc.CreateNode(XmlNodeType.Element, "Time", "")); innerChild1.InnerText = EncryptString("9999", encPassword); innerChild1 = child.AppendChild(doc.CreateNode(XmlNodeType.Element, "Name", "")); innerChild1.InnerText = EncryptString("Anonymous", encPassword); child = node.AppendChild(doc.CreateNode(XmlNodeType.Element, "Expert", "")); innerChild1 = child.AppendChild(doc.CreateNode(XmlNodeType.Element, "Time", "")); innerChild1.InnerText = EncryptString("9999", encPassword); innerChild1 = child.AppendChild(doc.CreateNode(XmlNodeType.Element, "Name", "")); innerChild1.InnerText = EncryptString("Anonymous", encPassword); doc.Save(fileName); }
public void _createXml() { if (!Directory.Exists(rutaDir)) { Directory.CreateDirectory(rutaDir); } if (!File.Exists(rutaXml)) { XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlNode root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); configuration = doc.CreateElement(nodoPrincipal); doc.AppendChild(configuration); XmlElement servers = doc.CreateElement(String.Empty, "Servers", String.Empty); configuration.AppendChild(servers); XmlElement modems = doc.CreateElement(String.Empty, "Modems", String.Empty); configuration.AppendChild(modems); XmlElement udp = doc.CreateElement(String.Empty, "Udp", String.Empty); servers.AppendChild(udp); XmlElement tcp = doc.CreateElement(String.Empty, "Tcp", String.Empty); servers.AppendChild(tcp); XmlElement udpm = doc.CreateElement(String.Empty, "Udp", String.Empty); modems.AppendChild(udpm); XmlElement tcpm = doc.CreateElement(String.Empty, "Tcp", String.Empty); modems.AppendChild(tcpm); XmlElement udpClient = doc.CreateElement(String.Empty, "UdpClient", String.Empty); servers.SelectSingleNode("Udp").AppendChild(udpClient); XmlElement udpClientm = doc.CreateElement(String.Empty, "UdpClient", String.Empty); modems.SelectSingleNode("Udp").AppendChild(udpClientm); XmlElement udpServer = doc.CreateElement(String.Empty, "UdpServer", String.Empty); servers.SelectSingleNode("Udp").AppendChild(udpServer); XmlElement udpServerm = doc.CreateElement(String.Empty, "UdpServer", String.Empty); modems.SelectSingleNode("Udp").AppendChild(udpServerm); XmlElement tcpClient = doc.CreateElement(String.Empty, "TcpClient", String.Empty); servers.SelectSingleNode("Tcp").AppendChild(tcpClient); XmlElement tcpClientm = doc.CreateElement(String.Empty, "TcpClient", String.Empty); modems.SelectSingleNode("Tcp").AppendChild(tcpClientm); XmlElement tcpServer = doc.CreateElement(String.Empty, "TcpServer", String.Empty); servers.SelectSingleNode("Tcp").AppendChild(tcpServer); XmlElement tcpServerm = doc.CreateElement(String.Empty, "TcpServer", String.Empty); modems.SelectSingleNode("Tcp").AppendChild(tcpServerm); doc.Save(rutaXml); } }
/// <inheritdoc /> public override void Apply(XmlDocument document, string key) { // Set the evaluation context context["key"] = key; XPathExpression xpath = pathExpression.Clone(); xpath.SetContext(context); // Evaluate the path string path = document.CreateNavigator().Evaluate(xpath).ToString(); if (basePath != null) { path = Path.Combine(basePath, path); } string targetDirectory = Path.GetDirectoryName(path); if (!Directory.Exists(targetDirectory)) { Directory.CreateDirectory(targetDirectory); } if (writeXhtmlNamespace) { document.DocumentElement.SetAttribute("xmlns", "http://www.w3.org/1999/xhtml"); document.LoadXml(document.OuterXml); } if (settings.OutputMethod == XmlOutputMethod.Html) { XmlDocumentType documentType = document.CreateDocumentType("html", null, null, null); if (document.DocumentType != null) { document.ReplaceChild(documentType, document.DocumentType); } else { document.InsertBefore(documentType, document.FirstChild); } } // Save the document. // selectExpression determines which nodes get saved. If there is no selectExpression we simply // save the root node as before. If there is a selectExpression, we evaluate the XPath expression // and save the resulting node set. The select expression also enables the "literal-text" processing // instruction, which outputs its content as unescaped text. if (selectExpression == null) { try { using (XmlWriter writer = XmlWriter.Create(path, settings)) { document.Save(writer); } } catch (IOException e) { base.WriteMessage(key, MessageLevel.Error, "An access error occurred while attempting to " + "save to the file '{0}'. The error message is: {1}", path, e.GetExceptionMessage()); } catch (XmlException e) { base.WriteMessage(key, MessageLevel.Error, "Invalid XML was written to the output " + "file '{0}'. The error message is: '{1}'", path, e.GetExceptionMessage()); } } else { // IMPLEMENTATION NOTE: The separate StreamWriter is used to maintain XML indenting. Without it // the XmlWriter won't honor our indent settings after plain text nodes have been written. using (StreamWriter output = File.CreateText(path)) { using (XmlWriter writer = XmlWriter.Create(output, settings)) { XPathExpression select_xpath = selectExpression.Clone(); select_xpath.SetContext(context); XPathNodeIterator ni = document.CreateNavigator().Select(selectExpression); while (ni.MoveNext()) { if (ni.Current.NodeType == XPathNodeType.ProcessingInstruction && ni.Current.Name.Equals("literal-text")) { writer.Flush(); output.Write(ni.Current.Value); } else { ni.Current.WriteSubtree(writer); } } } } } // Raise an event to indicate that a file was created this.OnComponentEvent(new FileCreatedEventArgs(path, true)); }
/// <summary> /// 加声明头部 /// </summary> /// <param name="doc"></param> private static void AddDelaration(XmlDocument doc) { XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(decl, doc.DocumentElement); }
/// <summary> /// Saves the specified XML. /// </summary> /// <param name="xml">The XML.</param> /// <param name="path">The path.</param> /// <param name="xmlTagsUsed">The XML tags used.</param> public static void Save(StringBuilder xml, string path, IEnumerable <string> xmlTagsUsed) { if (File.Exists(path)) { var tags = xmlTagsUsed.ToList(); tags.AddRange(new[] { "MediaInfo", "ContentRating", "MPAARating", "certification", "Persons", "Type", "Overview", "CustomRating", "LocalTitle", "SortTitle", "PremiereDate", "EndDate", "Budget", "Revenue", "Rating", "ProductionYear", "Website", "AspectRatio", "Language", "RunningTime", "Runtime", "TagLine", "Taglines", "IMDB_ID", "IMDB", "IMDbId", "TMDbId", "TVcomId", "RottenTomatoesId", "MusicbrainzId", "TMDbCollectionId", "Genres", "Genre", "Studios", "Tags", "Added", "LockData", "Trailer", "CriticRating", "CriticRatingSummary", "GamesDbId", "BirthDate", "DeathDate", "LockedFields", "Chapters" }); var position = xml.ToString().LastIndexOf("</", StringComparison.OrdinalIgnoreCase); xml.Insert(position, GetCustomTags(path, tags)); } var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml.ToString()); //Add the new node to the document. xmlDocument.InsertBefore(xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", "yes"), xmlDocument.DocumentElement); var parentPath = Path.GetDirectoryName(path); if (!Directory.Exists(parentPath)) { Directory.CreateDirectory(parentPath); } var wasHidden = false; var file = new FileInfo(path); // This will fail if the file is hidden if (file.Exists) { if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) { file.Attributes &= ~FileAttributes.Hidden; wasHidden = true; } } using (var filestream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) { using (var streamWriter = new StreamWriter(filestream, Encoding.UTF8)) { xmlDocument.Save(streamWriter); } } if (wasHidden) { file.Refresh(); // Add back the attribute file.Attributes |= FileAttributes.Hidden; } }
public static XmlDocument Create() { try { XmlDocument doc = new XmlDocument(); //(1) the xml declaration is recommended, but not mandatory XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); //(2) string.Empty makes cleaner code XmlElement element1 = doc.CreateElement(string.Empty, "input", string.Empty); doc.AppendChild(element1); XmlElement element2 = doc.CreateElement(string.Empty, "qualitycontrol", string.Empty); element2.SetAttribute("type", "no"); element2.SetAttribute("losequantity", "0"); element2.SetAttribute("delay", "0"); element1.AppendChild(element2); XmlElement element3 = doc.CreateElement(string.Empty, "sellwish", string.Empty); for (int i = 0; i < sellwish.Count; i++) { XmlElement e = doc.CreateElement(string.Empty, "item", string.Empty); e.SetAttribute("article", sellwishname[i]); e.SetAttribute("quantity", sellwish[i]); element3.AppendChild(e); } element1.AppendChild(element3); XmlElement element4 = doc.CreateElement(string.Empty, "selldirect", string.Empty); for (int i = 0; i < 3; i++) { XmlElement e = doc.CreateElement(string.Empty, "item", string.Empty); e.SetAttribute("article", sellwishname[i]); e.SetAttribute("quantity", selldirectmenge[i]); e.SetAttribute("price", selldirektpreis[i]); e.SetAttribute("penalty", selldirektkonventional[i]); element4.AppendChild(e); } element1.AppendChild(element4); XmlElement element5 = doc.CreateElement(string.Empty, "orderlist", string.Empty); for (int i = 0; i < Database.neuebestellungen.Count; i++) { XmlElement e = doc.CreateElement(string.Empty, "order", string.Empty); e.SetAttribute("article", Database.neuebestellungen[i].article); e.SetAttribute("quantity", Database.neuebestellungen[i].amount); e.SetAttribute("modus", Database.neuebestellungen[i].modus); element5.AppendChild(e); } element1.AppendChild(element5); XmlElement element6 = doc.CreateElement(string.Empty, "productionlist", string.Empty); for (int i = 0; i < Database.fertigungsauftraege.Count; i++) { if (Database.fertigungsauftraege[i].amount != "") { if (Convert.ToInt32(Database.fertigungsauftraege[i].amount) > 0) { XmlElement e = doc.CreateElement(string.Empty, "production", string.Empty); e.SetAttribute("article", Database.fertigungsauftraege[i].id); e.SetAttribute("quantity", Database.fertigungsauftraege[i].amount); element6.AppendChild(e); } } } element1.AppendChild(element6); XmlElement element7 = doc.CreateElement(string.Empty, "workingtimelist", string.Empty); for (int i = 0; i < Database.arbeitsplaetze.Count; i++) { XmlElement e = doc.CreateElement(string.Empty, "workingtime", string.Empty); e.SetAttribute("station", Database.arbeitsplaetze[i].station); e.SetAttribute("shift", Database.arbeitsplaetze[i].shift); if (Convert.ToInt32(Database.arbeitsplaetze[i].overtime) < 0) { e.SetAttribute("overtime", "0"); } else { if (Database.arbeitsplaetze[i].shift == "3") { e.SetAttribute("overtime", "0"); } else { if (Convert.ToInt32(Database.arbeitsplaetze[i].overtime) >= 1200) { e.SetAttribute("overtime", "1200"); } else { e.SetAttribute("overtime", Database.arbeitsplaetze[i].overtime); } } } element7.AppendChild(e); } element1.AppendChild(element7); return(doc); } catch (Exception err) { throw err; } }
/// <summary> /// Save current configuration to the specified file. /// </summary> /// <param name="configFile">The config file to which the current configuration is written to.</param> public static void SaveConfig(string configFile) { if (File.Exists(configFile)) { try { File.Delete(configFile); } catch (Exception) { } } FileUtility.CompletePath(Path.GetDirectoryName(configFile), true); #region create basic xml info XmlDocument configXml = new XmlDocument(); XmlDeclaration declaration = configXml.CreateXmlDeclaration("1.0", "utf-8", null); XmlNode rootNode = configXml.CreateElement(ConfigurationConstants.Tags.ROOT_NODE); XmlAttribute version = configXml.CreateAttribute(ConfigurationConstants.Attrs.CONFIG_VERSION); version.Value = "1.0"; rootNode.Attributes.Append(version); #endregion #region Get Local Setting Info XmlNode localNode = configXml.CreateElement(ConfigurationConstants.Tags.LOCAL); foreach (var _ in GetConfigurationInstances()) { XmlNode entry = configXml.CreateElement(_.EntryName); foreach (var attribute in _.Instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) { entry.Attributes.Append(SetAttribute(configXml, attribute.Name, attribute.GetValue(_.Instance).ToString())); } localNode.AppendChild(entry); } rootNode.AppendChild(localNode); #endregion #region Get cluster config foreach (var cluster in s_clusterConfigurations) { XmlNode clusterNode = configXml.CreateElement(ConfigurationConstants.Tags.CLUSTER); if (cluster.Key != ConfigurationConstants.Tags.DEFAULT_CLUSTER) { clusterNode.Attributes.Append(SetAttribute(configXml, ConfigurationConstants.Attrs.ID, cluster.Key)); } var ags = new List <List <AvailabilityGroup> > { cluster.Value.Servers, cluster.Value.Proxies }; for (int i = 0; i < ags.Count; ++i) { foreach (var ag in ags[i]) { foreach (var server in ag.Instances) { XmlNode serverNode = configXml.CreateElement(c_builtInSectionNames[i]); serverNode.Attributes.Append(SetAttribute(configXml, ConfigurationConstants.Attrs.ENDPOINT, server.EndPoint.ToString())); if (server.AssemblyPath != null) { serverNode.Attributes.Append(SetAttribute(configXml, ConfigurationConstants.Attrs.ASSEMBLY_PATH, server.AssemblyPath)); } if (server.Id != null) { serverNode.Attributes.Append(SetAttribute(configXml, ConfigurationConstants.Attrs.AVAILABILITY_GROUP, server.Id)); } var instances = GetConfigurationInstances(); foreach (var entry in server) { var currentInstance = instances.Where(_ => _.EntryName == entry.Key).FirstOrDefault(); if (currentInstance != null) { XmlNode entryNode = configXml.CreateElement(entry.Value.Name); foreach (var setting in entry.Value.Settings) { if (setting.Value.Literal != null) { entryNode.Attributes.Append(SetAttribute(configXml, setting.Key, setting.Value.Literal)); } } if (entryNode.Attributes.Count > 0) { serverNode.AppendChild(entryNode); } } } clusterNode.AppendChild(serverNode); } } } rootNode.AppendChild(clusterNode); } #endregion configXml.AppendChild(rootNode); configXml.InsertBefore(declaration, configXml.DocumentElement); configXml.Save(configFile); }
/// <summary> /// 实体序列化为XML对象 /// </summary> /// <param name="package"></param> /// <returns></returns> private XmlDocument Serialize(package package) { var xmlDoc = new XmlDocument(); var xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); var root = xmlDoc.CreateElement("Package"); xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement); xmlDoc.AppendChild(root); var participantsNode = xmlDoc.CreateElement("Participants"); root.AppendChild(participantsNode); var workflowProcessNode = xmlDoc.CreateElement("WorkflowProcess"); root.AppendChild(workflowProcessNode); var processNode = xmlDoc.CreateElement("Process"); workflowProcessNode.AppendChild(processNode); //added participants list package.participants.ForEach((a) => { var pNode = xmlDoc.CreateElement("Participant"); pNode.SetAttribute("type", a.type); pNode.SetAttribute("id", a.id); pNode.SetAttribute("name", a.name); pNode.SetAttribute("code", a.code); pNode.SetAttribute("outerId", a.outerId.ToString()); participantsNode.AppendChild(pNode); }); //added process node var process = package.process; processNode.SetAttribute("id", process.id); processNode.SetAttribute("name", process.name); //added snodes var activitiesNode = xmlDoc.CreateElement("Activities"); processNode.AppendChild(activitiesNode); process.snodes.ForEach((a) => { var aNode = xmlDoc.CreateElement("Activity"); aNode.SetAttribute("name", a.name); aNode.SetAttribute("id", a.id); if (!string.IsNullOrEmpty(a.code)) { aNode.SetAttribute("code", a.code); } var activityTypeNode = xmlDoc.CreateElement("ActivityType"); activityTypeNode.SetAttribute("type", a.type); aNode.AppendChild(activityTypeNode); //added performers node var performersNode = xmlDoc.CreateElement("Performers"); a.performers.ForEach((p) => { var pNode = xmlDoc.CreateElement("Performer"); pNode.SetAttribute("id", p.id); performersNode.AppendChild(pNode); }); aNode.AppendChild(performersNode); //added geography node var geographyNode = xmlDoc.CreateElement("Geography"); aNode.AppendChild(geographyNode); //added widget node var widgetNode = xmlDoc.CreateElement("Widget"); widgetNode.SetAttribute("nodeId", a.nodeId.ToString()); widgetNode.SetAttribute("left", a.x.ToString()); widgetNode.SetAttribute("top", a.y.ToString()); widgetNode.SetAttribute("width", a.width.ToString()); widgetNode.SetAttribute("height", a.height.ToString()); //added connectors node var connectorsNode = xmlDoc.CreateElement("Connectors"); a.inputConnectors.ForEach((c1) => { var cNode = xmlDoc.CreateElement("Connector"); cNode.SetAttribute("type", c1.type); cNode.SetAttribute("index", c1.index.ToString()); cNode.SetAttribute("name", c1.name); connectorsNode.AppendChild(cNode); }); a.outputConnectors.ForEach((c2) => { var cNode = xmlDoc.CreateElement("Connector"); cNode.SetAttribute("type", c2.type); cNode.SetAttribute("index", c2.index.ToString()); cNode.SetAttribute("name", c2.name); connectorsNode.AppendChild(cNode); }); widgetNode.AppendChild(connectorsNode); geographyNode.AppendChild(widgetNode); activitiesNode.AppendChild(aNode); }); //added slines var transitionsNode = xmlDoc.CreateElement("Transitions"); processNode.AppendChild(transitionsNode); process.slines.ForEach((t) => { var tNode = xmlDoc.CreateElement("Transition"); tNode.SetAttribute("name", t.name); tNode.SetAttribute("id", t.id); tNode.SetAttribute("from", t.from); tNode.SetAttribute("to", t.to); var dNode = xmlDoc.CreateElement("Description"); tNode.AppendChild(dNode); var dtext = xmlDoc.CreateTextNode(t.Description); tNode.AppendChild(dtext); var geographyNode = xmlDoc.CreateElement("Geography"); tNode.AppendChild(geographyNode); var lineNode = xmlDoc.CreateElement("Line"); geographyNode.AppendChild(lineNode); lineNode.SetAttribute("fromNode", t.source.nodeId.ToString()); lineNode.SetAttribute("fromConnector", t.source.connectorIndex.ToString()); lineNode.SetAttribute("toNode", t.dest.nodeId.ToString()); lineNode.SetAttribute("toConnector", t.dest.connectorIndex.ToString()); transitionsNode.AppendChild(tNode); }); return(xmlDoc); }
public void Write_Computer_List(string[] filenames) { XmlDocument xd = new XmlDocument(); XmlDeclaration xdec = xd.CreateXmlDeclaration("1.0", "utf-8", null); xd.InsertBefore(xdec, xd.DocumentElement); XmlElement xeroot = xd.CreateElement("Computers"); xd.AppendChild(xeroot); foreach (string K in filenames) { string fname; fname = K.ToString(); //getSerialNo(fname); XmlElement xeComputer = xd.CreateElement("Computer"); xeroot.AppendChild(xeComputer); XmlAttribute xa = xd.CreateAttribute("Name"); xa.Value = K.ToString(); xeComputer.Attributes.Append(xa); } xd.Save(Server.MapPath("..//Files//Asset.xml")); //////////// Add by Vishal for Networking 05-06-2012 //XmlDocument xd1 = new XmlDocument(); //XmlDeclaration xdec1 = xd1.CreateXmlDeclaration("1.0", "utf-8", null); //xd1.InsertBefore(xdec1, xd1.DocumentElement); //XmlElement xeroot1 = xd1.CreateElement("Devices"); //xd1.AppendChild(xeroot1); //foreach (string K1 in filenames) //{ // string fname; // fname = K1.ToString(); // //getSerialNo(fname); // XmlElement xeComputer1 = xd1.CreateElement("Devices"); // xeroot1.AppendChild(xeComputer1); // XmlAttribute xa1 = xd1.CreateAttribute("Name"); // xa1.Value = K1.ToString(); // xeComputer1.Attributes.Append(xa1); //} //xd.Save(Server.MapPath("..//Files//Network.xml")); }
private void BuildExtensionXml() { var doc = new XmlDocument(); var xmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", null); var root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); var rootNode = doc.CreateElement("extension"); var xmlns = doc.CreateAttribute("xmlns"); xmlns.Value = "http://ns.adobe.com/air/extension/19.0"; rootNode.Attributes.Append(xmlns); doc.AppendChild(rootNode); XmlNode idNode = doc.CreateElement("id"); idNode.AppendChild(doc.CreateTextNode($"{GroupId}.{ArtifactId}")); rootNode.AppendChild(idNode); XmlNode nameNode = doc.CreateElement("name"); nameNode.AppendChild(doc.CreateTextNode($"{ArtifactId}")); rootNode.AppendChild(nameNode); XmlNode copyrightNode = doc.CreateElement("copyright"); rootNode.AppendChild(copyrightNode); var versionCleaned = Version.Replace("-android", ""); XmlNode versionNumberNode = doc.CreateElement("versionNumber"); versionNumberNode.AppendChild(doc.CreateTextNode($"{versionCleaned}")); rootNode.AppendChild(versionNumberNode); XmlNode platformsNode = doc.CreateElement("platforms"); foreach (var p in PlatformsList) { XmlNode platformNode = doc.CreateElement("platform"); var nameAttr = doc.CreateAttribute("name"); nameAttr.Value = p; platformNode.Attributes.Append(nameAttr); XmlNode applicationDeploymentNode = doc.CreateElement("applicationDeployment"); if (p != "default") { XmlNode nativeLibraryNode = doc.CreateElement("nativeLibrary"); nativeLibraryNode.AppendChild(doc.CreateTextNode("classes.jar")); applicationDeploymentNode.AppendChild(nativeLibraryNode); XmlNode initializerNode = doc.CreateElement("initializer"); initializerNode.AppendChild(doc.CreateTextNode("com.tuarua.DummyANE")); applicationDeploymentNode.AppendChild(initializerNode); XmlNode finalizerNode = doc.CreateElement("finalizer"); finalizerNode.AppendChild(doc.CreateTextNode("com.tuarua.DummyANE")); applicationDeploymentNode.AppendChild(finalizerNode); } platformNode.AppendChild(applicationDeploymentNode); platformsNode.AppendChild(platformNode); } rootNode.AppendChild(platformsNode); doc.Save($"{BuildDirectory}/extension.xml"); }
/// <summary> /// This method will create xml to specified directory /// Read the xml if already there to get paths /// If xml is newly created then promps to get path values /// if all path values are not found then also prompts to get that /// </summary> public static void createAndUpdateXmlForPathSettings(string xmlPath) { XmlDocument doc = new XmlDocument(); if (File.Exists(xmlPath)) { doc.Load(xmlPath); XmlNode rootNode = doc.FirstChild.NextSibling; XmlNodeList pushDirectory = doc.GetElementsByTagName("pushDirectory"); foreach (XmlNode nd in pushDirectory) { CommitWindow.pushDirectory = nd.InnerText; } if (CommitWindow.pushDirectory == "") { PathSettings pushPath = new PathSettings(); pushPath.Text = "Set Commit Directory"; pushPath.lblSettings.Text = "Set Commit Directory"; pushPath.ShowDialog(); if (!(CommitWindow.pushDirectory == "")) { writeTagXML(doc.DocumentElement, doc, xmlPath, "pushDirectory", CommitWindow.pushDirectory); } } XmlNodeList rootDirectory = doc.GetElementsByTagName("rootDirectory"); foreach (XmlNode nd in rootDirectory) { CommitWindow.rootDirectory = nd.InnerText; } if (CommitWindow.rootDirectory == "") { PathSettings rootPath = new PathSettings(); rootPath.Text = "Set Root Directory"; rootPath.lblSettings.Text = "Set Root Directory"; rootPath.ShowDialog(); if (!(CommitWindow.rootDirectory == "")) { writeTagXML(doc.DocumentElement, doc, xmlPath, "rootDirectory", CommitWindow.rootDirectory); } } XmlNodeList codeDirectory = doc.GetElementsByTagName("codeDirectory"); foreach (XmlNode nd in codeDirectory) { CommitWindow.codeDirectory = nd.InnerText; } if (CommitWindow.codeDirectory == "") { PathSettings codePath = new PathSettings(); codePath.Text = "Set Code Directory"; codePath.lblSettings.Text = "Set Code Directory"; codePath.ShowDialog(); if (!(CommitWindow.codeDirectory == "")) //user may close the enter directory form..and then it will return empty directory { writeTagXML(doc.DocumentElement, doc, xmlPath, "codeDirectory", CommitWindow.codeDirectory); } } XmlNodeList finalDirectoryForEncryption = doc.GetElementsByTagName("finalDirectoryForEncryption"); foreach (XmlNode nd in finalDirectoryForEncryption) { CommitWindow.finalDirectoryForEncryption = nd.InnerText; } if (CommitWindow.finalDirectoryForEncryption == "") { PathSettings Encryption = new PathSettings(); Encryption.Text = "Set Encryption Directory"; Encryption.lblSettings.Text = "Set Encryption Directory"; Encryption.ShowDialog(); if (!(CommitWindow.finalDirectoryForEncryption == "")) //user may close the enter directory form..and then it will return empty directory { writeTagXML(doc.DocumentElement, doc, xmlPath, "finalDirectoryForEncryption", CommitWindow.finalDirectoryForEncryption); } } XmlNodeList emergencyDirectory = doc.GetElementsByTagName("emergencyDirectory"); foreach (XmlNode nd in emergencyDirectory) { CommitWindow.emergencyDirectory = nd.InnerText; } if (CommitWindow.emergencyDirectory == "") { PathSettings Emergency = new PathSettings(); Emergency.Text = "Set Emergency Directory"; Emergency.lblSettings.Text = "Set Emergency Directory"; Emergency.ShowDialog(); if (!(CommitWindow.emergencyDirectory == "")) //user may close the enter directory form..and then it will return empty directory { writeTagXML(doc.DocumentElement, doc, xmlPath, "emergencyDirectory", CommitWindow.emergencyDirectory); } } } else { //(1) the xml declaration is recommended, but not mandatory XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); XmlElement rootNode = doc.CreateElement(string.Empty, "root", string.Empty); doc.AppendChild(rootNode); //doc.Save(xmlPath); if (CommitWindow.pushDirectory == "") { PathSettings pushPath = new PathSettings(); pushPath.Text = "Set Commit Directory"; pushPath.lblSettings.Text = "Set Commit Directory"; pushPath.ShowDialog(); if (!(CommitWindow.pushDirectory == "")) //user may close the enter directory form..and then it will return empty directory { writeTagXML(rootNode, doc, xmlPath, "pushDirectory", CommitWindow.pushDirectory); } } if (CommitWindow.rootDirectory == "") { PathSettings rootPath = new PathSettings(); rootPath.Text = "Set Root Directory"; rootPath.lblSettings.Text = "Set Root Directory"; rootPath.ShowDialog(); if (!(CommitWindow.rootDirectory == "")) //user may close the enter directory form..and then it will return empty directory { writeTagXML(rootNode, doc, xmlPath, "rootDirectory", CommitWindow.rootDirectory); } } if (CommitWindow.codeDirectory == "") { PathSettings codePath = new PathSettings(); codePath.Text = "Set Code Directory"; codePath.lblSettings.Text = "Set Code Directory"; codePath.ShowDialog(); if (!(CommitWindow.codeDirectory == "")) //user may close the enter directory form..and then it will return empty directory { writeTagXML(rootNode, doc, xmlPath, "codeDirectory", CommitWindow.codeDirectory); } } if (CommitWindow.finalDirectoryForEncryption == "") { PathSettings Encryption = new PathSettings(); Encryption.Text = "Set Encryption Directory"; Encryption.lblSettings.Text = "Set Encryption Directory"; Encryption.ShowDialog(); if (!(CommitWindow.finalDirectoryForEncryption == "")) //user may close the enter directory form..and then it will return empty directory { writeTagXML(rootNode, doc, xmlPath, "finalDirectoryForEncryption", CommitWindow.finalDirectoryForEncryption); } } //The pupose of this emergency directory is to commit on emergency directory to get the function immidiately if (CommitWindow.emergencyDirectory == "") { PathSettings Emergency = new PathSettings(); Emergency.Text = "Set Emergency Directory"; Emergency.lblSettings.Text = "Set Emergency Directory"; Emergency.ShowDialog(); if (!(CommitWindow.emergencyDirectory == "")) //user may close the enter directory form..and then it will return empty directory { writeTagXML(doc.DocumentElement, doc, xmlPath, "emergencyDirectory", CommitWindow.emergencyDirectory); } } } }
// Methods internal override void Apply(XmlNode parent, ref XmlNode currentPosition) { XmlNode newNode = null; if (_nodeType == XmlNodeType.Attribute) { Debug.Assert(_name != string.Empty); if (_prefix == "xmlns") { newNode = parent.OwnerDocument.CreateAttribute(_prefix + ":" + _name); } else if (_prefix == "" && _name == "xmlns") { newNode = parent.OwnerDocument.CreateAttribute(_name); } else { newNode = parent.OwnerDocument.CreateAttribute(_prefix, _name, _ns); } ((XmlAttribute)newNode).Value = _value; Debug.Assert(currentPosition == null); parent.Attributes.Append((XmlAttribute)newNode); } else { switch (_nodeType) { case XmlNodeType.Element: Debug.Assert(_name != string.Empty); Debug.Assert(_value == string.Empty); newNode = parent.OwnerDocument.CreateElement(_prefix, _name, _ns); ApplyChildren(newNode); break; case XmlNodeType.Text: Debug.Assert(_value != string.Empty); newNode = parent.OwnerDocument.CreateTextNode(_value); break; case XmlNodeType.CDATA: Debug.Assert(_value != string.Empty); newNode = parent.OwnerDocument.CreateCDataSection(_value); break; case XmlNodeType.Comment: Debug.Assert(_value != string.Empty); newNode = parent.OwnerDocument.CreateComment(_value); break; case XmlNodeType.ProcessingInstruction: Debug.Assert(_value != string.Empty); Debug.Assert(_name != string.Empty); newNode = parent.OwnerDocument.CreateProcessingInstruction(_name, _value); break; case XmlNodeType.EntityReference: #if NETCORE throw new NotSupportedException("XmlNodeType.EntityReference is not supported"); #else Debug.Assert(_name != string.Empty); newNode = parent.OwnerDocument.CreateEntityReference(_name); break; #endif case XmlNodeType.XmlDeclaration: { Debug.Assert(_value != string.Empty); XmlDocument doc = parent.OwnerDocument; XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", string.Empty, string.Empty); decl.Value = _value; doc.InsertBefore(decl, doc.FirstChild); return; } case XmlNodeType.DocumentType: { #if NETCORE throw new NotSupportedException("XmlNodeType.DocumentType is not supported"); #else XmlDocument doc = parent.OwnerDocument; if (_prefix == string.Empty) { _prefix = null; } if (_ns == string.Empty) { _ns = null; } XmlDocumentType docType = doc.CreateDocumentType(_name, _prefix, _ns, _value); if (doc.FirstChild.NodeType == XmlNodeType.XmlDeclaration) { doc.InsertAfter(docType, doc.FirstChild); } else { doc.InsertBefore(docType, doc.FirstChild); } return; #endif } default: Debug.Assert(false); break; } Debug.Assert(currentPosition == null || currentPosition.NodeType != XmlNodeType.Attribute); if (_ignoreChildOrder) { parent.AppendChild(newNode); } else { parent.InsertAfter(newNode, currentPosition); } currentPosition = newNode; } }
/// <summary> /// /// </summary> /// <param name="inputPath"></param> /// <param name="outputPath"></param> /// <param name="pass"></param> /// <param name="xcert"></param> /// <param name="flag"></param> /// <param name="oneTimePassword"></param> public void ProcessInputKeyFile(string inputPath, string outputPath, string pass, X509Certificate2 xcert, bool flag, string oneTimePassword) { string strKey = string.Format("//{0}/{1}", CollectionIDTag, KeyTag); string strID = string.Format("//{0}/{1}", CollectionIDTag, iFolderIDTag); string decKey; byte[] decKeyByteArray; rsadec = xcert.PrivateKey as RSACryptoServiceProvider; try { string inKeyPath = Path.GetFullPath(inputPath); string outKeyPath = Path.GetFullPath(outputPath); XmlDocument encFile = new XmlDocument(); encFile.Load(inKeyPath); XmlNodeList keyNodeList, idNodeList; XmlElement root = encFile.DocumentElement; keyNodeList = root.SelectNodes(strKey); idNodeList = root.SelectNodes(strID); System.Xml.XmlDocument document = new XmlDocument(); XmlDeclaration xmlDeclaration = document.CreateXmlDeclaration("1.0", "utf-8", null); document.InsertBefore(xmlDeclaration, document.DocumentElement); XmlElement title = document.CreateElement(titleTag); document.AppendChild(title); int i = 0; foreach (XmlNode idNode in idNodeList) { if (idNode.InnerText == null || idNode.InnerText == String.Empty) { continue; } Console.WriteLine(idNode.InnerText); XmlNode newNode = document.CreateNode("element", CollectionIDTag, ""); newNode.InnerText = ""; document.DocumentElement.AppendChild(newNode); XmlNode innerNode = document.CreateNode("element", iFolderIDTag, ""); innerNode.InnerText = idNode.InnerText; newNode.AppendChild(innerNode); { XmlNode keyNode = keyNodeList[i++]; Console.WriteLine(decKey = keyNode.InnerText); decKeyByteArray = Convert.FromBase64String(decKey); XmlNode newElem2 = document.CreateNode("element", KeyTag, ""); if (decKey == null || decKey == String.Empty) { continue; } if (flag == true) { newElem2.InnerText = DecodeMessage(decKeyByteArray, oneTimePassword); } else { newElem2.InnerText = DecodeMessage(decKeyByteArray); } newNode.AppendChild(newElem2); } } if (File.Exists(outKeyPath)) { File.Delete(outKeyPath); } document.Save(outKeyPath); } catch (Exception e) { throw new Exception("Exception while processing in Process inputkey file" + e.Message + e.StackTrace); } }
// This function generates the XML request body // for the Sync request. protected override void GenerateXMLPayload() { // If WBXML was explicitly set, use that if (WbxmlBytes != null) { return; } // Otherwise, use the properties to build the XML and then WBXML encode it XmlDocument syncXML = new XmlDocument(); XmlDeclaration xmlDeclaration = syncXML.CreateXmlDeclaration("1.0", "utf-8", null); syncXML.InsertBefore(xmlDeclaration, null); XmlNode syncNode = syncXML.CreateElement(Xmlns.airSyncXmlns, "Sync", Namespaces.airSyncNamespace); syncNode.Prefix = Xmlns.airSyncXmlns; syncXML.AppendChild(syncNode); // Only add a collections node if there are folders in the request. // If omitting, there should be a Partial element. if (folderList.Count == 0 && isPartial == false) { throw new ArgumentException( "Sync requests must specify collections or include the Partial element."); } if (folderList.Count > 0) { XmlNode collectionsNode = syncXML.CreateElement(Xmlns.airSyncXmlns, "Collections", Namespaces.airSyncNamespace); collectionsNode.Prefix = Xmlns.airSyncXmlns; syncNode.AppendChild(collectionsNode); foreach (Folder folder in folderList) { XmlNode collectionNode = syncXML.CreateElement(Xmlns.airSyncXmlns, "Collection", Namespaces.airSyncNamespace); collectionNode.Prefix = Xmlns.airSyncXmlns; collectionsNode.AppendChild(collectionNode); XmlNode syncKeyNode = syncXML.CreateElement(Xmlns.airSyncXmlns, "SyncKey", Namespaces.airSyncNamespace); syncKeyNode.Prefix = Xmlns.airSyncXmlns; syncKeyNode.InnerText = folder.SyncKey; collectionNode.AppendChild(syncKeyNode); XmlNode collectionIdNode = syncXML.CreateElement(Xmlns.airSyncXmlns, "CollectionId", Namespaces.airSyncNamespace); collectionIdNode.Prefix = Xmlns.airSyncXmlns; collectionIdNode.InnerText = folder.Id; collectionNode.AppendChild(collectionIdNode); // To override "ghosting", you must include a Supported element here. // This only applies to calendar items and contacts // NOT IMPLEMENTED // If folder is set to permanently delete items, then add a DeletesAsMoves // element here and set it to false. // Otherwise, omit. Per MS-ASCMD, the absence of this element is the same as true. if (folder.AreDeletesPermanent == true) { XmlNode deletesAsMovesNode = syncXML.CreateElement(Xmlns.airSyncXmlns, "DeletesAsMoves", Namespaces.airSyncNamespace); deletesAsMovesNode.Prefix = Xmlns.airSyncXmlns; deletesAsMovesNode.InnerText = "0"; collectionNode.AppendChild(deletesAsMovesNode); } // In almost all cases the GetChanges element can be omitted. // It only makes sense to use it if SyncKey != 0 and you don't want // changes from the server for some reason. if (folder.AreChangesIgnored == true) { XmlNode getChangesNode = syncXML.CreateElement(Xmlns.airSyncXmlns, "GetChanges", Namespaces.airSyncNamespace); getChangesNode.Prefix = Xmlns.airSyncXmlns; getChangesNode.InnerText = "0"; collectionNode.AppendChild(getChangesNode); } // If there's a folder-level window size, include it if (folder.WindowSize > 0) { XmlNode folderWindowSizeNode = syncXML.CreateElement(Xmlns.airSyncXmlns, "WindowSize", Namespaces.airSyncNamespace); folderWindowSizeNode.Prefix = Xmlns.airSyncXmlns; folderWindowSizeNode.InnerText = folder.WindowSize.ToString(); collectionNode.AppendChild(folderWindowSizeNode); } // If the folder is set to conversation mode, specify that if (folder.UseConversationMode == true) { XmlNode conversationModeNode = syncXML.CreateElement(Xmlns.airSyncXmlns, "ConversationMode", Namespaces.airSyncNamespace); conversationModeNode.Prefix = Xmlns.airSyncXmlns; conversationModeNode.InnerText = "1"; collectionNode.AppendChild(conversationModeNode); } // Include sync options for the folder // Note that you can include two Options elements, but the 2nd one is for SMS // SMS is not implemented at this time, so we'll only include one. if (folder.Options != null) { folder.GenerateOptionsXml(collectionNode); } // Include client-side changes // TODO: Implement client side changes on the Folder object //if (folder.Commands != null) //{ // folder.GenerateCommandsXml(collectionNode); //} } } // If a wait period was specified, include it here if (wait > 0) { XmlNode waitNode = syncXML.CreateElement(Xmlns.airSyncXmlns, "Wait", Namespaces.airSyncNamespace); waitNode.Prefix = Xmlns.airSyncXmlns; waitNode.InnerText = wait.ToString(); syncNode.AppendChild(waitNode); } // If a heartbeat interval period was specified, include it here if (heartBeatInterval > 0) { XmlNode heartBeatIntervalNode = syncXML.CreateElement(Xmlns.airSyncXmlns, "HeartbeatInterval", Namespaces.airSyncNamespace); heartBeatIntervalNode.Prefix = Xmlns.airSyncXmlns; heartBeatIntervalNode.InnerText = heartBeatInterval.ToString(); syncNode.AppendChild(heartBeatIntervalNode); } // If a windows size was specified, include it here if (windowSize > 0) { XmlNode windowSizeNode = syncXML.CreateElement(Xmlns.airSyncXmlns, "WindowSize", Namespaces.airSyncNamespace); windowSizeNode.Prefix = Xmlns.airSyncXmlns; windowSizeNode.InnerText = windowSize.ToString(); syncNode.AppendChild(windowSizeNode); } // If this request contains a partial list of collections, include the Partial element if (isPartial == true) { XmlNode partialNode = syncXML.CreateElement(Xmlns.airSyncXmlns, "Partial", Namespaces.airSyncNamespace); partialNode.Prefix = Xmlns.airSyncXmlns; syncNode.AppendChild(partialNode); } StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter); xmlWriter.Formatting = Formatting.Indented; syncXML.WriteTo(xmlWriter); xmlWriter.Flush(); XmlString = stringWriter.ToString(); }
public Stream Save(Stream stream) { XmlDocument doc = new XmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); XmlElement CrossIndustryDocument = doc.CreateElement("rsm", "CrossIndustryDocument", rsm); CrossIndustryDocument.SetAttribute("xmlns:xsi", xsi); CrossIndustryDocument.SetAttribute("xmlns:rsm", rsm); CrossIndustryDocument.SetAttribute("xmlns:udt", udt); CrossIndustryDocument.SetAttribute("xmlns:ram", ram); XmlElement specifiedExchangedDocument = doc.CreateElement("rsm", "SpecifiedExchangedDocumentContext", rsm); XmlElement TestIndicator = doc.CreateElement("ram", "TestIndicator", ram); XmlElement Indicator = doc.CreateElement("udt", "Indicator", udt); Indicator.InnerText = "true"; TestIndicator.AppendChild(Indicator); specifiedExchangedDocument.AppendChild(TestIndicator); XmlElement guidelineSpecifiedDocument = doc.CreateElement("ram", "GuidelineSpecifiedDocumentContextParameter", ram); XmlElement id = doc.CreateElement("ram", "ID", ram); id.InnerText = "urn:ferd:CrossIndustryDocument:invoice:1p0:" + Profile.ToString(); guidelineSpecifiedDocument.AppendChild(id); specifiedExchangedDocument.AppendChild(guidelineSpecifiedDocument); CrossIndustryDocument.AppendChild(specifiedExchangedDocument); XmlElement headerExchangeDocument = WriteHeaderExchangeDocument(doc); XmlElement SpecifiedSupplyChainTradeTransaction = doc.CreateElement("rsm", "SpecifiedSupplyChainTradeTransaction", rsm); XmlElement ApplicableSupplyChainTradeAgreement = doc.CreateElement("ram", "ApplicableSupplyChainTradeAgreement", ram); XmlElement SellerTradeParty = WriteUserDetails(doc, "SellerTradeParty", Seller); XmlElement BuyerTradeParty = WriteUserDetails(doc, "BuyerTradeParty", Buyer); ApplicableSupplyChainTradeAgreement.AppendChild(SellerTradeParty); ApplicableSupplyChainTradeAgreement.AppendChild(BuyerTradeParty); SpecifiedSupplyChainTradeTransaction.AppendChild(ApplicableSupplyChainTradeAgreement); XmlElement ApplicableSupplyChainTradeSettlement = doc.CreateElement("ram", "ApplicableSupplyChainTradeSettlement", ram); XmlElement InvoiceCurrencyCode = doc.CreateElement("ram", "InvoiceCurrencyCode", ram); InvoiceCurrencyCode.InnerText = Currency.ToString("g"); ApplicableSupplyChainTradeSettlement.AppendChild(InvoiceCurrencyCode); XmlElement SpecifiedTradeSettlementMonetarySummation = doc.CreateElement("ram", "SpecifiedTradeSettlementMonetarySummation", ram); XmlElement GrandTotalAmount = doc.CreateElement("ram", "GrandTotalAmount", ram); GrandTotalAmount.InnerText = TotalAmount.ToString(); SpecifiedTradeSettlementMonetarySummation.AppendChild(GrandTotalAmount); ApplicableSupplyChainTradeSettlement.AppendChild(SpecifiedTradeSettlementMonetarySummation); SpecifiedSupplyChainTradeTransaction.AppendChild(ApplicableSupplyChainTradeSettlement); XmlElement LineItem = AddTradeLineItems(doc); SpecifiedSupplyChainTradeTransaction.AppendChild(LineItem); CrossIndustryDocument.AppendChild(headerExchangeDocument); CrossIndustryDocument.AppendChild(SpecifiedSupplyChainTradeTransaction); doc.AppendChild(CrossIndustryDocument); doc.Save(stream); stream.Position = 0; return(stream); }
private static void Main(string[] args) { if (args.Length > 0) { if (args[0] == "?") { Console.WriteLine("Argument expected: XML File Path."); Console.WriteLine("Example: "); Console.WriteLine(" HdHomeRunEpgXml " + '"' + "hdEpg.xml" + '"'); Console.WriteLine(" HdHomeRunEpgXml " + '"' + "C:\\hdEpg.xml" + '"'); Console.WriteLine(""); Console.WriteLine("You can also specify the device."); Console.WriteLine(" HdHomeRunEpgXml " + '"' + "C:\\hdEpg.xml" + '"' + " <DeviceID>"); } } if (args.Length == 0) { Console.WriteLine("Argument expected: XML File Path."); Console.WriteLine("Example: "); Console.WriteLine(" HdHomeRunEpgXml " + '"' + "hdEpg.xml" + '"'); Console.WriteLine(" HdHomeRunEpgXml " + '"' + "C:\\hdEpg.xml" + '"'); Console.WriteLine(""); Console.WriteLine("Press enter to exit."); Console.ReadLine(); return; } DownloadImdb(); DownloadImdbRatings(); string selectedDevice = null; if (args.Length == 2) { selectedDevice = args[1]; } IpAddressFinder.PrintLocalIPAddress(); var tvShows = new List <XmlElement>(); var doc = new XmlDocument(); var xmlDeclaration = doc.CreateXmlDeclaration("1.0", "ISO-8859-1", null); var root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); var eleTv = doc.CreateElement(string.Empty, "tv", string.Empty); doc.AppendChild(eleTv); var processedChannel = new List <string>(); //Fetch the devices registered. List <HdConnectDevice> devices = null; try { devices = JsonCalls.GetHdConnectDevices(); } catch (Exception e) { Console.WriteLine("!!!!!It appears you do not have any HdHomeRun devices.!!!!!"); Console.WriteLine("Press <enter> to exit"); Console.ReadLine(); Environment.Exit(0); } if (devices == null) { Console.WriteLine("Devices are null! Can't find recievers."); } else { try { //For Each device. foreach (var device in devices) { if (selectedDevice != null) { if (!selectedDevice.Trim().Equals(device.DeviceID.Trim(), StringComparison.InvariantCultureIgnoreCase)) { continue; } } Console.WriteLine("Processing Device: " + device.DeviceID); //Get the Auth info var discover = device.GetHdConnectDiscover(); //Get the channels var channels = discover.GetHdConnectChannels(); //For each channel foreach (var channel in channels) { //If we already processed this channel, then skip if (processedChannel.Contains(channel.GuideNumber)) { continue; } //Process the channel processedChannel.Add(channel.GuideNumber); //Add the tv shows tvShows.AddRange(doc.ProcessChannel(eleTv, channel, discover.DeviceAuth)); } } } catch (Exception e) { Console.WriteLine("Error processing devices."); Console.WriteLine(e); } } //Append the shows to the list foreach (var element in tvShows) { eleTv.AppendChild(element); } try { //Save the file doc.Save(args[0]); } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine("Finished."); Console.WriteLine("Epg file saved to: " + args[0]); }
private void BuildPlatformXml() { var doc = new XmlDocument(); var xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); var root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); var rootNode = doc.CreateElement("platform"); var xmlns = doc.CreateAttribute("xmlns"); xmlns.Value = "http://ns.adobe.com/air/extension/19.0"; rootNode.Attributes.Append(xmlns); doc.AppendChild(rootNode); XmlNode packagedDependenciesNode = doc.CreateElement("packagedDependencies"); // rootJar XmlNode baseJarNode = doc.CreateElement("packagedDependency"); baseJarNode.AppendChild(doc.CreateTextNode($"{GroupId}-{ArtifactId}-{Version}.jar")); packagedDependenciesNode.AppendChild(baseJarNode); XmlNode packagedResourcesNode = doc.CreateElement("packagedResources"); if (HasResources) { XmlNode resourceNode = doc.CreateElement("packagedResource"); XmlNode packageNameNode = doc.CreateElement("packageName"); XmlNode folderNameNode = doc.CreateElement("folderName"); packageNameNode.AppendChild(doc.CreateTextNode($"{GroupId}")); folderNameNode.AppendChild(doc.CreateTextNode($"{GroupId}-{ArtifactId}-{Version}-res")); resourceNode.AppendChild(packageNameNode); resourceNode.AppendChild(folderNameNode); packagedResourcesNode.AppendChild(resourceNode); } foreach (var dependency in _dependencies) { XmlNode dependencyJarNode = doc.CreateElement("packagedDependency"); dependencyJarNode.AppendChild( doc.CreateTextNode($"{dependency.GroupId}-{dependency.ArtifactId}-{dependency.Version}.jar")); packagedDependenciesNode.AppendChild(dependencyJarNode); if (!dependency.HasResources) { continue; } XmlNode resourceNode = doc.CreateElement("packagedResource"); XmlNode packageNameNode = doc.CreateElement("packageName"); XmlNode folderNameNode = doc.CreateElement("folderName"); packageNameNode.AppendChild(dependency.PackageName != null ? doc.CreateTextNode($"{dependency.PackageName}") : doc.CreateTextNode($"{dependency.GroupId}-{dependency.ArtifactId}")); folderNameNode.AppendChild( doc.CreateTextNode($"{dependency.GroupId}-{dependency.ArtifactId}-{dependency.Version}-res")); resourceNode.AppendChild(packageNameNode); resourceNode.AppendChild(folderNameNode); packagedResourcesNode.AppendChild(resourceNode); } rootNode.AppendChild(packagedDependenciesNode); if (packagedResourcesNode.HasChildNodes) { rootNode.AppendChild(packagedResourcesNode); } doc.Save($"{BuildDirectory}/platforms/android/platform.xml"); }
private void WriteToHQN(string ClientMacAddress, string ControlName, string ControlState, string ComputerGroup) { //create the XML based on LC0095-001 XmlDocument HQNFile = new XmlDocument(); XmlDeclaration xmlDeclaration = HQNFile.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = HQNFile.DocumentElement; HQNFile.InsertBefore(xmlDeclaration, root); //create the root element XmlElement rootElement = HQNFile.CreateElement(string.Empty, "hqn", string.Empty); HQNFile.AppendChild(rootElement); //create the event element XmlElement eventElement = HQNFile.CreateElement(string.Empty, "event", string.Empty); rootElement.AppendChild(eventElement); //Create the event id by converting the dateTime to int32 //XmlElement eventIdElement = HQNFile.CreateElement(string.Empty, "event_id", string.Empty); //eventIdElement.AppendChild(HQNFile.CreateTextNode(unchecked((int)DateTime.Now.Ticks).ToString())); //eventElement.AppendChild(eventIdElement); //Write the date XmlElement dateTimeElement = HQNFile.CreateElement(string.Empty, "date_time", string.Empty); dateTimeElement.AppendChild(HQNFile.CreateTextNode(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"))); eventElement.AppendChild(dateTimeElement); //Write the computer group as client, e.g. HS1/FRx FAT, line 1, etc. //maybe in the future add a hook to specify a controller from the group XmlElement clientElement = HQNFile.CreateElement(string.Empty, "client", string.Empty); clientElement.AppendChild(HQNFile.CreateTextNode(ComputerGroup)); eventElement.AppendChild(clientElement); //Write a web.config entry for supplier XmlElement supplierElement = HQNFile.CreateElement(string.Empty, "supplier", string.Empty); supplierElement.AppendChild(HQNFile.CreateTextNode(ConfigurationManager.AppSettings["HQNSupplier"])); eventElement.AppendChild(supplierElement); //Write a web.config entry for product. Product has no meaning in this context XmlElement productElement = HQNFile.CreateElement(string.Empty, "product", string.Empty); productElement.AppendChild(HQNFile.CreateTextNode(ConfigurationManager.AppSettings["HQNProduct"])); eventElement.AppendChild(productElement); //Write the process name XmlElement processElement = HQNFile.CreateElement(string.Empty, "process", string.Empty); processElement.AppendChild(HQNFile.CreateTextNode("Andon Monitor")); eventElement.AppendChild(processElement); //Write an empty string for serial number as a default XmlElement serialNumberElement = HQNFile.CreateElement(string.Empty, "serial_number", string.Empty); serialNumberElement.AppendChild(HQNFile.CreateTextNode(ComputerGroup)); eventElement.AppendChild(serialNumberElement); //write True final status as a default XmlElement finalStatusElement = HQNFile.CreateElement(string.Empty, "final_status", string.Empty); finalStatusElement.AppendChild(HQNFile.CreateTextNode("True")); eventElement.AppendChild(finalStatusElement); //<creation_date>5/1/2015 5:35:40 PM</creation_date> ////Write the date //XmlElement creationDateTimeElement = HQNFile.CreateElement(string.Empty, "creation_date", string.Empty); ////re-use dateTimeElement //eventElement.AppendChild(dateTimeElement); ////<file_created>False</file_created> ////write True final status as a default //XmlElement fileCreatedElement = HQNFile.CreateElement(string.Empty, "file_created", string.Empty); //fileCreatedElement.AppendChild(HQNFile.CreateTextNode("True")); //eventElement.AppendChild(fileCreatedElement); //create the first attribute element for the control name XmlElement attributeElementControl = HQNFile.CreateElement(string.Empty, "attribute", string.Empty); rootElement.AppendChild(attributeElementControl); //write the control name XmlElement attributeNameElementControlName = HQNFile.CreateElement(string.Empty, "attr_name", string.Empty); attributeNameElementControlName.AppendChild(HQNFile.CreateTextNode(ControlName)); attributeElementControl.AppendChild(attributeNameElementControlName); //write the control state XmlElement attributeNameElementControlState = HQNFile.CreateElement(string.Empty, "attr_value", string.Empty); attributeNameElementControlState.AppendChild(HQNFile.CreateTextNode(ControlState)); attributeElementControl.AppendChild(attributeNameElementControlState); //create the second attribute element for the mac address of the controller (client) XmlElement attributeElementMACAddress = HQNFile.CreateElement(string.Empty, "attribute", string.Empty); rootElement.AppendChild(attributeElementMACAddress); //write a mac address attribute XmlElement attributeNameElementMacName = HQNFile.CreateElement(string.Empty, "attr_name", string.Empty); attributeNameElementMacName.AppendChild(HQNFile.CreateTextNode("MAC address")); attributeElementMACAddress.AppendChild(attributeNameElementMacName); //write the client mac address as the value XmlElement attributeNameElementMacValue = HQNFile.CreateElement(string.Empty, "attr_value", string.Empty); attributeNameElementMacValue.AppendChild(HQNFile.CreateTextNode(ClientMacAddress)); attributeElementMACAddress.AppendChild(attributeNameElementMacValue); //create the second attribute element for the mac address of the controller (client) XmlElement attributeElementGuid = HQNFile.CreateElement(string.Empty, "attribute", string.Empty); rootElement.AppendChild(attributeElementGuid); //write a mac address attribute XmlElement attributeNameElementGuidName = HQNFile.CreateElement(string.Empty, "attr_name", string.Empty); attributeNameElementGuidName.AppendChild(HQNFile.CreateTextNode("GUID")); attributeElementGuid.AppendChild(attributeNameElementGuidName); //write the client mac address as the value XmlElement attributeNameElementGuidValue = HQNFile.CreateElement(string.Empty, "attr_value", string.Empty); attributeNameElementGuidValue.AppendChild(HQNFile.CreateTextNode(Guid.NewGuid().ToString())); attributeElementGuid.AppendChild(attributeNameElementGuidValue); //create a file path with the local file path, machine name, and date time string HqnFileName = ConfigurationManager.AppSettings["HQNFileLocalPath"]; HqnFileName += Server.MachineName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_andon_monitor.xml"; HQNFile.Save(HqnFileName); //send XML to HQN file drop along with any other files MoveHQNFiles(); }
public void Save() { XmlDocument xmlDoc = new XmlDocument(); XmlNode nodProject = xmlDoc.CreateElement("Project"); xmlDoc.AppendChild(nodProject); // Create an XML declaration. XmlDeclaration xmldecl; xmldecl = xmlDoc.CreateXmlDeclaration("1.0", null, null); xmlDoc.InsertBefore(xmldecl, xmlDoc.DocumentElement); nodProject.AppendChild(xmlDoc.CreateElement("Name")).InnerText = Name; nodProject.AppendChild(xmlDoc.CreateElement("DateTimeCreated")).InnerText = DateTimeCreated.ToString("o"); nodProject.AppendChild(xmlDoc.CreateElement("GCDVersion")).InnerText = GCDVersion; if (OnlineParams.Count > 0) { XmlNode nodUpload = nodProject.AppendChild(xmlDoc.CreateElement("Online")); foreach (KeyValuePair <string, string> kvp in OnlineParams) { XmlNode kvpItem = nodUpload.AppendChild(xmlDoc.CreateElement(kvp.Key)); kvpItem.InnerText = kvp.Value; } } XmlNode nodDescription = nodProject.AppendChild(xmlDoc.CreateElement("Description")); if (!string.IsNullOrEmpty(Description)) { nodDescription.InnerText = Description; } XmlNode nodUnits = nodProject.AppendChild(xmlDoc.CreateElement("Units")); nodUnits.AppendChild(xmlDoc.CreateElement("Horizontal")).InnerText = Units.HorizUnit.ToString(); nodUnits.AppendChild(xmlDoc.CreateElement("Vertical")).InnerText = Units.VertUnit.ToString(); nodUnits.AppendChild(xmlDoc.CreateElement("Area")).InnerText = Units.ArUnit.ToString(); nodUnits.AppendChild(xmlDoc.CreateElement("Volume")).InnerText = Units.VolUnit.ToString(); XmlNode nodArea = nodProject.AppendChild(xmlDoc.CreateElement("CellArea")); if (CellArea.As(Units.ArUnit) > 0) { nodArea.InnerText = CellArea.As(Units.ArUnit).ToString("R", CultureInfo.InvariantCulture); } if (DEMSurveys.Count > 0) { XmlNode nodDEMs = nodProject.AppendChild(xmlDoc.CreateElement("DEMSurveys")); foreach (DEMSurvey dem in DEMSurveys) { XmlNode nodItem = nodDEMs.AppendChild(xmlDoc.CreateElement("DEM")); dem.Serialize(nodItem); } } if (ReferenceSurfaces.Count > 0) { XmlNode nodSurfaces = nodProject.AppendChild(xmlDoc.CreateElement("ReferenceSurfaces")); foreach (Surface surf in ReferenceSurfaces) { XmlNode nodItem = nodSurfaces.AppendChild(xmlDoc.CreateElement("ReferenceSurface")); surf.Serialize(nodItem); } } if (Masks.Count > 0) { XmlNode nodMasks = nodProject.AppendChild(xmlDoc.CreateElement("Masks")); Masks.ForEach(x => x.Serialize(nodMasks)); } if (ProfileRoutes.Count > 0) { XmlNode nodRoutes = nodProject.AppendChild(xmlDoc.CreateElement("ProfileRoutes")); ProfileRoutes.ForEach(x => x.Serialize(nodRoutes)); } if (DoDs.Count > 0) { XmlNode nodDoDs = nodProject.AppendChild(xmlDoc.CreateElement("DoDs")); foreach (DoDBase dod in DoDs) { dod.Serialize(nodDoDs); } } if (InterComparisons.Count > 0) { XmlNode nodInter = nodProject.AppendChild(xmlDoc.CreateElement("InterComparisons")); InterComparisons.ForEach(x => x.Serialize(nodInter)); } if (MetaData.Count > 0) { XmlNode nodMetaData = nodProject.AppendChild(xmlDoc.CreateElement("MetaData")); foreach (KeyValuePair <string, string> item in MetaData) { XmlNode nodItem = nodMetaData.AppendChild(xmlDoc.CreateElement("Item")); nodItem.AppendChild(xmlDoc.CreateElement("Key")).InnerText = item.Key; nodItem.AppendChild(xmlDoc.CreateElement("Value")).InnerText = item.Value; } } xmlDoc.Save(ProjectFile.FullName); try { SaveRiverscapesProject(ProjectFile); } catch (Exception ex) { // Fail silently Console.WriteLine("Error saving riverscapes project file."); Console.WriteLine(ex.Message); } }
public bool LoadXMLConfig() { var dir = AppDomain.CurrentDomain.BaseDirectory; string strPath = dir.ToString(); if (strPath.Substring(strPath.Length - 1).Contains("\\")) { strPath = strPath + @"ServicePoint.Settings.xml"; } else { strPath = strPath + @"\\ServicePoint.Settings.xml"; } GetSystemInformation(); try { XmlDocument xml = new XmlDocument(); xml.Load(@strPath); if (xml.FirstChild.NodeType == XmlNodeType.XmlDeclaration) { XmlDeclaration dec = (XmlDeclaration)xml.FirstChild; dec.Encoding = "UTF-8"; } else { XmlDeclaration dec = xml.CreateXmlDeclaration("1.0", null, null); dec.Encoding = "UTF-8"; xml.InsertBefore(dec, xml.DocumentElement); } XmlNodeList xnList = xml.SelectNodes("/ServicePoint/AGENT"); foreach (XmlNode xn in xnList) { g_SharedData.WSP_AGENT_SETTING.strServerKey = xn["SERVER_KEY"].InnerText; g_SharedData.WSP_AGENT_SETTING.iBuildNumber = "2.1"; //xn["BuildNumber"].InnerText; g_SharedData.WSP_AGENT_SETTING.strWS_URL = xn["WS_URL"].InnerText; //g_SharedData.WSP_AGENT_SETTING.iPerfLogCollectInterval = Convert.ToInt32(xn["PerformanceCollectInterval"].InnerText); //if (g_SharedData.WSP_AGENT_SETTING.iPerfLogCollectInterval < 5 || g_SharedData.WSP_AGENT_SETTING.iPerfLogCollectInterval > 3600) // g_SharedData.WSP_AGENT_SETTING.iPerfLogCollectInterval = 15; g_SharedData.WSP_AGENT_SETTING.iPerfLogCollectInterval = 15; g_SharedData.WSP_AGENT_SETTING.iMaxAgentMemorySizeMB = 70; // Convert.ToInt32(xn["MaxAgentMemorySizeMB"].InnerText); } xnList = xml.SelectNodes("/ServicePoint/WEB"); foreach (XmlNode xn in xnList) { g_SharedData.WEB_SETTING.iMaxConnectionPoolSize = Convert.ToInt32(xn["MaxPoolSize"].InnerText); g_SharedData.WEB_SETTING.strLogFilesDirectory = xn["LogFileDirectory"].InnerText; g_SharedData.WEB_SETTING.strLastLogFileName = xn["LastLogFile"].InnerText; if (xn["IISLogAnalysis"].InnerText.ToLower() == "false") { g_SharedData.WEB_SETTING.bIISLogAnalysis = false; } else { g_SharedData.WEB_SETTING.bIISLogAnalysis = true; } if (xn["HC_Enabled"].InnerText.ToLower() == "false") { g_SharedData.HC_SETTING.bHC_Enabled = false; } else { g_SharedData.HC_SETTING.bHC_Enabled = true; } g_SharedData.WEB_SETTING.strHostHeader = xn["HostHeader"].InnerText; g_SharedData.HC_SETTING.iHC_Interval = Convert.ToInt32(xn["HC_Interval"].InnerText); if (g_SharedData.HC_SETTING.iHC_Interval < 1 || g_SharedData.HC_SETTING.iHC_Interval > 60) { g_SharedData.HC_SETTING.iHC_Interval = 30; } g_SharedData.HC_SETTING.iHC_Timeout = Convert.ToInt32(xn["HC_TimeOut"].InnerText); if (g_SharedData.HC_SETTING.iHC_Timeout < 1) { g_SharedData.HC_SETTING.iHC_Timeout = 1; } // Initialize HC List in dtHC_URL datatable if (g_SharedData.HC_SETTING.dtHC_URL == null) { g_SharedData.HC_SETTING.dtHC_URL = new DataTable(); g_SharedData.HC_SETTING.dtHC_URL.Columns.Add(new DataColumn("HC_URL", typeof(string))); } else { g_SharedData.HC_SETTING.dtHC_URL.Rows.Clear(); } XmlNodeList xnURLS = xml.SelectNodes("/ServicePoint/WEB/HC_URLS/URL"); foreach (XmlNode xn2 in xnURLS) { g_SharedData.HC_SETTING.dtHC_URL.Rows.Add(xn2.InnerText); } } xnList = xml.SelectNodes("/ServicePoint/SQL"); foreach (XmlNode xn in xnList) { g_SharedData.LOCAL_SQL_SETTING.strServerName = xn["ServerName"].InnerText; g_SharedData.LOCAL_SQL_SETTING.strAuthentication = xn["Authentication"].InnerText; g_SharedData.LOCAL_SQL_SETTING.strAccount = xn["UserName"].InnerText; g_SharedData.LOCAL_SQL_SETTING.strPassword = xn["Password"].InnerText; g_SharedData.LOCAL_SQL_SETTING.strEncrypted = xn["LocalDB_EncrtypedPassword"].InnerText; g_SharedData.LOCAL_SQL_SETTING.iQueryInterval = Convert.ToInt32(xn["LocalDB_minQueryInterval"].InnerText); if (xn["EnableCollectingRunningQueries"].InnerText.ToUpper() == "TRUE") { g_SharedData.LOCAL_SQL_SETTING.bEnableCollectingRunningQueries = true; } else { g_SharedData.LOCAL_SQL_SETTING.bEnableCollectingRunningQueries = false; } } BuildLocalDBConnectionString(); return(true); } catch (Exception ex) { WSPEvent.WriteEvent("Service Point Agent failed to read settings from ServicePoint.Settings.XML. Please review your cofigurations in the file. - " + ex.Message, "E", 1137); return(false); } }
private void SaveRiverscapesProject(FileInfo gcdProjectFile) { XmlDocument xmlDoc = new XmlDocument(); XmlNode nodProject = xmlDoc.CreateElement("Project"); xmlDoc.AppendChild(nodProject); XmlAttribute attNameSpace = xmlDoc.CreateAttribute("xmlns:xsi"); attNameSpace.InnerText = "http://www.w3.org/2001/XMLSchema-instance"; nodProject.Attributes.Append(attNameSpace); XmlAttribute attSchema = xmlDoc.CreateAttribute("noNamespaceSchemaLocation", attNameSpace.InnerText); attSchema.InnerText = "https://xml.riverscapes.xyz/Projects/XSD/V1/GCD.xsd"; nodProject.Attributes.Append(attSchema); // Create an XML declaration. XmlDeclaration xmldecl; xmldecl = xmlDoc.CreateXmlDeclaration("1.0", null, null); xmlDoc.InsertBefore(xmldecl, xmlDoc.DocumentElement); nodProject.AppendChild(xmlDoc.CreateElement("Name")).InnerText = Name; nodProject.AppendChild(xmlDoc.CreateElement("ProjectType")).InnerText = "GCD"; XmlNode nodMetaData = nodProject.AppendChild(xmlDoc.CreateElement("MetaData")); if (!MetaData.ContainsKey("Description")) { XmlNode nodItem = nodMetaData.AppendChild(xmlDoc.CreateElement("Meta")); nodItem.InnerText = Description; XmlAttribute attName = xmlDoc.CreateAttribute("name"); attName.InnerText = "Description"; nodItem.Attributes.Append(attName); } // Project Date Creation time XmlNode nodMetaDate = nodMetaData.AppendChild(xmlDoc.CreateElement("Meta")); nodMetaDate.InnerText = DateTimeCreated.ToString("o"); XmlAttribute attMetaDate = xmlDoc.CreateAttribute("name"); attMetaDate.InnerText = "DateCreated"; nodMetaDate.Attributes.Append(attMetaDate); // GCD Version XmlNode nodMetaVersion = nodMetaData.AppendChild(xmlDoc.CreateElement("Meta")); nodMetaVersion.InnerText = GCDVersion; XmlAttribute attMetaVersion = xmlDoc.CreateAttribute("name"); attMetaVersion.InnerText = "GCDVersion"; nodMetaVersion.Attributes.Append(attMetaVersion); // GCD Project Metadata foreach (KeyValuePair <string, string> item in MetaData) { XmlNode nodItem = nodMetaData.AppendChild(xmlDoc.CreateElement("Meta")); nodItem.InnerText = item.Value; XmlAttribute attName = xmlDoc.CreateAttribute("name"); attName.InnerText = item.Key; nodItem.Attributes.Append(attName); } XmlNode nodRealizations = nodProject.AppendChild(xmlDoc.CreateElement("Realizations")); XmlNode nodGCD = nodRealizations.AppendChild(xmlDoc.CreateElement("GCD")); XmlAttribute attGUID = xmlDoc.CreateAttribute("id"); attGUID.InnerText = Guid.NewGuid().ToString(); nodGCD.Attributes.Append(attGUID); XmlAttribute attDate = xmlDoc.CreateAttribute("dateCreated"); attDate.InnerText = DateTimeCreated.ToString("o"); nodGCD.Attributes.Append(attDate); XmlAttribute attVersion = xmlDoc.CreateAttribute("productVersion"); attVersion.InnerText = GCDVersion; nodGCD.Attributes.Append(attVersion); nodGCD.AppendChild(xmlDoc.CreateElement("Name")).InnerText = Name; nodGCD.AppendChild(xmlDoc.CreateElement("ProjectPath")).InnerText = GetRelativePath(gcdProjectFile); FileInfo riverscapesFile = new FileInfo(Path.Combine(gcdProjectFile.DirectoryName, "project.rs.xml")); xmlDoc.Save(riverscapesFile.FullName); }
private string createNuspec(string outputDir, FileInfo moduleFileInfo) { WriteVerbose("Creating new nuspec file."); Hashtable parsedMetadataHash = new Hashtable(); if (moduleFileInfo.Extension.Equals(".psd1", StringComparison.OrdinalIgnoreCase)) { System.Management.Automation.Language.Token[] tokens; ParseError[] errors; var ast = Parser.ParseFile(moduleFileInfo.FullName, out tokens, out errors); if (errors.Length > 0) { var message = String.Format("Could not parse '{0}' as a PowerShell data file.", moduleFileInfo.FullName); var ex = new ArgumentException(message); var psdataParseError = new ErrorRecord(ex, "psdataParseError", ErrorCategory.ParserError, null); this.ThrowTerminatingError(psdataParseError); } else { var data = ast.Find(a => a is HashtableAst, false); if (data != null) { parsedMetadataHash = (Hashtable)data.SafeGetValue(); } else { var message = String.Format("Could not parse as PowerShell data file-- no hashtable root for file '{0}'", moduleFileInfo.FullName); var ex = new ArgumentException(message); var psdataParseError = new ErrorRecord(ex, "psdataParseError", ErrorCategory.ParserError, null); this.ThrowTerminatingError(psdataParseError); } } } else if (moduleFileInfo.Extension.Equals(".ps1", StringComparison.OrdinalIgnoreCase)) { ParseScriptMetadata(parsedMetadataHash, moduleFileInfo); } /// now we have parsedMetadatahash to fill out the nuspec information var nameSpaceUri = "http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd"; var doc = new XmlDocument(); // xml declaration is recommended, but not mandatory XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); // create top-level elements XmlElement packageElement = doc.CreateElement("package", nameSpaceUri); XmlElement metadataElement = doc.CreateElement("metadata", nameSpaceUri); Dictionary <string, string> metadataElementsDictionary = new Dictionary <string, string>(); // id is mandatory metadataElementsDictionary.Add("id", pkgName); string version = String.Empty; if (parsedMetadataHash.ContainsKey("moduleversion")) { version = parsedMetadataHash["moduleversion"].ToString(); } else if (parsedMetadataHash.ContainsKey("version")) { version = parsedMetadataHash["version"].ToString(); } else { // no version is specified for the nuspec var message = "There is no package version specified. Please specify a version before publishing."; var ex = new ArgumentException(message); var NoVersionFound = new ErrorRecord(ex, "NoVersionFound", ErrorCategory.InvalidArgument, null); this.ThrowTerminatingError(NoVersionFound); } // Look for Prerelease tag if (parsedMetadataHash.ContainsKey("PrivateData")) { if (parsedMetadataHash["PrivateData"] is Hashtable privateData && privateData.ContainsKey("PSData")) { if (privateData["PSData"] is Hashtable psData && psData.ContainsKey("Prerelease")) { if (psData["Prerelease"] is string preReleaseVersion) { version = string.Format(@"{0}-{1}", version, preReleaseVersion); } } } } NuGetVersion.TryParse(version, out pkgVersion); metadataElementsDictionary.Add("version", pkgVersion.ToNormalizedString()); if (parsedMetadataHash.ContainsKey("author")) { metadataElementsDictionary.Add("authors", parsedMetadataHash["author"].ToString().Trim()); } if (parsedMetadataHash.ContainsKey("companyname")) { metadataElementsDictionary.Add("owners", parsedMetadataHash["companyname"].ToString().Trim()); } // defaults to false var requireLicenseAcceptance = parsedMetadataHash.ContainsKey("requirelicenseacceptance") ? parsedMetadataHash["requirelicenseacceptance"].ToString().ToLower().Trim() : "false"; metadataElementsDictionary.Add("requireLicenseAcceptance", requireLicenseAcceptance); if (parsedMetadataHash.ContainsKey("description")) { metadataElementsDictionary.Add("description", parsedMetadataHash["description"].ToString().Trim()); } if (parsedMetadataHash.ContainsKey("releasenotes") || !String.IsNullOrEmpty(_releaseNotes)) { var releaseNotes = string.IsNullOrEmpty(_releaseNotes) ? parsedMetadataHash["releasenotes"].ToString().Trim() : _releaseNotes; metadataElementsDictionary.Add("releaseNotes", releaseNotes); } if (parsedMetadataHash.ContainsKey("copyright")) { metadataElementsDictionary.Add("copyright", parsedMetadataHash["copyright"].ToString().Trim()); } string tags = string.Empty; if (parsedMetadataHash.ContainsKey("tags") || _tags != null) { tags = _tags == null ? (parsedMetadataHash["tags"].ToString().Trim() + " ") : (_tags.ToString().Trim() + " "); } tags += moduleFileInfo.Extension.Equals(".psd1", StringComparison.OrdinalIgnoreCase) ? "PSModule" : "PSScript"; metadataElementsDictionary.Add("tags", tags); if (parsedMetadataHash.ContainsKey("licenseurl") || !String.IsNullOrEmpty(_licenseUrl)) { var licenseUrl = string.IsNullOrEmpty(_licenseUrl) ? parsedMetadataHash["licenseurl"].ToString().Trim() : _licenseUrl; metadataElementsDictionary.Add("licenseUrl", licenseUrl); } if (parsedMetadataHash.ContainsKey("projecturl") || !String.IsNullOrEmpty(_projectUrl)) { var projectUrl = string.IsNullOrEmpty(_projectUrl) ? parsedMetadataHash["projecturl"].ToString().Trim() : _projectUrl; metadataElementsDictionary.Add("projectUrl", projectUrl); } if (parsedMetadataHash.ContainsKey("iconurl") || !String.IsNullOrEmpty(_iconUrl)) { var iconUrl = string.IsNullOrEmpty(_iconUrl) ? parsedMetadataHash["iconurl"].ToString().Trim() : _iconUrl; metadataElementsDictionary.Add("iconUrl", iconUrl); } foreach (var key in metadataElementsDictionary.Keys) { XmlElement element = doc.CreateElement(key, nameSpaceUri); string elementInnerText; metadataElementsDictionary.TryGetValue(key, out elementInnerText); element.InnerText = elementInnerText; metadataElement.AppendChild(element); } var requiredModules = ParseRequiredModules(parsedMetadataHash); if (requiredModules != null) { XmlElement dependenciesElement = doc.CreateElement("dependencies", nameSpaceUri); foreach (Hashtable dependency in requiredModules) { XmlElement element = doc.CreateElement("dependency", nameSpaceUri); element.SetAttribute("id", dependency["ModuleName"].ToString()); if (!string.IsNullOrEmpty(dependency["ModuleVersion"].ToString())) { element.SetAttribute("version", dependency["ModuleVersion"].ToString()); } dependenciesElement.AppendChild(element); } metadataElement.AppendChild(dependenciesElement); } packageElement.AppendChild(metadataElement); doc.AppendChild(packageElement); var nuspecFullName = System.IO.Path.Combine(outputDir, pkgName + ".nuspec"); doc.Save(nuspecFullName); this.WriteVerbose("The newly created nuspec is: " + nuspecFullName); return(nuspecFullName); }
void thread() { DataTable Transactions = getAllLocation(); string prevDoc = ""; int total = Transactions.Rows.Count; // esrcibo en el nowin porque van para premiumsoft foreach (DataRow row in Transactions.Rows) { if (prevDoc != row["LOCNCODE"].ToString().Trim()) { DataTable TransactionDetail = getInventorySnapshot(row["LOCNCODE"].ToString().Trim(), mItmbs); string ADJUST = row["LOCNCODE"].ToString().Trim(); string FileName = "GP_INI_{0}.xml"; IEvent e = new InfoEvent("", "", "Iniciando la creación del archivo XML '" + String.Format(FileName, ADJUST) + "'."); e.Publish(); // xml // XmlDocument doc = new XmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); /* Lines */ XmlElement Lines = doc.CreateElement(string.Empty, "lines", string.Empty); /* Lines */ ///////// Models.InventoryAdjustment ia = new Models.InventoryAdjustment(); foreach (DataRow det in TransactionDetail.Rows) { string DOCNUMBR = det["LOCNCODE"].ToString().Trim(); string USERID = "UNKNOWN"; string DOCDATE = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + " 00:00"; string TIME = DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":00"; string ITEMNMBR = det["ITEMNMBR"].ToString().Trim(); Models.ItemAvailability iav = new Models.ItemAvailability(); try { if (det["PRCLEVEL"].ToString().Trim() == "GALAPAGO") { XmlElement Item = doc.CreateElement(string.Empty, "articulo", string.Empty); ///* document */ //XmlElement document = doc.CreateElement(string.Empty, "documento", string.Empty); iav.Codigoalmacen = det["LOCNCODE"].ToString().Trim();//XmlText document_text = doc.CreateTextNode(det["LOCNCODE"].ToString().Trim()); //document.AppendChild(document_text); //Item.AppendChild(document); ///* document */ ///* realizador */ //XmlElement realizador = doc.CreateElement(string.Empty, "realizador", string.Empty); iav.Realizador = USERID;//XmlText realizador_text = doc.CreateTextNode("UNKNOWN"); //realizador.AppendChild(realizador_text); //Item.AppendChild(realizador); ///* realizador */ ///* motivo */ //XmlElement motivo = doc.CreateElement(string.Empty, "motivo", string.Empty); iav.Motivo = "ESTATUS ACTUAL DE INVENTARIO";//XmlText motivo_text = doc.CreateTextNode("ESTATUS ACTUAL DE INVENTARIO"); //motivo.AppendChild(motivo_text); //Item.AppendChild(motivo); ///* motivo */ ///* fecha */ //XmlElement fecha = doc.CreateElement(string.Empty, "fecha", string.Empty); iav.Fecha = DOCDATE;//XmlText fecha_text = doc.CreateTextNode(DOCDATE); //fecha.AppendChild(fecha_text); //Item.AppendChild(fecha); ///* fecha */ ///* hora */ //XmlElement hora = doc.CreateElement(string.Empty, "hora", string.Empty); iav.Hora = TIME;//XmlText hora_text = doc.CreateTextNode(TIME); //hora.AppendChild(hora_text); //Item.AppendChild(hora); ///* hora */ ///* codigo */ //XmlElement codigo = doc.CreateElement(string.Empty, "codigo", string.Empty); iav.Codigo = ITEMNMBR;//XmlText codigo_text = doc.CreateTextNode(ITEMNMBR); //codigo.AppendChild(codigo_text); //Item.AppendChild(codigo); ///* codigo */ ///* nombre */ //XmlElement nombre = doc.CreateElement(string.Empty, "nombre", string.Empty); iav.Nombre = det["ITEMDESC"].ToString().Trim();//XmlText nombre_text = doc.CreateTextNode(det["ITEMDESC"].ToString().Trim()); //nombre.AppendChild(nombre_text); //Item.AppendChild(nombre); ///* nombre */ ///* grupo */ //XmlElement grupo = doc.CreateElement(string.Empty, "grupo", string.Empty); iav.Grupo = det["ITMCLSCD"].ToString().Trim();//XmlText grupo_text = doc.CreateTextNode(det["ITMCLSCD"].ToString().Trim()); //grupo.AppendChild(grupo_text); //Item.AppendChild(grupo); ///* grupo */ ///* tipoproceso */ //XmlElement tipoproceso = doc.CreateElement(string.Empty, "tipoproceso", string.Empty); iav.Tipoproceso = 1;//XmlText tipoproceso_text = doc.CreateTextNode("1"); //tipoproceso.AppendChild(tipoproceso_text); //Item.AppendChild(tipoproceso); ///* tipoproceso */ ///* codigoalmacen */ //XmlElement codigoalmacen = doc.CreateElement(string.Empty, "codigoalmacen", string.Empty); iav.Codigoalmacen = det["LOCNCODE"].ToString().Trim();//XmlText codigoalmacen_text = doc.CreateTextNode(det["LOCNCODE"].ToString().Trim()); //codigoalmacen.AppendChild(codigoalmacen_text); //Item.AppendChild(codigoalmacen); ///* codigoalmacen */ ///* usuario */ //XmlElement usuario = doc.CreateElement(string.Empty, "descripcion", string.Empty); iav.Descripcion = row["LOCNDSCR"].ToString().Trim();//XmlText usuario_text = doc.CreateTextNode(row["LOCNDSCR"].ToString().Trim()); //usuario.AppendChild(usuario_text); //Item.AppendChild(usuario); ///* usuario */ ///* ubicacion */ //XmlElement ubicacion = doc.CreateElement(string.Empty, "usuario", string.Empty); iav.Usuario = "UNKNOWN"; //XmlText ubicacion_text = doc.CreateTextNode("UNKNOWN"); //ubicacion.AppendChild(ubicacion_text); //Item.AppendChild(ubicacion); ///* ubicacion */ ///* descripción */ //XmlElement descripcion = doc.CreateElement(string.Empty, "ubicacion", string.Empty); iav.Ubicacion = row["ADDRESS1"].ToString().Trim();//XmlText descripcion_text = doc.CreateTextNode(row["ADDRESS1"].ToString().Trim()); //descripcion.AppendChild(descripcion_text); //Item.AppendChild(descripcion); ///* descripción */ ///* precio */ //XmlElement precio = doc.CreateElement(string.Empty, "precio_neto", string.Empty); iav.Precio_neto = (decimal)Convert.ToDecimal(det["PRICE"].ToString().Trim().Replace(",", "."));//XmlText precio_text = doc.CreateTextNode(det["PRICE"].ToString().Trim().Replace(",", ".")); //precio.AppendChild(precio_text); //Item.AppendChild(precio); ///* precio */ ///* cost */ //XmlElement cost = doc.CreateElement(string.Empty, "precio_con_itbms", string.Empty); iav.Precio_con_itbms = (decimal)Convert.ToDecimal(det["PRICEWITMBS"].ToString().Trim().Replace(",", ".")); //XmlText cost_text = doc.CreateTextNode(det["PRICEWITMBS"].ToString().Trim().Replace(",", ".")); //cost.AppendChild(cost_text); //Item.AppendChild(cost); ///* costo */ ///* costo */ //#region "COSTO NODE" //XmlElement costo = doc.CreateElement(string.Empty, "costo", string.Empty); iav.Costo = (decimal)Convert.ToDecimal(det["CURRCOST"].ToString().Trim().Replace(",", "."));//XmlText costo_text = doc.CreateTextNode(det["CURRCOST"].ToString().Trim().Replace(",", ".")); //costo.AppendChild(costo_text); //Item.AppendChild(costo); //#endregion ///* costo */ //XmlElement element7 = doc.CreateElement(string.Empty, "porcentaje_itbms", string.Empty); iav.Porcentaje_itbms = (decimal)Convert.ToDecimal(det["ITMBSPCT"].ToString().Trim().Replace(",", ".")); //XmlText text5 = doc.CreateTextNode(det["ITMBSPCT"].ToString().Trim().Replace(",", ".")); //element7.AppendChild(text5); //Item.AppendChild(element7); //XmlElement element8 = doc.CreateElement(string.Empty, "tipo", string.Empty); iav.Tipo = (int)Convert.ToInt32(det["ITEMTYPE"].ToString().Trim());//XmlText text6 = doc.CreateTextNode(det["ITEMTYPE"].ToString().Trim()); //element8.AppendChild(text6); //Item.AppendChild(element8); //XmlElement element9 = doc.CreateElement(string.Empty, "cantidad", string.Empty); iav.Cantidad = (decimal)Convert.ToDecimal(det["DISP"].ToString().Trim().Replace(",", "."));//XmlText text7 = doc.CreateTextNode(det["DISP"].ToString().Trim().Replace(",", ".")); //element9.AppendChild(text7); //Item.AppendChild(element9); //XmlElement element10 = doc.CreateElement(string.Empty, "unidad_de_medida", string.Empty); iav.Unidad_de_medida = det["UOFM"].ToString().Trim();//XmlText text8 = doc.CreateTextNode(det["UOFM"].ToString().Trim()); //element10.AppendChild(text8); //Item.AppendChild(element10); ia.Add(iav);//Lines.AppendChild(Item); } } catch (Exception ex) { IEvent err = new ErrorEvent("", "", "No pudo crear el archivo xml correctamente. Mensaje: " + ex.Message); err.Publish(); } } doc.AppendChild(Lines); if (this.NowPathIn.ToCharArray().Last() == '/' || this.NowPathIn.ToCharArray().Last() == '\\') { if (!System.IO.File.Exists(this.mNowPathOut + string.Format(FileName, ADJUST))) { Models.InventoryAdjustment.SaveAs(this.mNowPathOut + string.Format(FileName, ADJUST), ia);// doc.Save(this.mNowPathOut + string.Format(FileName, ADJUST)); } } else { if (!System.IO.File.Exists(this.mNowPathOut + "/" + string.Format(FileName, ADJUST))) { Models.InventoryAdjustment.SaveAs(this.mNowPathOut + "/" + string.Format(FileName, ADJUST), ia);// doc.Save(this.mNowPathOut + "/" + string.Format(FileName, ADJUST)); } } total--; ObserverManager.Instance.addSubject(new ProgressSubject(total, Transactions.Rows.Count - total)); IEvent e2 = new InfoEvent("", "", "El archivo '" + String.Format(FileName, ADJUST) + "'. fue creado correctamente"); e2.Publish(); } prevDoc = row["LOCNCODE"].ToString().Trim(); } ObserverManager.Instance.addSubject(new ProgressSubject(0, 0)); }
public void WriteOutputXmlFile() { XmlDocument doc = new XmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); //[3/27/2018 17:33] Cameron Osborn: Create wrapper XmlElement options = doc.CreateElement(string.Empty, "Options", string.Empty); doc.AppendChild(options); XmlElement templates = doc.CreateElement(string.Empty, "CodeTemplates", string.Empty); options.AppendChild(templates); //[3/27/2018 17:36] Cameron Osborn: Write all templates foreach (CodeTemplate template in templates) { XmlElement templateElement = doc.CreateElement(string.Empty, "CodeTemplate", string.Empty); XmlElement descElement = doc.CreateElement(string.Empty, "Description", string.Empty); XmlText descText = doc.CreateTextNode(template.Description); descElement.AppendChild(descText); templateElement.AppendChild(descElement); XmlElement textElement = doc.CreateElement(string.Empty, "Text", string.Empty); XmlText textText = doc.CreateTextNode(template.Text); textElement.AppendChild(textText); templateElement.AppendChild(textElement); XmlElement authorElement = doc.CreateElement(string.Empty, "Author", string.Empty); XmlText authorText = doc.CreateTextNode(template.Author); authorElement.AppendChild(authorText); templateElement.AppendChild(authorElement); XmlElement commentElement = doc.CreateElement(string.Empty, "Comment", string.Empty); XmlText commentText = doc.CreateTextNode(template.Comment); commentElement.AppendChild(commentText); templateElement.AppendChild(commentElement); XmlElement expansionKeywordElement = doc.CreateElement(string.Empty, "ExpansionKeyword", string.Empty); XmlText expansionKeywordText = doc.CreateTextNode(template.ExpansionKeyword); expansionKeywordElement.AppendChild(expansionKeywordText); templateElement.AppendChild(expansionKeywordElement); XmlElement commandNameElement = doc.CreateElement(string.Empty, "CommandName", string.Empty); XmlText commandNameText = doc.CreateTextNode(template.CommandName); commandNameElement.AppendChild(commandNameText); templateElement.AppendChild(commandNameElement); XmlElement categoryElement = doc.CreateElement(string.Empty, "Category", string.Empty); XmlText categoryText = doc.CreateTextNode(template.Category); categoryElement.AppendChild(categoryText); templateElement.AppendChild(categoryElement); XmlElement languageElement = doc.CreateElement(string.Empty, "Language", string.Empty); XmlText languageText = doc.CreateTextNode(template.Language.ToString()); languageElement.AppendChild(languageText); templateElement.AppendChild(languageElement); } doc.Save("C:\\Users\\camerono\\Desktop\\XmlOut.xml"); }
static void Main(string[] args) { //1. input: path to where all the files are located, output file? string inputFilePath; string outputFile; if (args.Length != 2) { Console.WriteLine("incorrect number of arguments. Correct usage: xxx {inputFilePath} {outputFile}"); Environment.Exit(1); } inputFilePath = args[0]; outputFile = args[1]; //inputFilePath = @"..\..\..\..\..\..\..\SD\working.client.writer\client\writer\intl\markets"; //outputFile = @"c:\temp\output.xml"; //2. generate blank xml root XmlDocument marketsXml = new XmlDocument(); XmlDeclaration declaration = marketsXml.CreateXmlDeclaration("1.0", "utf-8", String.Empty); XmlElement entryNode = marketsXml.CreateElement(FEATURES); marketsXml.AppendChild(entryNode); marketsXml.InsertBefore(declaration, entryNode); //3. get all folders DirectoryInfo dir = new DirectoryInfo(inputFilePath); DirectoryInfo[] marketDirs = dir.GetDirectories(); //4. open each folder and get the xml file from inside foreach (DirectoryInfo marketDir in marketDirs) { FileInfo[] files = marketDir.GetFiles("market.xml"); //case 1: no market xml if (files.Length == 0) { continue; } FileInfo xmlFile = files[0]; //defaulting to taking the first here...shouldn't be more than one tho! //5. scan xml file for correctness. if correct, move on, else log error // 5a. is actual XML document // 5b. XML structure: contains feature root, one market element, 0-many feature elements, each with 0 - many params // 5c. features have name and enabled attributes. parameters have name and value attributes. if (!ValidateXml(inputFilePath, xmlFile.FullName)) { Console.WriteLine("Validation Failed for file " + xmlFile.FullName); Environment.Exit(1); } //6. take the market portion and copy into new xml document using (FileStream xmlStream = xmlFile.OpenRead()) { XmlDocument marketDocument = new XmlDocument(); marketDocument.Load(xmlStream); XmlNode marketNode = marketDocument.SelectSingleNode("//features/market"); if (marketNode == null) { Console.WriteLine("Invalid marketizationXml.xml file detected"); Environment.Exit(1); } string marketName = marketNode.Attributes["name"].InnerText; if (marketName.ToLower() != marketName) { Console.WriteLine("market name must be lower case"); Environment.Exit(1); } entryNode.AppendChild(marketsXml.ImportNode(marketNode, true)); } } //7. output the xml into document (check for existence, create. Do not append) marketsXml.Save(outputFile); }
public void Save() { if (!IsNew && ReadOnly()) { MessageBox.Show(String.Format("\"{0}\" is read-only, cannot save this file.", wxsFile.Name), "Read Only!", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (wxsWatcher != null) { wxsWatcher.EnableRaisingEvents = false; } UndoManager.DeregisterHandlers(); XmlComment commentElement = null; if (projectSettings.IsEmpty() == false) { StringBuilder commentBuilder = new StringBuilder(); commentBuilder.Append("\r\n"); commentBuilder.Append(" # This comment is generated by WixEdit, the specific commandline\r\n"); commentBuilder.Append(" # arguments for the WiX Toolset are stored here.\r\n\r\n"); commentBuilder.AppendFormat(" candleArgs: {0}\r\n", projectSettings.CandleArgs); commentBuilder.AppendFormat(" lightArgs: {0}\r\n", projectSettings.LightArgs); commentElement = wxsDocument.CreateComment(commentBuilder.ToString()); XmlNode firstElement = wxsDocument.FirstChild; if (firstElement != null) { if (firstElement.NodeType == XmlNodeType.XmlDeclaration) { firstElement = wxsDocument.FirstChild.NextSibling; } wxsDocument.InsertBefore(commentElement, firstElement); } else { wxsDocument.AppendChild(commentElement); } } // Handle extension namespaces. Remove all those which are not used in the file. foreach (string ext in xsdExtensionNames) { string theNodeNamespace = LookupExtensionNameReverse(ext); XmlNodeList list = wxsDocument.SelectNodes(String.Format("//{0}:*", theNodeNamespace), wxsNsmgr); if (list.Count == 0) { // Error reports show that a NullReferenceException occurs on the next line now, how can this be? // The wxsDocument.DocumentElement is null. wxsDocument.DocumentElement.RemoveAttribute(String.Format("xmlns:{0}", theNodeNamespace)); } } if (IncludeManager.HasIncludes) { IncludeManager.RemoveIncludes(); ArrayList changedIncludes = UndoManager.ChangedIncludes; if (changedIncludes.Count > 0) { string filesString = String.Join("\r\n\x2022 ", changedIncludes.ToArray(typeof(string)) as string[]); if (DialogResult.Yes == MessageBox.Show(String.Format("Do you want to save the following changed include files?\r\n\r\n\x2022 {0}", filesString), "Save?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { IncludeManager.SaveIncludes(UndoManager.ChangedIncludes); } } } FileMode mode = FileMode.OpenOrCreate; if (File.Exists(wxsFile.FullName)) { mode = mode | FileMode.Truncate; } using (FileStream fs = new FileStream(wxsFile.FullName, mode)) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = new string(' ', WixEditSettings.Instance.XmlIndentation); settings.NewLineHandling = NewLineHandling.None; settings.Encoding = new System.Text.UTF8Encoding(); XmlWriter writer = XmlWriter.Create(fs, settings); wxsDocument.Save(writer); writer.Close(); fs.Close(); } if (IncludeManager.HasIncludes) { // Remove nodes from main xml document IncludeManager.RestoreIncludes(); } projectSettings.ChangesHasBeenSaved(); if (commentElement != null) { wxsDocument.RemoveChild(commentElement); } if (wxsWatcher != null) { wxsWatcher.EnableRaisingEvents = true; } undoManager.DocumentIsSaved(); UndoManager.RegisterHandlers(); }
/*********************************************** * Procedure: protected void Page_Load() * Purpose: Create header of xml file * Parameters In: object sender, EventArgs e * Parameters Out: void ***********************************************/ protected void Page_Load(object sender, EventArgs e) { string exec = Request["executive"]; string strSite = Request["site"]; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Expires = -1; Response.ContentType = "text/xml"; Response.ContentEncoding = System.Text.Encoding.UTF8; if (exec == "true") { Guid siteid = SPContext.Current.Site.ID; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(siteid)) { SPWeb web = site.RootWeb;//No need to dispose if (strSite == "false") { web = site.OpenWeb(SPContext.Current.Web.ID); } web.Site.CatchAccessDeniedException = false; doc.LoadXml("<rows></rows>"); XmlNode mainNode = doc.ChildNodes[0]; XmlNode headNode = doc.CreateNode(XmlNodeType.Element, "head", doc.NamespaceURI); XmlNode ndSettings = doc.CreateNode(XmlNodeType.Element, "settings", doc.NamespaceURI); XmlNode ndColwith = doc.CreateNode(XmlNodeType.Element, "colwidth", doc.NamespaceURI); ndColwith.InnerText = "%"; ndSettings.AppendChild(ndColwith); headNode.AppendChild(ndSettings); mainNode.AppendChild(headNode); XmlAttribute attrType = doc.CreateAttribute("type"); attrType.Value = "tree"; XmlAttribute attrWidth = doc.CreateAttribute("width"); attrWidth.Value = "100"; XmlNode newNode = doc.CreateNode(XmlNodeType.Element, "column", doc.NamespaceURI); newNode.Attributes.Append(attrType); newNode.Attributes.Append(attrWidth); newNode.InnerText = ""; headNode.AppendChild(newNode); addWebs(web, mainNode); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "iso-8859-1", null); doc.InsertBefore(xmlDeclaration, doc.DocumentElement); data = doc.OuterXml; } }); } else { Guid siteid = SPContext.Current.Site.ID; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite tSite = new SPSite(siteid)) { AddMainNode( tSite, strSite, string.Empty, doc, (web, mainNode) => addWebs(web, mainNode), ref data, document => { var xmlDeclaration = document.CreateXmlDeclaration("1.0", "iso-8859-1", null); document.InsertBefore(xmlDeclaration, doc.DocumentElement); }); } }); } }
private bool GenerarXML() { try { string cfdi = "http://www.sat.gob.mx/cfd/3"; string xmlns = "http://www.w3.org/2000/xmlns/"; string xsi = "http://www.w3.org/2001/XMLSchema-instance"; string esquema = "http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd"; //string fecha = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss"); string fecha = Funciones.ObtenerFechaHora(); prefactura = fecha.Replace("-", "").Replace("T", "_").Replace(":", "") + ".xml"; XmlDocument documento = new XmlDocument(); XmlDeclaration declaracion = documento.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement raiz = documento.DocumentElement; documento.InsertBefore(declaracion, raiz); XmlElement comp = documento.CreateElement("cfdi", "Comprobante", cfdi); XmlAttribute ns = documento.CreateAttribute("xmlns:xsi", xmlns); ns.Value = xsi; comp.SetAttributeNode(ns); comp.SetAttribute("schemaLocation", xsi, esquema); // Parte 1: Atributos del comprobante string formaPago = txtFormaPago.Text; string subtotal = txtSubtotal.Text; string tipo = ddlTipo.Text; string total = txtTotal.Text; string metodoPago = txtMetodo.Text; string lugarExpedicion = txtLugar.Text; string version = "3.2"; string cuentaPago = (metodoPago != "No Identificado") ? txtCuenta.Text : ""; string noCertificado = ""; string rutaCertificado = Path.Combine(carpetaCertificados, certificado); string rutaLlave = Path.Combine(carpetaCertificados, llave); comp.SetAttribute("certificado", ClaseCertificado.ObtenerCertificado(rutaCertificado, out noCertificado)); comp.SetAttribute("fecha", fecha); comp.SetAttribute("formaDePago", formaPago); comp.SetAttribute("noCertificado", ClaseCertificado.ConvertHexToString(noCertificado, new UTF8Encoding(false))); comp.SetAttribute("subTotal", subtotal); comp.SetAttribute("tipoDeComprobante", tipo); comp.SetAttribute("total", total); comp.SetAttribute("metodoDePago", metodoPago); comp.SetAttribute("LugarExpedicion", lugarExpedicion); comp.SetAttribute("version", version); if (cuentaPago != "") { comp.SetAttribute("NumCtaPago", cuentaPago); } // Parte 2: Emisor string rfcEmisor = txtRFCEmisor.Text; string regimen = ddlRegimen.Text; string nombreEmisor = txtNombreEmisor.Text; XmlElement emisor = documento.CreateElement("cfdi", "Emisor", cfdi); emisor.SetAttribute("rfc", rfcEmisor); emisor.SetAttribute("nombre", txtNombreEmisor.Text); XmlElement regimenFiscal = documento.CreateElement("cfdi", "RegimenFiscal", cfdi); regimenFiscal.SetAttribute("Regimen", regimen); emisor.AppendChild(regimenFiscal); comp.AppendChild(emisor); // Parte 3: Receptor string rfcReceptor = txtRFCReceptor.Text; //string nombreReceptor = txtNombreReceptor.Text; XmlElement receptor = documento.CreateElement("cfdi", "Receptor", cfdi); receptor.SetAttribute("rfc", rfcReceptor); //receptor.SetAttribute("nombre",txtNombreReceptor.Text); comp.AppendChild(receptor); // Parte 4: Conceptos XmlElement conceptos = documento.CreateElement("cfdi", "Conceptos", cfdi); foreach (DataRow registro in dtConceptos.Rows) { decimal valorunit = decimal.Parse(registro["valorunitario"].ToString()); decimal importe = decimal.Parse(registro["importe"].ToString()); XmlElement concepto = documento.CreateElement("cfdi", "Concepto", cfdi); concepto.SetAttribute("cantidad", registro["cantidad"].ToString()); concepto.SetAttribute("unidad", registro["unidad"].ToString()); concepto.SetAttribute("descripcion", registro["descripcion"].ToString()); concepto.SetAttribute("valorUnitario", valorunit.ToString()); concepto.SetAttribute("importe", importe.ToString()); conceptos.AppendChild(concepto); } comp.AppendChild(conceptos); // Parte 5: Impuestos bool trasladosSI = chbTrasladoIVA.Checked || chbTrasladoIEPS.Checked; bool retencionesSI = chbRetencionIVA.Checked || chbRetencionISR.Checked; decimal trasladoIVA = (chbTrasladoIVA.Checked) ? decimal.Parse(txtImporteTrasladoIVA.Text) : 0; decimal trasladoIEPS = (chbTrasladoIEPS.Checked) ? decimal.Parse(txtImporteTrasladoIEPS.Text) : 0; string tasaIVA = txtTasaTrasladoIVA.Text; string tasaIEPS = txtTasaTrasladoIEPS.Text; decimal impuestosTrasladados = trasladoIVA + trasladoIEPS; decimal retencionIVA = (chbRetencionIVA.Checked) ? decimal.Parse(txtImporteRetencionIVA.Text) : 0; decimal retencionISR = (chbRetencionISR.Checked) ? decimal.Parse(txtImporteRetencionISR.Text) : 0; decimal impuestosRetenidos = retencionIVA + retencionISR; XmlElement impuestos = documento.CreateElement("cfdi", "Impuestos", cfdi); impuestos.SetAttribute("totalImpuestosTrasladados", impuestosTrasladados.ToString()); impuestos.SetAttribute("totalImpuestosRetenidos", impuestosRetenidos.ToString()); // 5a Retenciones if (chbRetenciones.Checked) { if (retencionesSI) { XmlElement retenciones = documento.CreateElement("cfdi", "Retenciones", cfdi); if (chbRetencionIVA.Checked) { XmlElement retencion1 = documento.CreateElement("cfdi", "Retencion", cfdi); retencion1.SetAttribute("importe", retencionIVA.ToString()); retencion1.SetAttribute("impuesto", "IVA"); retenciones.AppendChild(retencion1); } if (chbRetencionISR.Checked) { XmlElement retencion2 = documento.CreateElement("cfdi", "Retencion", cfdi); retencion2.SetAttribute("importe", retencionISR.ToString()); retencion2.SetAttribute("impuesto", "ISR"); retenciones.AppendChild(retencion2); } impuestos.AppendChild(retenciones); } } // 5b Traslados if (chbTraslados.Checked) { if (trasladosSI) { XmlElement traslados = documento.CreateElement("cfdi", "Traslados", cfdi); if (chbTrasladoIVA.Checked) { XmlElement traslado1 = documento.CreateElement("cfdi", "Traslado", cfdi); traslado1.SetAttribute("importe", trasladoIVA.ToString()); traslado1.SetAttribute("impuesto", "IVA"); traslado1.SetAttribute("tasa", tasaIVA); traslados.AppendChild(traslado1); } if (chbTrasladoIEPS.Checked) { XmlElement traslado2 = documento.CreateElement("cfdi", "Traslado", cfdi); traslado2.SetAttribute("importe", trasladoIEPS.ToString()); traslado2.SetAttribute("impuesto", "IEPS"); traslado2.SetAttribute("tasa", tasaIEPS); traslados.AppendChild(traslado2); } impuestos.AppendChild(traslados); } } comp.AppendChild(impuestos); documento.AppendChild(comp); MemoryStream memoria = XMLToStream(documento); string cadenaOriginal = ClaseCertificado.ObtenerCadenaOriginal(memoria); string selloCadena = ClaseCertificado.Sellar(rutaLlave, pass, cadenaOriginal); if (selloCadena == "") { return(false); } comp.SetAttribute("sello", selloCadena); MemoryStream memoria2 = XMLToStream(documento); GuardarXML(prefactura, memoria2); return(true); } catch (Exception ex) { return(false); } }
public static void ExportGPX(string OverlayTag) { SaveFileDialog StandardFileDialog = new SaveFileDialog { InitialDirectory = Program.DB.LastUsedFilepath, Filter = "gpx files (*.gpx)|*.gpx|All files (*.*)|*.*", FilterIndex = 0, RestoreDirectory = true, Title = "Export route as track" }; if (StandardFileDialog.ShowDialog() == DialogResult.OK) { KeyValuePair <string, Tourplanning.RouteData> RouteToSeialize = Program.Routes.First(x => x.Key == OverlayTag); XmlDocument GPX = new XmlDocument(); XmlDeclaration xmldecl = GPX.CreateXmlDeclaration("1.0", "UTF-8", null); XmlNode root = GPX.CreateElement("gpx"); GPX.AppendChild(root); XmlAttribute xmlns = GPX.CreateAttribute("xmlns"); xmlns.Value = "http://www.topografix.com/GPX/1/1"; root.Attributes.Append(xmlns); XmlAttribute version = GPX.CreateAttribute("version"); version.Value = "1.1"; root.Attributes.Append(version); XmlAttribute creator = GPX.CreateAttribute("creator"); creator.Value = "GeocachingTourPlanner"; root.Attributes.Append(creator); foreach (Geocache GC in RouteToSeialize.Value.GeocachesOnRoute()) { XmlElement wpt = GPX.CreateElement("wpt"); //Coordinates XmlAttribute latitude = GPX.CreateAttribute("lat"); latitude.Value = GC.lat.ToString(CultureInfo.InvariantCulture); XmlAttribute longitude = GPX.CreateAttribute("lon"); longitude.Value = GC.lon.ToString(CultureInfo.InvariantCulture); wpt.Attributes.Append(latitude); wpt.Attributes.Append(longitude); //Name XmlElement gcname = GPX.CreateElement("name"); gcname.InnerText = GC.Name; wpt.AppendChild(gcname); //link XmlElement link = GPX.CreateElement("link"); XmlAttribute linkattribute = GPX.CreateAttribute("href"); linkattribute.Value = "https://www.coord.info/" + GC.GCCODE; link.Attributes.Append(linkattribute); wpt.AppendChild(link); root.AppendChild(wpt); } XmlNode track = GPX.CreateElement("trk"); root.AppendChild(track); //Name of track XmlNode name = GPX.CreateElement("name"); name.InnerText = RouteToSeialize.Key; track.AppendChild(name); XmlNode tracksegment = GPX.CreateElement("trkseg"); Route FinalRoute = RouteToSeialize.Value.partialRoutes[0].partialRoute; for (int i = 1; i < RouteToSeialize.Value.partialRoutes.Count; i++) { FinalRoute = FinalRoute.Concatenate(RouteToSeialize.Value.partialRoutes[i].partialRoute); } foreach (Coordinate COO in FinalRoute.Shape) { XmlNode trackpoint = GPX.CreateElement("trkpt"); //Coordinates XmlAttribute latitude = GPX.CreateAttribute("lat"); latitude.Value = COO.Latitude.ToString(CultureInfo.InvariantCulture); XmlAttribute longitude = GPX.CreateAttribute("lon"); longitude.Value = COO.Longitude.ToString(CultureInfo.InvariantCulture); trackpoint.Attributes.Append(latitude); trackpoint.Attributes.Append(longitude); tracksegment.AppendChild(trackpoint); } track.AppendChild(tracksegment); GPX.InsertBefore(xmldecl, root); GPX.Save(StandardFileDialog.FileName); } }
/// <summary> /// 保存配置 /// </summary> internal static void AlterConfig() { Parameter parameter = ModelManager.Instance.GetParameter; string outPath = string.Concat(Application.streamingAssetsPath, configPath); if (File.Exists(outPath)) { File.Delete(outPath); } XmlDocument xmlDocument = new XmlDocument(); XmlDeclaration declaration = xmlDocument.CreateXmlDeclaration("1.0", "utf-8", null); //根节点 XmlNode root = xmlDocument.CreateElement("items"); //描述说明 XmlComment xmlComment; //元素 XmlElement item; //写入配置 #region 半径 xmlComment = xmlDocument.CreateComment("半径"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "radius"); item.SetAttribute("value", parameter.Radius.ToString()); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region x轴偏移 xmlComment = xmlDocument.CreateComment("x轴偏移"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "offsetX"); item.SetAttribute("value", parameter.OffsetX.ToString()); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region y轴偏移 xmlComment = xmlDocument.CreateComment("y轴偏移"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "offsetY"); item.SetAttribute("value", parameter.OffsetY.ToString()); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region 可视化数据数量 xmlComment = xmlDocument.CreateComment("可视化数据数量"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "audioDataCount"); item.SetAttribute("value", parameter.AudioDataCount.ToString()); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region 线宽 xmlComment = xmlDocument.CreateComment("线宽"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "lineWidth"); item.SetAttribute("value", parameter.LineWidth.ToString()); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region 最小高度 xmlComment = xmlDocument.CreateComment("最小高度"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "minHight"); item.SetAttribute("value", parameter.MinHight.ToString()); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region 最大高度 xmlComment = xmlDocument.CreateComment("最大高度"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "maxHight"); item.SetAttribute("value", parameter.MaxHight.ToString()); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region 亮度 xmlComment = xmlDocument.CreateComment("亮度"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "colorBrightness"); item.SetAttribute("value", parameter.ColorBrightness.ToString()); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region 主颜色 xmlComment = xmlDocument.CreateComment("主颜色"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "AlphaEdge"); item.SetAttribute("value", string.Concat("#", ColorUtility.ToHtmlStringRGB(parameter.MainColor))); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region 次要颜色 xmlComment = xmlDocument.CreateComment("次要颜色"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "viceColor"); item.SetAttribute("value", string.Concat("#", ColorUtility.ToHtmlStringRGB(parameter.ViceColor))); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region 更新间隔 xmlComment = xmlDocument.CreateComment("更新间隔"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "updateInterval"); item.SetAttribute("value", parameter.UpdateInterval.ToString()); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region 放大因子 xmlComment = xmlDocument.CreateComment("放大因子"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "amplificationFactor"); item.SetAttribute("value", parameter.AmplificationFactor.ToString()); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region 旋转速度 xmlComment = xmlDocument.CreateComment("旋转速度"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "rotateSpeed"); item.SetAttribute("value", parameter.RotateSpeed.ToString()); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region 基础字体颜色 xmlComment = xmlDocument.CreateComment("基础字体颜色"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "baseFontColor"); item.SetAttribute("value", string.Concat("#", ColorUtility.ToHtmlStringRGB(parameter.BaseFontColor))); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region 当前字体颜色 xmlComment = xmlDocument.CreateComment("当前字体颜色"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "currentFontColor"); item.SetAttribute("value", string.Concat("#", ColorUtility.ToHtmlStringRGB(parameter.CurrentFontColor))); root.AppendChild(xmlComment); root.AppendChild(item); #endregion #region 字体大小 xmlComment = xmlDocument.CreateComment("字体大小"); item = xmlDocument.CreateElement("item"); item.SetAttribute("name", "fontSize"); item.SetAttribute("value", parameter.FontSize.ToString()); root.AppendChild(xmlComment); root.AppendChild(item); #endregion xmlDocument.AppendChild(root); xmlDocument.InsertBefore(declaration, xmlDocument.DocumentElement); #region 生成Xml,UTF-8无BOM格式编码 System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false); StreamWriter sw = new StreamWriter(outPath, false, utf8); xmlDocument.Save(sw); sw.Close(); sw.Dispose(); #endregion }
public ActionResult EditSequence(int page, int id, FormCollection collection) { //Check Exists PolicyGroup policyGroup = new PolicyGroup(); policyGroup = policyGroupRepository.GetGroup(id); if (policyGroup == null) { ViewData["ActionMethod"] = "EditSequencePost"; return(View("RecordDoesNotExistError")); } //Check Access Rights RolesRepository rolesRepository = new RolesRepository(); if (!rolesRepository.HasWriteAccessToPolicyGroup(id)) { ViewData["Message"] = "You do not have access to this item"; return(View("Error")); } string[] sequences = collection["PolicySequence"].Split(new char[] { ',' }); int sequence = (page - 1 * 5) - 2; if (sequence < 0) { sequence = 1; } XmlDocument doc = new XmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); XmlElement rootElement = doc.CreateElement(string.Empty, "SequenceXML", string.Empty); doc.AppendChild(rootElement); foreach (string s in sequences) { string[] policyCityGroupItemPK = s.Split(new char[] { '_' }); int policyCityGroupItemId = Convert.ToInt32(policyCityGroupItemPK[0]); int versionNumber = Convert.ToInt32(policyCityGroupItemPK[1]); XmlElement itemElement = doc.CreateElement(string.Empty, "Item", string.Empty); XmlElement sequenceElement = doc.CreateElement(string.Empty, "Sequence", string.Empty); XmlCDataSection sequenceText = doc.CreateCDataSection(HttpUtility.HtmlEncode(sequence.ToString())); sequenceElement.AppendChild(sequenceText); itemElement.AppendChild(sequenceElement); XmlElement policyCityGroupItemIdElement = doc.CreateElement(string.Empty, "PolicyCityGroupItemId", string.Empty); XmlCDataSection policyCityGroupItemIdText = doc.CreateCDataSection(HttpUtility.HtmlEncode(policyCityGroupItemId.ToString())); policyCityGroupItemIdElement.AppendChild(policyCityGroupItemIdText); itemElement.AppendChild(policyCityGroupItemIdElement); XmlElement versionNumberElement = doc.CreateElement(string.Empty, "VersionNumber", string.Empty); XmlCDataSection versionNumberText = doc.CreateCDataSection(HttpUtility.HtmlEncode(versionNumber.ToString())); versionNumberElement.AppendChild(versionNumberText); itemElement.AppendChild(versionNumberElement); rootElement.AppendChild(itemElement); sequence = sequence + 1; } try { PolicyGroupSequenceRepository policyGroupSequenceRepository = new PolicyGroupSequenceRepository(); policyGroupSequenceRepository.UpdatePolicyCityGroupItemSequences(doc.OuterXml); } catch (SqlException ex) { //Versioning Error if (ex.Message == "SQLVersioningError") { ViewData["ReturnURL"] = "/PolicyCityGroupItem.mvc/EditSequence/" + id + "?page=" + page; return(View("VersionError")); } LogRepository logRepository = new LogRepository(); logRepository.LogError(ex.Message); ViewData["Message"] = "There was a problem with your request, please see the log file or contact an administrator for details"; return(View("Error")); } return(RedirectToAction("List", new { id = id })); }
/// <summary> /// setup the xmlDocument that holds the data to be return to the /// client /// </summary> /// <param name="xmlDoc"></param> /// <param name="parentNode"></param> private void CreateReturnXml(XmlDocument xmlDoc, XmlElement parentNode) { XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); // Create the root element XmlElement rootNode = xmlDoc.CreateElement("UploadReport"); xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement); xmlDoc.AppendChild(rootNode); // Create a new <Errors> element and add it to the root node xmlDoc.DocumentElement.PrependChild(parentNode); }
public static void clr_GetADobjects(SqlString ADpath, SqlString ADfilter, out SqlXml MemberList) { // Filter syntax: https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx // AD attributes: https://msdn.microsoft.com/en-us/library/ms675089(v=vs.85).aspx MemberList = new SqlXml(); //System.IO.StreamWriter file = Util.CreateLogFile(); SearchResultCollection results = null; Int32 itemcount = 0; try { XmlDocument doc = new XmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); XmlElement body = doc.CreateElement(string.Empty, "body", string.Empty); doc.AppendChild(body); ADcolsTable TblData = new ADcolsTable((string)ADfilter); DataTable tbl = TblData.CreateTable(); DataRow row; // Create key/value collection - key is (user) distinguishedname, value is object GUID. Dictionary<string, Guid> UserDStoGUID = new Dictionary<string, Guid>(); DirectoryEntry entry = new DirectoryEntry((string)ADpath); DirectorySearcher searcher = new DirectorySearcher(entry); searcher.Filter = (string)ADfilter; searcher.PageSize = 500; results = searcher.FindAll(); foreach (SearchResult searchResult in results) { itemcount++; DirectoryEntry item = searchResult.GetDirectoryEntry(); row = tbl.NewRow(); UACflags Item_UAC_flags = null; Int64 UserPasswordExpiryTimeComputed = 0; PropertyValueCollection ADGroupType = null; for (int i = 0; i < TblData.collist.Length; i++) { TableColDef coldef = TblData.collist[i]; switch(coldef.OPtype) { case "Adprop": if (coldef.ADpropName == "useraccountcontrol" && Item_UAC_flags != null) { row[i] = Item_UAC_flags.ADobj_flags; break; } PropertyValueCollection prop = Util.GetADproperty(item, coldef.ADpropName); if (prop != null) row[i] = prop.Value; break; case "UAC": if (Item_UAC_flags == null) { // Get UAC flags only once per AD object. Item_UAC_flags = new UACflags(Util.Get_userAccountControl(item, out UserPasswordExpiryTimeComputed)); } row[i] = Item_UAC_flags.GetFlag(coldef.ADpropName); break; case "ObjClass": row[i] = item.SchemaClassName; break; case "ObjGuid": row[i] = item.Guid; break; case "filetime": Int64 time = 0; if (coldef.ADpropName == "msDS-UserPasswordExpiryTimeComputed") time = UserPasswordExpiryTimeComputed; else time = Util.GetFileTime(searchResult, coldef.ADpropName); if(time > 0 && time != 0x7fffffffffffffff && time != -1) { //row[i] = DateTime.FromFileTimeUtc(time); row[i] = DateTime.FromFileTime(time); // Convert UTC to local time. } break; case "SID": row[i] = Util.GetSID(item, coldef.ADpropName); break; case "GrpCat": if (ADGroupType == null) ADGroupType = Util.GetADproperty(item, "grouptype"); row[i] = Util.GetGroupCategory(ADGroupType); break; case "GrpScope": if (ADGroupType == null) ADGroupType = Util.GetADproperty(item, "grouptype"); row[i] = Util.GetGroupScope(ADGroupType); break; } } tbl.Rows.Add(row); if (TblData.IsUser) { // Set UserMustChangePasswordAtNextLogon column value (for user objects). bool IsUsrChgPwd = false; if (row.IsNull("PasswordLastSet") && !row.IsNull("PasswordNeverExpires") && !row.IsNull("PasswordNotRequired") && !(bool)row["PasswordNeverExpires"] && !(bool)row["PasswordNotRequired"]) { IsUsrChgPwd = true; } row["UserMustChangePasswordAtNextLogon"] = IsUsrChgPwd; // Collect user distinguishedname into dictionary, value is object GUID. // This is needed later to set ManagerGUID column. UserDStoGUID.Add((string)row["distinguishedname"], (Guid)row["ObjectGUID"]); } // Save group members into the Xml document. if (TblData.IsGroup && item.Properties.Contains("member")) { PropertyValueCollection coll = Util.GetADproperty(item, "member"); string parent = (string)row["distinguishedname"]; Util.SaveGroupMembersToXml(doc, body, parent, coll); } } // endof: foreach (SearchResult searchResult in results) // All rows have been added to the dataset. // set ManagerGUID column for user objects. if (TblData.IsUser) { foreach (DataRow rowUsr in tbl.Rows) { object manager = rowUsr["Manager"]; // distinguishedname of Manager. if (manager == DBNull.Value) continue; Guid ManagerGUID; if (UserDStoGUID.TryGetValue((string)manager, out ManagerGUID)) rowUsr["ManagerGUID"] = ManagerGUID; } } // Return dataset to SQL server. ReturnDatasetToSqlServer(tbl); using (XmlNodeReader xnr = new XmlNodeReader(doc)) { MemberList = new SqlXml(xnr); } } catch (System.Runtime.InteropServices.COMException) { SqlContext.Pipe.Send("COMException in clr_GetADobjects. ItemCounter = " + itemcount.ToString()); throw; } catch (InvalidOperationException) { SqlContext.Pipe.Send("InvalidOperationException in clr_GetADobjects. ItemCounter = " + itemcount.ToString()); throw; } catch (NotSupportedException) { SqlContext.Pipe.Send("NotSupportedException in clr_GetADobjects. ItemCounter = " + itemcount.ToString()); throw; } catch (Exception) { SqlContext.Pipe.Send("Exception in clr_GetADobjects. ItemCounter = " + itemcount.ToString()); throw; } finally { if (null != results) { results.Dispose(); // To prevent memory leaks, always call results = null; // SearchResultCollection.Dispose() manually. } } //file.Close(); }