public static Dictionary<string, string> GetBlockSources(string path) { Dictionary<string, string> ret = new Dictionary<string, string>(); XmlDocument doc = new XmlDocument(); doc.Load(path); foreach (XmlNode node in doc.GetElementsByTagName("block")) { string id = node.Attributes["id"].Value; if (node.Attributes["src"] != null) { ret.Add(id, node.Attributes["src"].Value); } string fontPath = GetFontPath(node); if (fontPath != string.Empty) { ret.Add(id, fontPath); } } doc.RemoveAll(); doc = null; return (ret); }
public void CheckMarkerPaths(string fileName) { DirectoryInfo markerDir = new DirectoryInfo(Path.Combine(Path.GetDirectoryName(fileName), "Markers")); XmlDocument doc = new XmlDocument(); doc.Load(fileName); if (doc.GetElementsByTagName("markers").Count == 0) return; XmlNodeList markerList = doc.GetElementsByTagName("marker"); if (markerList.Count > 0) { foreach (XmlNode node in markerList) { if(node.Attributes == null || node.Attributes["id"] == null) throw new UserMessageException("Marker id doesn't exist for 'Marker' element in file {1}", fileName); if (node.Attributes == null || node.Attributes["name"] == null) throw new UserMessageException("Marker name doesn't exist for 'Marker' element in file {1}", fileName); string id = node.Attributes["id"].Value; string name = node.Attributes["name"].Value; FileInfo[] f = markerDir.GetFiles(string.Format("{0}.*", id), SearchOption.TopDirectoryOnly); if (f.Length == 0) { throw new UserMessageException("Marker image not found with id {0} and name {1} in file {2}", id, name, fileName); } } } doc.RemoveAll(); doc = null; }
public bool Save(string path) { bool saved = true; XmlDocument m_Xdoc = new XmlDocument(); try { m_Xdoc.RemoveAll(); XmlNode node = m_Xdoc.CreateXmlDeclaration("1.0", "utf-8", string.Empty); m_Xdoc.AppendChild(node); node = m_Xdoc.CreateComment($" Profile Configuration Data. {DateTime.Now} "); m_Xdoc.AppendChild(node); node = m_Xdoc.CreateWhitespace("\r\n"); m_Xdoc.AppendChild(node); node = m_Xdoc.CreateNode(XmlNodeType.Element, "Profile", null); m_Xdoc.AppendChild(node); m_Xdoc.Save(path); } catch { saved = false; } return saved; }
private void SaveAsXML() { DataTable dt = (DataTable)bindingSource.DataSource; XmlDocument doc = new XmlDocument(); XmlNode rootNode = doc.CreateNode(XmlNodeType.Element,"root", null); foreach (DataRow row in dt.Rows) { object[] values = row.ItemArray; XmlNode prop = doc.CreateNode(XmlNodeType.Element, "propertyset", null); XmlNode name = doc.CreateNode(XmlNodeType.Element, "name", null); XmlNode value = doc.CreateNode(XmlNodeType.Element, "value", null); name.InnerText = (string)values[0]; value.InnerText = (string)values[1]; prop.AppendChild(name); prop.AppendChild(value); rootNode.AppendChild(prop); } doc.AppendChild(rootNode); string file = Path.Combine(GetExecutingDir(), xmlPropertyFileName); if (File.Exists(file)) { File.Delete(file); } doc.Save(file); doc.RemoveAll(); doc = null; }
//add any properties you need, declarations and xelements to methods below public static void Save() { var document = new XmlDocument(); document.Load(path); document.RemoveAll(); //add to doc somehow? document.Save(path); }
public static void Execute(string inputFile, string output) { if (!_insertHomographClass && !_insertSenseNumClass) return; var xmlDoc = new XmlDocument(); xmlDoc.XmlResolver = FileStreamXmlResolver.GetNullResolver(); var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); const string xhtmlns = "http://www.w3.org/1999/xhtml"; nsmgr.AddNamespace("x", xhtmlns); xmlDoc.Load(inputFile); var changed = false; if (_insertSenseNumClass) { var senseNums = xmlDoc.SelectNodes("//x:span[@class='headref']/x:span", nsmgr); foreach (XmlElement senseNum in senseNums) { if (!senseNum.HasAttribute("class")) { senseNum.SetAttribute("class", "revsensenumber"); changed = true; } } } if (_insertHomographClass) { var nodes = xmlDoc.SelectNodes("//x:span[@class='headref']/text()", nsmgr); foreach (XmlNode node in nodes) { var match = Regex.Match(node.InnerText, "([^0-9]*)([0-9]*)"); if (match.Groups[2].Length > 0) { var homographNode = xmlDoc.CreateElement("span", xhtmlns); homographNode.SetAttribute("class", "revhomographnumber"); homographNode.InnerText = match.Groups[2].Value; node.InnerText = match.Groups[1].Value; node.ParentNode.InsertAfter(homographNode, node); changed = true; } } } if (changed) { var xmlWriter = XmlWriter.Create(output); xmlDoc.WriteTo(xmlWriter); xmlWriter.Close(); } xmlDoc.RemoveAll(); }
public ProblemXML(String filename,bool isReadOnly) { FileName = filename; xd = new XmlDocument(); if (isReadOnly) { if (File.Exists(FileName)) { try { xd.Load(FileName); } catch { Console.WriteLine("文件不是有效的XML"); isError = true; } } else { Console.WriteLine("文件不存在"); isError = true; } } else { if (FileName != "") { XmlElement xmlelem; XmlNode xmlnode; xd.RemoveAll(); //加入xml声明 xmlnode = xd.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xd.AppendChild(xmlnode); //加入一个根元素 xmlelem = xd.CreateElement("", "ROOT", ""); xd.AppendChild(xmlelem); xd.Save(FileName); } else { Console.WriteLine("文件不存在"); isError = true; } } }
internal List<SetGuid> GetGuids() { List<SetGuid> ret = new List<SetGuid>(); XmlDocument doc = new XmlDocument(); FileInfo[] d = new DirectoryInfo(p).GetFiles("*.xml"); FileInfo f = null; if (d.Length > 0) { f = d[0]; } if (f != null) { doc.Load(f.FullName); XmlNode n = doc.GetElementsByTagName("set").Item(0); Guid s = Guid.Empty; if (n.Attributes["id"] != null) { s = Guid.Parse(n.Attributes["id"].Value); } XmlNodeList l = doc.GetElementsByTagName("card"); foreach (XmlNode node in l) { if (node.Attributes["id"] != null) { Guid g = Guid.Parse(node.Attributes["id"].Value); SetGuid setguid = new SetGuid() { set = s, card = g }; ret.Add(setguid); } } } doc.RemoveAll(); doc = null; return (ret); }
public OfficeXML(String filename) { FileName = filename; XmlDocument xd = new XmlDocument(); if (FileName != "") { XmlElement xmlelem; XmlNode xmlnode; if (File.Exists(FileName)) { try { xd.Load(FileName); } catch { xd.RemoveAll(); //加入xml声明 xmlnode = xd.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xd.AppendChild(xmlnode); //加入一个根元素 xmlelem = xd.CreateElement("", "ROOT", ""); xd.AppendChild(xmlelem); } } else { //加入xml声明 xmlnode = xd.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xd.AppendChild(xmlnode); //加入一个根元素 xmlelem = xd.CreateElement("", "ROOT", ""); xd.AppendChild(xmlelem); } xd.Save(FileName); } }
private void openDefinitionButton_Click(object sender, EventArgs e) { if (definitionOpenDialog.ShowDialog() != DialogResult.Cancel) { string def = definitionOpenDialog.FileName; rootDirTextBox.Text = Path.GetDirectoryName(def); XmlDocument doc = new XmlDocument(); doc.Load(def); XmlNodeList list = doc.GetElementsByTagName("proxygen"); string relPath = list.Item(0).Attributes["definitionsrc"].Value; proxydefPathTextBox.Text = Path.Combine(rootDirTextBox.Text, relPath); doc.RemoveAll(); doc = null; if (!ValidateTemplatePaths()) { proxydefPathTextBox.Text = string.Empty; rootDirTextBox.Text = string.Empty; MessageBox.Show("Template contains an invalid image path"); } else { generateProxyButton.Enabled = true; } } }
static void Main(string[] args) { Console.WriteLine("========================================="); Console.WriteLine("= " + DateTime.Now.AddDays(-1).ToString("MMMM dd, yyyy").ToUpper().PadLeft(17) + " - " + DateTime.Now.ToString("MMMM dd, yyyy").ToUpper().PadRight(17) + " ="); Console.WriteLine("========================================="); ArrayList al = new ArrayList(); //NON-FG ArrayList al2 = new ArrayList(); //FG string invoiceNum = ""; XmlDocument doc = new XmlDocument(); methods me = new methods(); string lineItemNum = ""; //NON-FINISHED GOODS THAT WERE INVOICED al = me.getTodaysInvoices(); foreach (object[] row in al) { Console.WriteLine("WIKey:" + row[0].ToString()); for (int i = 1; i < row.Length; i++) { Console.WriteLine(" -"+ row[i] as string); } invoiceNum = row[1].ToString(); //2nd column in vw_PTI_invoice lineItemNum = row[4].ToString(); //5th column in vw_PTI_invoice Console.WriteLine("Line Item ID: " + lineItemNum); doc = me.createInvoiceByLineItemRequest(invoiceNum, lineItemNum); me.parseResponse(me.sendXmlRequest(doc)); try { doc.Save("../../XML/" + invoiceNum + " - " + lineItemNum + "_req.xml"); } catch (Exception e) { Console.WriteLine(e.ToString()); } doc.RemoveAll(); int settlementNeeded = Convert.ToInt32(row[7]); if (settlementNeeded == 1) { Console.WriteLine("CREDIT CARD SETTLEMENT FOR " + lineItemNum +"\n"); string orderID = me.getOrderID(lineItemNum); XmlDocument d = me.createSettlementByOrderRequest(orderID); me.parseResponse_settlement(me.sendXmlRequest_Settlement(d)); d.RemoveAll(); } Console.WriteLine("========================================"); } //FINISHED GOODS ORDERS THAT WERE INVOICED al2 = me.getTodaysFGInvoices(); foreach (object[] row in al2) { Console.WriteLine("WIKey:" + row[0].ToString()); for (int i = 0; i < row.Length; i++) { Console.WriteLine(" -" + row[i] as string); } invoiceNum = row[2].ToString(); //3rd column in vw_PTI_invoiceFG string hold = row[6] as string; //8th column in vw_PTI_invoiceFG //string fgOrderNum = me.finGoodSubstring(hold); string FGwebOrderID = hold; string s = me.getOrderID(FGwebOrderID); Console.WriteLine("Web Order ID: " + hold /*FGwebOrderID*/ + "\n"); doc = me.createInvoiceByLineItemRequest(invoiceNum, hold/*FGwebOrderID*/); me.parseResponse(me.sendXmlRequest(doc)); doc.RemoveAll(); if (me.needsSettlement(s)) { Console.WriteLine("CREDIT CARD SETTLEMENT FOR FG" + FGwebOrderID + "Ord:" + s + "\n"); XmlDocument d = me.createSettlementByOrderRequest(s); me.parseResponse_settlement(me.sendXmlRequest_Settlement(d)); d.RemoveAll(); } Console.WriteLine("========================================"); } // // MANUAL FG ORDER INVOICE // /*al2 = me.getTodaysFGInvoices(); foreach (object[] row in al2) { Console.WriteLine("WIKey:" + row[0].ToString()); for (int i = 0; i < row.Length; i++) { Console.WriteLine(" -" + row[i] as string); } invoiceNum = "134428"; string hold = row[6] as string; //8th column in vw_PTI_invoiceFG //string fgOrderNum = me.finGoodSubstring(hold); string FGwebOrderID = hold; string s = me.getOrderID(FGwebOrderID); Console.WriteLine("Web Order ID: " + hold + "\n"); doc = me.createInvoiceByLineItemRequest(invoiceNum, hold); me.parseResponse(me.sendXmlRequest(doc)); doc.RemoveAll(); if (me.needsSettlement(s)) { Console.WriteLine("CREDIT CARD SETTLEMENT FOR FG" + FGwebOrderID + "Ord:" + s + "\n"); XmlDocument d = me.createSettlementByOrderRequest(s); me.parseResponse_settlement(me.sendXmlRequest_Settlement(d)); d.RemoveAll(); } Console.WriteLine("========================================"); } */ // // // }
private void LoadXML(string path) { DataTable dt = SetupDataTable(); XmlDocument doc = new XmlDocument(); doc.Load(path); XmlNodeList list = doc.GetElementsByTagName("propertyset"); foreach (XmlNode node in list) { string[] values = new string[2]; values[0] = node.ChildNodes[0].InnerText; values[1] = node.ChildNodes[1].InnerText; dt.Rows.Add(values); } bindingSource.DataSource = dt; doc.RemoveAll(); doc = null; }
private static void CreateConfigurationElement(XmlDocument document) { if (document.DocumentElement != null) document.RemoveAll(); XmlElement element = document.CreateElement(ConfigurationElementName); document.AppendChild(element); }
private void SaveNotation_Click(object sender, RoutedEventArgs e) { ReportStatusBar.clearReportMessage(); if (String.IsNullOrEmpty(NotationNameTextBox.Text)) { ReportStatusBar.ShowStatus("Notation name is not provided!", ReportIcon.Error); logger.log("Generating \'" + NotationNameTextBox.Text + "\' failed -> " + "Notation name is not provided!", ReportIcon.Error); NotationNameTextBox.Focus(); } else { string xamlText = new TextRange(GraphicsInput.Document.ContentStart, GraphicsInput.Document.ContentEnd).Text; if (String.IsNullOrEmpty(xamlText)) { ReportStatusBar.ShowStatus("Notation XAML is missing!", ReportIcon.Error); logger.log("Generating \'" + NotationNameTextBox.Text + "\' failed -> " + "Notation XAML is missing!", ReportIcon.Error); GraphicsInput.Focus(); } else { string dataText = new TextRange(XMLDataInput.Document.ContentStart, XMLDataInput.Document.ContentEnd).Text; if (String.IsNullOrEmpty(dataText)) { ReportStatusBar.ShowStatus("Data XML is missing!", ReportIcon.Error); logger.log("Generating \'" + NotationNameTextBox.Text + "\' failed -> " + "Data XML is missing!", ReportIcon.Error); XMLDataInput.Focus(); } else { XmlDocument xdoc = new XmlDocument(); XmlNode itemNode = xdoc.CreateElement("item"); XmlAttribute nameAttr = xdoc.CreateAttribute("name"); nameAttr.Value = NotationNameTextBox.Text; itemNode.Attributes.Append(nameAttr); XmlAttribute typeAttr = xdoc.CreateAttribute("type"); if (visType == VisualisationType.XAML) typeAttr.Value = "XAML"; else if (visType == VisualisationType.SVG) typeAttr.Value = "SVG"; itemNode.Attributes.Append(typeAttr); //data XML String dataXML = dataText; xdoc.LoadXml(dataXML); XmlNode dataNode = xdoc.CreateElement("data"); dataNode.AppendChild(xdoc.DocumentElement.Clone()); string dataNodeName = xdoc.DocumentElement.Name; //name of the data XML document element to be the name of (template match="name") itemNode.AppendChild(dataNode); xdoc.RemoveAll(); //create transforamtion Collection<XmlNode> transXSLTemplates = parseAnnotatedGraphics(xamlText, dataNodeName, dataNode.FirstChild); if (transXSLTemplates.Count > 0) { XmlNode transformationNode = xdoc.CreateElement("trans"); foreach (XmlNode x in transXSLTemplates) transformationNode.AppendChild(transformationNode.OwnerDocument.ImportNode(x, true)); itemNode.AppendChild(transformationNode); xdoc.RemoveAll(); //save notation XML //MessageBox.Show(prettyPrinter.PrintToString(itemNode.OuterXml)); //find ToolBoxItems.xml string customElementsFile = getDirectory("Resources\\ToolBoxItems.xml"); customElementsFile = (customElementsFile.Replace("file:\\", "")); XmlDocument customElementsDoc = new XmlDocument(); customElementsDoc.Load(customElementsFile); XmlNode customItemsNode = customElementsDoc.SelectSingleNode("items"); if (customItemsNode != null) { customItemsNode.AppendChild(customItemsNode.OwnerDocument.ImportNode(itemNode, true)); customElementsDoc.Save(customElementsFile); //create visual element if (visType == VisualisationType.XAML) { XAMLRenderer rend = new XAMLRenderer(); VisualElement v = rend.render(itemNode) as VisualElement; if (v != null) { XAMLRenderCanvas.Children.Clear(); XAMLRenderCanvas.Children.Add(v); ReportStatusBar.ShowStatus("XAML Notation Saved", ReportIcon.OK); logger.log("XAML Notation \'" + NotationNameTextBox.Text + "\' saved in notation repository.", ReportIcon.OK); SkinOutputTabControl.SelectedIndex = 0; //Clear callforlist callForList.Clear(); } else { ReportStatusBar.ShowStatus("XAML Notation failed!", ReportIcon.OK); logger.log("XAML Notation \'" + NotationNameTextBox.Text + "\' failed.", ReportIcon.Error); } } else if (visType == VisualisationType.SVG) { ReportStatusBar.ShowStatus("SVG Notation Saved", ReportIcon.OK); logger.log("SVG Notation \'" + NotationNameTextBox.Text + "\' saved in notation repository.", ReportIcon.OK); } } else { ReportStatusBar.ShowStatus("Could not locate custom items", ReportIcon.Error); logger.log("Generating \'" + NotationNameTextBox.Text + "\' failed.", ReportIcon.Error); } } } } } }
public static void PreLoadCustomMeta(Workspace ws) { _agentsXMLNode = null; _typesXMLNode = null; string bbPath = ws.getBlackboardPath(); if (string.IsNullOrEmpty(bbPath) || !File.Exists(bbPath)) { return; } XmlDocument bbfile = new XmlDocument(); try { FileStream fs = new FileStream(bbPath, FileMode.Open, FileAccess.Read, FileShare.Read); bbfile.Load(fs); fs.Close(); XmlNode root = bbfile.ChildNodes[1]; if (root.Name == "meta") { foreach(XmlNode xmlNode in root.ChildNodes) { if (xmlNode.Name == "agents") { _agentsXMLNode = xmlNode; } else if (xmlNode.Name == "types") { _typesXMLNode = xmlNode; } } } else if (root.Name == "agents") { _agentsXMLNode = root; } } catch (Exception e) { MessageBox.Show(e.Message, Resources.LoadError, MessageBoxButtons.OK); bbfile.RemoveAll(); } }
static int Main(string[] args) { log("starting analysis launcher"); int iPassed = (int)Launcher.ExitCodeEnum.Passed;//variable to keep track of whether all of the SLAs passed try { if (args.Length != 3) { ShowHelp(); return (int)Launcher.ExitCodeEnum.Aborted; } string lrrlocation = args[0]; string lralocation = args[1]; string htmlLocation = args[2]; log("creating analysis COM object"); LrAnalysis analysis = new LrAnalysis(); Session session = analysis.Session; log("creating analysis session"); if (session.Create(lralocation, lrrlocation)) { log("analysis session created"); log("creating HTML reports"); HtmlReportMaker reportMaker = session.CreateHtmlReportMaker(); reportMaker.CreateDefaultHtmlReport(Path.Combine(Path.GetDirectoryName(htmlLocation), "IE", Path.GetFileName(htmlLocation)), ApiBrowserType.IE); reportMaker.CreateDefaultHtmlReport(Path.Combine(Path.GetDirectoryName(htmlLocation), "Netscape", Path.GetFileName(htmlLocation)), ApiBrowserType.Netscape); log("HTML reports created"); XmlDocument xmlDoc = new XmlDocument(); log("loading errors, if any"); session.ErrorMessages.LoadValuesIfNeeded(); if (session.ErrorMessages.Count != 0) { log("error count: " + session.ErrorMessages.Count); if (session.ErrorMessages.Count > 1000) { log("more then 1000 error during scenario run, analyzing only the first 1000."); } log(Resources.ErrorsReportTitle); XmlElement errorRoot = xmlDoc.CreateElement("Errors"); xmlDoc.AppendChild(errorRoot); int limit = 1000; ErrorMessage[] errors = session.ErrorMessages.ToArray(); //foreach (ErrorMessage err in session.ErrorMessages) for (int i = 0; i < limit && i < errors.Length; i++) { ErrorMessage err = errors[i]; XmlElement elem = xmlDoc.CreateElement("Error"); elem.SetAttribute("ID", err.ID.ToString()); elem.AppendChild(xmlDoc.CreateTextNode(err.Name)); log("ID: " + err.ID + " Name: " + err.Name); errorRoot.AppendChild(elem); } xmlDoc.Save(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(lrrlocation)), "Errors.xml")); xmlDoc.RemoveAll(); log (""); } log("closing session"); session.Close(); log(Resources.SLAReportTitle); log("calculating SLA"); SlaResult slaResult = Session.CalculateSla(lralocation, true); log("SLA calculation done"); XmlElement root = xmlDoc.CreateElement("SLA"); xmlDoc.AppendChild(root); int iCounter = 0; // set counter log("WholeRunRules : " + slaResult.WholeRunRules.Count); foreach (SlaWholeRunRuleResult a in slaResult.WholeRunRules) { log(Resources.DoubleLineSeperator); XmlElement elem; if (a.Measurement.Equals(SlaMeasurement.PercentileTRT)) { SlaPercentileRuleResult b = slaResult.TransactionRules.PercentileRules[iCounter]; elem = xmlDoc.CreateElement(b.RuleName.Replace(" ", "_")); //no white space in the element name log("Transaction Name : " + b.TransactionName); elem.SetAttribute("TransactionName", b.TransactionName.ToString()); log("Percentile : " + b.Percentage); elem.SetAttribute("Percentile", b.Percentage.ToString()); elem.SetAttribute("FullName", b.RuleUiName); log("Full Name : " + b.RuleUiName); log("Measurement : " + b.Measurement); elem.SetAttribute("Measurement", b.Measurement.ToString()); log("Goal Value : " + b.GoalValue); elem.SetAttribute("GoalValue", b.GoalValue.ToString()); log("Actual value : " + b.ActualValue); elem.SetAttribute("ActualValue", b.ActualValue.ToString()); log("status : " + b.Status); elem.AppendChild(xmlDoc.CreateTextNode(b.Status.ToString())); if (b.Status.Equals(SlaRuleStatus.Failed)) // 0 = failed { iPassed = (int)Launcher.ExitCodeEnum.Failed; } iCounter++; } else { elem = xmlDoc.CreateElement(a.RuleName.Replace(" ", "_")); //no white space in the element name elem.SetAttribute("FullName", a.RuleUiName); log("Full Name : " + a.RuleUiName); log("Measurement : " + a.Measurement); elem.SetAttribute("Measurement", a.Measurement.ToString()); log("Goal Value : " + a.GoalValue); elem.SetAttribute("GoalValue", a.GoalValue.ToString()); log("Actual value : " + a.ActualValue); elem.SetAttribute("ActualValue", a.ActualValue.ToString()); log("status : " + a.Status); elem.AppendChild(xmlDoc.CreateTextNode(a.Status.ToString())); if (a.Status.Equals(SlaRuleStatus.Failed)) // 0 = failed { iPassed = (int)Launcher.ExitCodeEnum.Failed; } } root.AppendChild(elem); log(Resources.DoubleLineSeperator); } iCounter = 0; // reset counter log("TimeRangeRules : " + slaResult.TimeRangeRules.Count); foreach (SlaTimeRangeRuleResult a in slaResult.TimeRangeRules) { log(Resources.DoubleLineSeperator); XmlElement rule; if (a.Measurement.Equals(SlaMeasurement.AverageTRT)) { SlaTransactionTimeRangeRuleResult b = slaResult.TransactionRules.TimeRangeRules[iCounter]; rule = xmlDoc.CreateElement(b.RuleName.Replace(" ", "_")); //no white space in the element name log("Transaction Name: " + b.TransactionName); rule.SetAttribute("TransactionName", b.TransactionName); log("Full Name : " + b.RuleUiName); rule.SetAttribute("FullName", b.RuleUiName); log("Measurement : " + b.Measurement); rule.SetAttribute("Measurement", b.Measurement.ToString()); log("SLA Load Threshold Value : " + b.CriteriaMeasurement); rule.SetAttribute("SLALoadThresholdValue", b.CriteriaMeasurement.ToString()); log("LoadThresholds : " + b.LoadThresholds.Count); foreach (SlaLoadThreshold slat in b.LoadThresholds) { XmlElement loadThr = xmlDoc.CreateElement("SlaLoadThreshold"); loadThr.SetAttribute("StartLoadValue", slat.StartLoadValue.ToString()); loadThr.SetAttribute("EndLoadValue", slat.EndLoadValue.ToString()); loadThr.SetAttribute("ThresholdValue", slat.ThresholdValue.ToString()); rule.AppendChild(loadThr); } XmlElement timeRanges = xmlDoc.CreateElement("TimeRanges"); log("TimeRanges : " + b.TimeRanges.Count); foreach (SlaTimeRangeInfo slatri in b.TimeRanges) { XmlElement subsubelem = xmlDoc.CreateElement("TimeRangeInfo"); subsubelem.SetAttribute("StartTime", slatri.StartTime.ToString()); subsubelem.SetAttribute("EndTime", slatri.EndTime.ToString()); subsubelem.SetAttribute("GoalValue", slatri.GoalValue.ToString()); subsubelem.SetAttribute("ActualValue", slatri.ActualValue.ToString()); subsubelem.SetAttribute("LoadValue", slatri.LoadValue.ToString()); subsubelem.InnerText = slatri.Status.ToString(); timeRanges.AppendChild(subsubelem); } rule.AppendChild(timeRanges); log("status : " + b.Status); rule.AppendChild(xmlDoc.CreateTextNode(b.Status.ToString())); if (b.Status.Equals(SlaRuleStatus.Failed)) // 0 = failed { iPassed = (int)Launcher.ExitCodeEnum.Failed; } iCounter++; } else { rule = xmlDoc.CreateElement(a.RuleName.Replace(" ", "_")); //no white space in the element name log("Full Name : " + a.RuleUiName); rule.SetAttribute("FullName", a.RuleUiName); log("Measurement : " + a.Measurement); rule.SetAttribute("Measurement", a.Measurement.ToString()); log("SLA Load Threshold Value : " + a.CriteriaMeasurement); rule.SetAttribute("SLALoadThresholdValue", a.CriteriaMeasurement.ToString()); log("LoadThresholds : " + a.LoadThresholds.Count); foreach (SlaLoadThreshold slat in a.LoadThresholds) { XmlElement loadThr = xmlDoc.CreateElement("SlaLoadThreshold"); loadThr.SetAttribute("StartLoadValue", slat.StartLoadValue.ToString()); loadThr.SetAttribute("EndLoadValue", slat.EndLoadValue.ToString()); loadThr.SetAttribute("ThresholdValue", slat.ThresholdValue.ToString()); rule.AppendChild(loadThr); } XmlElement timeRanges = xmlDoc.CreateElement("TimeRanges"); log("TimeRanges : " + a.TimeRanges.Count); foreach (SlaTimeRangeInfo slatri in a.TimeRanges) { XmlElement subsubelem = xmlDoc.CreateElement("TimeRangeInfo"); subsubelem.SetAttribute("StartTime", slatri.StartTime.ToString()); subsubelem.SetAttribute("EndTime", slatri.EndTime.ToString()); subsubelem.SetAttribute("GoalValue", slatri.GoalValue.ToString()); subsubelem.SetAttribute("ActualValue", slatri.ActualValue.ToString()); subsubelem.SetAttribute("LoadValue", slatri.LoadValue.ToString()); subsubelem.InnerText = slatri.Status.ToString(); timeRanges.AppendChild(subsubelem); } rule.AppendChild(timeRanges); log("status : " + a.Status); rule.AppendChild(xmlDoc.CreateTextNode(a.Status.ToString())); if (a.Status.Equals(SlaRuleStatus.Failed)) { iPassed = (int)Launcher.ExitCodeEnum.Failed; } } root.AppendChild(rule); log(Resources.DoubleLineSeperator); } //write XML to location: log("saving SLA.xml to " + Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(lrrlocation)), "SLA.xml")); xmlDoc.Save(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(lrrlocation)), "SLA.xml")); } else { log(Resources.CannotCreateSession); return (int)Launcher.ExitCodeEnum.Aborted; } log("closing analysis session"); session.Close(); } catch (TypeInitializationException ex) { if (ex.InnerException is UnauthorizedAccessException) log("UnAuthorizedAccessException: Please check the account privilege of current user, LoadRunner tests should be run by administrators."); else { log(ex.Message); log(ex.StackTrace); } return (int)Launcher.ExitCodeEnum.Aborted; } catch (Exception e) { log(e.Message); log(e.StackTrace); return (int)Launcher.ExitCodeEnum.Aborted; } // return SLA status code, if any SLA fails return a fail here. // writer.Flush(); // writer.Close(); return iPassed; }
/// <summary> /// Converts targets of the given scope into a string value for persisting</summary> /// <param name="scope">Target scope</param> /// <returns>String representation of targets</returns> protected virtual string SerializeTargets( TargetScope scope) { XmlDocument xmlDoc = new XmlDocument(); //xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes")); XmlElement root = xmlDoc.CreateElement("TcpTargets"); xmlDoc.AppendChild(root); try { foreach (TcpIpTargetInfo target in m_targets) { if (target.Scope != scope) continue; XmlElement elem = xmlDoc.CreateElement("TcpTarget"); elem.SetAttribute("name", target.Name); elem.SetAttribute("platform", target.Platform); elem.SetAttribute("endpoint", target.Endpoint); elem.SetAttribute("protocol", target.Protocol); if (scope != TargetScope.PerApp) elem.SetAttribute("provider", Id); if (target.FixedPort > 0) elem.SetAttribute("fixedport", target.FixedPort.ToString()); root.AppendChild(elem); } if (xmlDoc.DocumentElement.ChildNodes.Count == 0) xmlDoc.RemoveAll(); } catch { xmlDoc.RemoveAll(); } return xmlDoc.InnerXml; }
private void GetFaultsTree() { Response.Charset = "utf-8"; Response.Expires = -1; string ids = Request.QueryString["id"] != null ? Request.QueryString["id"].ToString() : string.Empty; string output = Request.QueryString["out"] != null ? Request.QueryString["out"].ToString() : "xml"; if (ids == "undefined") { Response.End(); } int n = 0; if (ids == string.Empty) ///建立树的根节点。 { this.thesql = "select distinct t.fault_group_code as id,a.fault_group_name as name from rmes_rel_station_faultgroup t left join code_fault_group a on a.fault_group_code = t.fault_group_code where t.company_code='C2' order by a.fault_group_name"; } else { char[] sep1 = { '_' }; string[] arr = ids.Split(sep1); n = arr.Length; switch (n) { case 1: //strSQL = "select "; this.thesql = "select t.fault_place_code as id,a.fault_place_name as name from rmes_rel_group_faultplace t left join code_fault_place a on a.fault_place_code = t.fault_place_code where t.company_code='C2' and t.fault_group_code='" + arr[0] + "' order by a.fault_place_name"; break; case 2: this.thesql = "select t.fault_part_code as id,a.fault_part_name as name from rmes_rel_faultplace_faultpart t left join code_fault_part a on a.fault_part_code = t.fault_part_code where t.company_code='C2' and t.pline_type_code in (select x.pline_type_code from code_fault_group x where x.fault_group_code='" + arr[0] + "') and t.fault_group_code='" + arr[0] + "' and t.fault_place_code='" + arr[1] + "' order by a.fault_part_name"; break; case 3: this.thesql = "select t.fault_code as id,a.fault_name as name from rmes_rel_faultpart_fault t left join code_fault a on a.fault_code = t.fault_code where t.company_code='C2' and t.pline_type_code in (select x.pline_type_code from code_fault_group x where x.fault_group_code='" + arr[0] + "') and t.fault_group_code='" + arr[0] + "' and t.fault_place_code='" + arr[1] + "' and t.fault_part_code = '" + arr[2] + "' order by a.fault_name"; break; default: this.thesql = ""; break; } } string retStr = ""; if (this.thesql != string.Empty) { dataConn dc = new dataConn(); dc.OpenConn(); dc.theComd.CommandType = CommandType.Text; dc.theComd.CommandText = thesql; OracleDataReader dr = dc.theComd.ExecuteReader(); string prefix = (ids == string.Empty) ? "" : (ids + "_"); if (output == "xml") { Response.ContentType = "text/xml"; System.Xml.XmlDocument docXML = new System.Xml.XmlDocument(); System.Xml.XmlElement allnode = docXML.CreateElement("root"); while (dr.Read()) { System.Xml.XmlElement emper = docXML.CreateElement("item"); emper = docXML.CreateElement("item"); emper.SetAttribute("id", prefix + dr["id"].ToString()); emper.InnerXml = "<content><name id=\"" + prefix + dr["id"].ToString() + "\">" + dr["name"].ToString() + "</name></content>"; if (n != 3) { emper.SetAttribute("state", "closed"); } allnode.AppendChild(emper); } if (allnode != null && allnode.ChildNodes.Count > 0) { docXML.AppendChild(allnode); retStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + docXML.InnerXml; docXML.RemoveAll(); docXML = null; } } if (output == "json") { Response.ContentType = "text/html"; string name = "", id = ""; retStr = ""; while (dr.Read()) { id = dr["id"].ToString(); name = dr["name"].ToString(); retStr += "{ \"attr\":{\"id\":\"" + prefix + id + "\"},\"data\":{\"title\":\"" + name + "\"} },\r\n"; } //if (retStr.EndsWith(",")) retStr = retStr.Substring(0, retStr.Length - 1); retStr = "[ \r\n" + retStr + " ]"; } dc.theConn.Close(); } Response.Write(retStr); Response.End(); }
public static SceneObjectGroup FromXml2Format(string xmlData, IScene scene) { //m_log.DebugFormat("[SOG]: Starting deserialization of SOG"); //int time = Util.EnvironmentTickCount(); XmlDocument doc = new XmlDocument (); try { doc.LoadXml (xmlData); SceneObjectGroup grp = InternalFromXml2Format (doc, scene); grp.XMLRepresentation = Encoding.UTF8.GetBytes(doc.OuterXml); return grp; } catch (Exception e) { m_log.ErrorFormat ("[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData); return null; } finally { doc.RemoveAll (); doc = null; } }
public static SceneObjectGroup FromXml2Format(MemoryStream ms, IScene scene) { //m_log.DebugFormat("[SOG]: Starting deserialization of SOG"); //int time = Util.EnvironmentTickCount(); XmlDocument doc = new XmlDocument (); SceneObjectGroup grp = null; try { doc.Load(ms); grp = InternalFromXml2Format (doc, scene); grp.XMLRepresentation = ms.ToArray(); return grp; } catch (Exception e) { m_log.ErrorFormat("[SERIALIZER]: Deserialization of xml failed with {0}", e); return grp; } finally { doc.RemoveAll (); doc = null; } }
public void rexSetECAttributes(string vPrimLocalId, Dictionary<string, string> attributes, string typeName, string name) { SceneObjectPart target = World.GetSceneObjectPart(System.Convert.ToUInt32(vPrimLocalId, 10)); if (target != null) { RexObjectProperties rop = m_rexObjects.GetObject(target.UUID); if (rop != null) { try { // Parse the old xmldata for modifications XmlDocument xml = new XmlDocument(); XmlElement compElem = null; XmlElement entityElem = null; try { xml.LoadXml(rop.RexData); entityElem = (XmlElement)xml.GetElementsByTagName("entity")[0]; } catch (Exception) { // If parsing fails, we'll just create a new empty entity element (no previous xml data or it was malformed) xml.RemoveAll(); } // Search for the component if (entityElem == null) { entityElem = xml.CreateElement("entity"); xml.AppendChild(entityElem); } XmlNodeList components = entityElem.GetElementsByTagName("component"); foreach (XmlNode node in components) { // Check for component typename match XmlAttribute typeAttr = node.Attributes["type"]; if ((typeAttr != null) && (typeAttr.Value == typeName)) { String compName = ""; if (node.Attributes["name"] != null) compName = node.Attributes["name"].Value; // Check for component name match, or empty search name if ((name.Length == 0) || (name == compName)) { compElem = (XmlElement)node; break; } } } // If component not found, prepare new if (compElem == null) { compElem = xml.CreateElement("component"); compElem.SetAttribute("type", typeName); if (name.Length > 0) compElem.SetAttribute("name", name); entityElem.AppendChild(compElem); } // Remove any existing attributes while (compElem.FirstChild != null) { compElem.RemoveChild(compElem.FirstChild); } // Fill the attributes from the dictionary foreach (KeyValuePair<String, String> kvp in attributes) { XmlElement attributeElem = xml.CreateElement("attribute"); attributeElem.SetAttribute("name", kvp.Key); attributeElem.SetAttribute("value", kvp.Value); compElem.AppendChild(attributeElem); } // Convert xml to string StringBuilder xmlText = new StringBuilder(); XmlWriter writer = XmlWriter.Create(xmlText); xml.Save(writer); String text = xmlText.ToString(); // Remove the encoding tag, for some reason Naali doesn't like it int idx = text.IndexOf("?>"); if ((idx >= 0) && (idx < text.Length)) text = text.Substring(idx + 2); // Check for reasonable data size before setting rexfreedata if (text.Length <= 1000) { rop.RexData = text; // Need to manually replicate to all users m_rexObjects.SendPrimFreeDataToAllUsers(target.UUID, text); } else m_log.Warn("[REXSCRIPT]: Too long (over 1000 chars) output data from rexSetECAttributes, not setting"); } catch (Exception e) { m_log.Warn("[REXSCRIPT]: rexSetECAttributes exception: " + e.Message); } } } else { m_log.Warn("[REXSCRIPT]: rexSetECAttributes, target prim not found:" + vPrimLocalId); } }
//===================================================================== /// <summary> /// This method applies the branding package transforms. /// </summary> /// <param name="document">The current document.</param> /// <param name="key">The document's unique identifier.</param> private void ApplyBranding(XmlDocument document, string key) { if(m_brandingTransform != null) { #if DEBUG WriteMessage(MessageLevel.Info, " Branding topic {0} ({1}) SelfBranded={2}", key, m_locale, m_selfBranded); #endif try { XmlDocument v_tempDocument = new XmlDocument(); v_tempDocument.LoadXml(document.OuterXml); // The default xhtml namespace is required for the branding transforms to work, if(String.IsNullOrEmpty(v_tempDocument.DocumentElement.GetAttribute("xmlns"))) { v_tempDocument.DocumentElement.SetAttribute("xmlns", s_xhtmlNamespace); v_tempDocument.LoadXml(v_tempDocument.OuterXml); } SetSelfBranding(v_tempDocument, m_selfBranded); #if DEBUG//_NOT try { String v_tempPath = Path.GetFullPath("PreBranding"); if(!Directory.Exists(v_tempPath)) { Directory.CreateDirectory(v_tempPath); } v_tempPath = Path.Combine(v_tempPath, key.Replace(':', '_').Replace('.', '_') + ".htm"); v_tempDocument.Save(v_tempPath); } catch { } #endif #if DEBUG_NOT String v_tempBrandingPath = Path.GetFullPath("TempBranding"); if (!Directory.Exists (v_tempBrandingPath)) { Directory.CreateDirectory (v_tempBrandingPath); } v_tempBrandingPath = Path.Combine (v_tempBrandingPath, key.Replace (':', '_').Replace ('.', '_') + ".htm"); using (FileStream v_stream = new FileStream (v_tempBrandingPath, FileMode.Create, FileAccess.ReadWrite)) #else using(Stream v_stream = new MemoryStream()) #endif { try { XPathNavigator v_navigator = v_tempDocument.CreateNavigator(); using(XmlWriter v_writer = XmlWriter.Create(v_stream, m_brandingTransform.OutputSettings)) { m_brandingTransform.Transform(v_navigator, m_transformArguments, v_writer); } XmlReaderSettings v_readerSettings = new XmlReaderSettings(); v_readerSettings.ConformanceLevel = ConformanceLevel.Fragment; v_readerSettings.CloseInput = true; v_stream.Seek(0, SeekOrigin.Begin); using(XmlReader v_reader = XmlReader.Create(v_stream, v_readerSettings)) { v_tempDocument.RemoveAll(); v_tempDocument.Load(v_reader); } RemoveUnusedNamespaces(v_tempDocument); using(XmlReader v_reader = new SpecialXmlReader(v_tempDocument.OuterXml, this)) { document.RemoveAll(); document.Load(v_reader); } #if DEBUG//_NOT try { String v_tempPath = Path.GetFullPath("PostBranding"); if(!Directory.Exists(v_tempPath)) { Directory.CreateDirectory(v_tempPath); } v_tempPath = Path.Combine(v_tempPath, key.Replace(':', '_').Replace('.', '_') + ".htm"); document.Save(v_tempPath); } catch { } #endif } catch(Exception exp) { WriteMessage(key, MessageLevel.Error, exp.Message); } } } catch(XsltException exp) { WriteMessage(key, MessageLevel.Error, "{0} at {1} {2} {3}", exp.Message, exp.SourceUri, exp.LineNumber, exp.LinePosition); #if DEBUG if(exp.InnerException != null) { WriteMessage(key, MessageLevel.Error, "[{0}] {1}", exp.InnerException.GetType().Name, exp.InnerException.Message); } #endif } catch(Exception exp) { WriteMessage(key, MessageLevel.Error, exp.Message); } } }
protected void Page_Load(object sender, EventArgs e) { try { // By default (false) it uses SQLite database (Database.db). You can switch to MS Access database (Database.mdb) by setting UseMDB = true // The SQLite loads dynamically its DLL from TreeGrid distribution, it chooses 32bit or 64bit assembly // The MDB can be used only on 32bit IIS mode !!! The ASP.NET service program must have write access to the Database.mdb file !!! bool UseMDB = false; // --- Response initialization --- Response.ContentType = "text/xml"; Response.Charset = "utf-8"; Response.AppendHeader("Cache-Control", "max-age=1, must-revalidate"); System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US"); // --- Database initialization --- string Path = System.IO.Path.GetDirectoryName(Context.Request.PhysicalPath); System.Data.IDbConnection Conn = null; System.Data.Common.DbDataAdapter Sql = null; System.Data.Common.DbCommandBuilder Bld = null; string SqlStr = "SELECT * FROM TableData"; System.Reflection.Assembly SQLite = null; // Required only for SQLite database if (UseMDB) // For MS Acess database { Conn = new System.Data.OleDb.OleDbConnection("Data Source=\"" + Path + "\\..\\Database.mdb\";Mode=Share Deny None;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Engine Type=5;Provider=\"Microsoft.Jet.OLEDB.4.0\";Jet OLEDB:System database=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1"); Sql = new System.Data.OleDb.OleDbDataAdapter(SqlStr, (System.Data.OleDb.OleDbConnection)Conn); } else // For SQLite database { SQLite = System.Reflection.Assembly.LoadFrom(Path + "\\..\\..\\..\\Server\\SQLite" + (IntPtr.Size == 4 ? "32" : "64") + "\\System.Data.SQLite.DLL"); Conn = (System.Data.IDbConnection)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteConnection"), "Data Source=" + Path + "\\..\\Database.db"); Sql = (System.Data.Common.DbDataAdapter)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteDataAdapter"), SqlStr, Conn); //*/ } System.Data.DataTable D = new System.Data.DataTable(); Sql.Fill(D); // --- Save data to database --- System.Xml.XmlDocument X = new System.Xml.XmlDocument(); string XML = Request["TGData"]; if (XML != "" && XML != null) { X.LoadXml(HttpUtility.HtmlDecode(XML)); System.Xml.XmlNodeList Ch = X.GetElementsByTagName("Changes"); if (Ch.Count > 0) { foreach (System.Xml.XmlElement I in Ch[0]) { string id = I.GetAttribute("id"); System.Data.DataRow R; if (I.GetAttribute("Added") == "1") { R = D.NewRow(); R["ID"] = id; D.Rows.Add(R); } else { R = D.Select("[ID]='" + id + "'")[0]; } if (I.GetAttribute("Deleted") == "1") { R.Delete(); } else if (I.GetAttribute("Added") == "1" || I.GetAttribute("Changed") == "1") { if (I.HasAttribute("Project")) { R["Project"] = I.GetAttribute("Project"); } if (I.HasAttribute("Resource")) { R["Resource"] = I.GetAttribute("Resource"); } if (I.HasAttribute("Week")) { R["Week"] = System.Double.Parse(I.GetAttribute("Week")); } if (I.HasAttribute("Hours")) { R["Hours"] = System.Double.Parse(I.GetAttribute("Hours")); } } } } if (UseMDB) { new System.Data.OleDb.OleDbCommandBuilder((System.Data.OleDb.OleDbDataAdapter)Sql); // For MS Acess database } else { Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteCommandBuilder"), Sql); // For SQLite database } Sql.Update(D); // Updates changed to database D.AcceptChanges(); X.RemoveAll(); Response.Write("<Grid><IO Result='0'/></Grid>"); } // --- Load data from database --- else { System.Xml.XmlElement G, BB, B, I; G = X.CreateElement("Grid"); X.AppendChild(G); BB = X.CreateElement("Body"); G.AppendChild(BB); B = X.CreateElement("B"); BB.AppendChild(B); foreach (System.Data.DataRow R in D.Rows) { I = X.CreateElement("I"); B.AppendChild(I); I.SetAttribute("id", R[0].ToString()); I.SetAttribute("Project", R[1].ToString()); I.SetAttribute("Resource", R[2].ToString()); I.SetAttribute("Week", R[3].ToString()); I.SetAttribute("Hours", R[4].ToString()); } Response.Write(X.InnerXml); } } catch (Exception E) { Response.Write("<Grid><IO Result=\"-1\" Message=\"Error in TreeGrid example:

" + E.Message.Replace("&", "&").Replace("<", "<").Replace("\"", """) + "\"/></Grid>"); } }
// Read XML document from file, if not exist, start new XML document. public bool Start(String filename, String docName) { m_filename = filename; m_name = System.IO.Path.GetFileName(filename); m_xdoc = new XmlDocument(); m_toplevel = null; bool fileExist = System.IO.File.Exists(m_filename); try { m_xdoc.Load(m_filename); m_toplevel = m_xdoc.ChildNodes[1]; //m_version = GetInt(m_xdoc, "FileVersion", 0); if (m_toplevel.Name != docName) m_toplevel = null; else { m_verattr = m_toplevel.Attributes["FileVersion"]; m_version = int.Parse(m_verattr.Value); } } catch (Exception ex) { if (fileExist) { DebugLogger.Instance().LogError(m_name + ": " + ex.Message); m_xdoc.RemoveAll(); } m_toplevel = null; } if (m_toplevel == null) { NewDocument(docName); } return fileExist; }
public void CheckSetXML(string fileName) { string definitionPath = Path.Combine(this.Directory.FullName, "definition.xml"); List<string> properties = new List<string>(); XmlDocument doc = new XmlDocument(); doc.Load(definitionPath); XmlNode cardDef = doc.GetElementsByTagName("card").Item(0); foreach (XmlNode propNode in cardDef.ChildNodes) { if (propNode.Name == "property") { if (propNode.Attributes["name"] != null) { properties.Add(propNode.Attributes["name"].Value); } } } cardDef = null; doc.RemoveAll(); doc = null; doc = new XmlDocument(); doc.Load(fileName); foreach (XmlNode cardNode in doc.GetElementsByTagName("card")) { string cardName = cardNode.Attributes["name"].Value; List<string> cardProps = new List<string>(); foreach (XmlNode propNode in cardNode.ChildNodes) { if (propNode.Name == "alternate") { string altName = propNode.Attributes["name"].Value; List<string> props = new List<string>(); foreach (XmlNode altPropNode in propNode.ChildNodes) { string prop = altPropNode.Attributes["name"].Value; if (!props.Contains(prop)) { props.Add(prop); } else { throw new UserMessageException("Duplicate property found named {0} on card named {1} within alternate {2} in set file {3}",prop, cardName, altName, fileName); } } foreach (string prop in props) { if (!properties.Contains(prop)) { throw new UserMessageException("Property defined on card {0} alternate with name {1} named {2} is not defined in definition.xml in set file {2}", cardName, altName, prop, fileName); } } continue; } if (!cardProps.Contains(propNode.Attributes["name"].Value)) { cardProps.Add(propNode.Attributes["name"].Value); } else { throw new UserMessageException("Duplicate property found named {0} on card named {1} in set file {2}", propNode.Attributes["name"].Value, cardName, fileName); } } foreach (string prop in cardProps) { if (!properties.Contains(prop)) { throw new UserMessageException("Property defined on card name {0} named {1} that is not defined in definition.xml in set file {2}", cardName, prop, fileName); } } } doc.RemoveAll(); doc = null; }
private void PPreview_Click(object sender, EventArgs e) { if (this.PrintTemplateList.SelectedItem == null) { BusinessLogic.MyMessageBox("Please first select a template for printing from the [Choose Template] section"); } else { TextWriter writer = null; try { if (this.SelectedColumnList.Items.Count < 1) { throw new Exception("No columns selected!"); } XmlDocument doc = new XmlDocument(); int num = 100 / (this.SelectedColumnList.Items.Count + 1); doc.LoadXml("<center><table border=\"1\" width=\"" + Convert.ToString((int) (num * this.SelectedColumnList.Items.Count)) + "%\"></table></center>"); XmlNode node = doc.DocumentElement.FirstChild.AppendChild(doc.CreateElement("tr")); foreach (object obj2 in this.SelectedColumnList.Items) { XmlNode node2 = node.AppendChild(doc.CreateElement("td")); XmlNode node3 = doc.CreateNode(XmlNodeType.Attribute, "width", null); node3.Value = Convert.ToString(num) + "%"; node2.Attributes.SetNamedItem(node3); node2.AppendChild(doc.CreateElement("b")).InnerText = Convert.ToString(obj2); } foreach (DataRow row in this.dsSrc.Tables[0].Rows) { XmlNode node5 = doc.DocumentElement.FirstChild.AppendChild(doc.CreateElement("tr")); foreach (object obj2 in this.SelectedColumnList.Items) { XmlNode node6 = node5.AppendChild(doc.CreateElement("td")); XmlNode node7 = doc.CreateNode(XmlNodeType.Attribute, "width", null); node7.Value = Convert.ToString(num) + "%"; node6.Attributes.SetNamedItem(node7); node6.InnerText = Convert.ToString(row[Convert.ToString(obj2)]); } } string str2 = this.ApplyTemplate(doc); doc.RemoveAll(); writer = new StreamWriter(@".\PrintCache\PrintDocument.html", false, Encoding.ASCII); writer.Write(str2); writer.WriteLine("<script language=\"javascript\">"); writer.WriteLine("\tvar WebBrowser='<OBJECT ID=WebBrowser1 WIDTH=0 HEIGHT=0 CLASSID=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2></OBJECT>';"); writer.WriteLine("\tdocument.write(WebBrowser);"); writer.WriteLine("\tWebBrowser1.ExecWB(7,0);"); writer.WriteLine("</script>"); writer.Close(); writer = null; Process.Start("iexplore.exe", "\"" + Application.StartupPath + "\\PrintCache\\PrintDocument.html\""); } catch (Exception exception) { if (writer != null) { writer.Close(); writer = null; } BusinessLogic.MyMessageBox(exception.Message); BusinessLogic.MyMessageBox("Document for printing could not be formed!"); } } }
public static bool SaveExtraMeta(Workspace ws) { string extraPath = ws.getExtraMetaPath(); XmlDocument extrafile = new XmlDocument(); try { FileManagers.SaveResult result = FileManagers.FileManager.MakeWritable(extraPath, Resources.SaveFileWarning); if (FileManagers.SaveResult.Succeeded != result) return false; extrafile.RemoveAll(); XmlDeclaration declaration = extrafile.CreateXmlDeclaration("1.0", "utf-8", null); extrafile.AppendChild(declaration); XmlComment comment = extrafile.CreateComment("EXPORTED BY TOOL, DON'T MODIFY IT!"); extrafile.AppendChild(comment); XmlElement meta = extrafile.CreateElement("extrameta"); extrafile.AppendChild(meta); if (SaveExtraMembers(extrafile, meta)) extrafile.Save(extraPath); return true; } catch (Exception ex) { extrafile.RemoveAll(); string msgError = string.Format(Resources.SaveFileError, extraPath, ex.Message); MessageBox.Show(msgError, Resources.SaveError, MessageBoxButtons.OK); } return false; }
public static bool SaveCustomMeta(Workspace ws) { string bbPath = ws.getBlackboardPath(); XmlDocument bbfile = new XmlDocument(); try { FileManagers.SaveResult result = FileManagers.FileManager.MakeWritable(bbPath, Resources.SaveFileWarning); if (FileManagers.SaveResult.Succeeded != result) { return false; } bbfile.RemoveAll(); XmlDeclaration declaration = bbfile.CreateXmlDeclaration("1.0", "utf-8", null); bbfile.AppendChild(declaration); XmlElement meta = bbfile.CreateElement("meta"); bbfile.AppendChild(meta); SaveCustomTypes(bbfile, meta); SaveCustomMembers(bbfile, meta); bbfile.Save(bbPath); ws.IsBlackboardDirty = false; return true; } catch (Exception ex) { bbfile.RemoveAll(); string msgError = string.Format(Resources.SaveFileError, bbPath, ex.Message); MessageBox.Show(msgError, Resources.SaveError, MessageBoxButtons.OK); } return false; }
protected void Page_Load(object sender, EventArgs e) { // --- Database initialization --- string Path = System.IO.Path.GetDirectoryName(Context.Request.PhysicalPath); System.Data.IDbConnection Conn = null; System.Data.Common.DbDataAdapter Sql = null; string SqlStr = "SELECT * FROM TableData"; System.Reflection.Assembly SQLite = null; // Required only for SQLite database if (UseMDB) // For MS Acess database { Conn = new System.Data.OleDb.OleDbConnection("Data Source=\"" + Path + "\\..\\Database.mdb\";Mode=Share Deny None;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Engine Type=5;Provider=\"Microsoft.Jet.OLEDB.4.0\";Jet OLEDB:System database=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1"); Sql = new System.Data.OleDb.OleDbDataAdapter(SqlStr, (System.Data.OleDb.OleDbConnection)Conn); } else // For SQLite database { SQLite = System.Reflection.Assembly.LoadFrom(Path + "\\..\\..\\..\\Server\\SQLite" + (IntPtr.Size == 4 ? "32" : "64") + "\\System.Data.SQLite.DLL"); Conn = (System.Data.IDbConnection)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteConnection"), "Data Source=" + Path + "\\..\\Database.db"); Sql = (System.Data.Common.DbDataAdapter)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteDataAdapter"), SqlStr, Conn); //*/ } System.Data.DataTable D = new System.Data.DataTable(); Sql.Fill(D); // --- Response initialization --- Response.ContentType = "text/html"; Response.Charset = "utf-8"; Response.AppendHeader("Cache-Control", "max-age=1, must-revalidate"); System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US"); System.Xml.XmlDocument X = new System.Xml.XmlDocument(); // --- Save data to database --- string XML = TGData.Value; if (XML != "" && XML != null) { X.LoadXml(HttpUtility.HtmlDecode(XML)); System.Xml.XmlNodeList Ch = X.GetElementsByTagName("Changes"); if (Ch.Count > 0) { foreach (System.Xml.XmlElement I in Ch[0]) { string id = I.GetAttribute("id"); System.Data.DataRow R; if (I.GetAttribute("Added") == "1") { R = D.NewRow(); R["ID"] = id; D.Rows.Add(R); } else { R = D.Select("[ID]='" + id + "'")[0]; } if (I.GetAttribute("Deleted") == "1") { R.Delete(); } else if (I.GetAttribute("Added") == "1" || I.GetAttribute("Changed") == "1") { if (I.HasAttribute("Project")) { R["Project"] = I.GetAttribute("Project"); } if (I.HasAttribute("Resource")) { R["Resource"] = I.GetAttribute("Resource"); } if (I.HasAttribute("Week")) { R["Week"] = System.Double.Parse(I.GetAttribute("Week")); } if (I.HasAttribute("Hours")) { R["Hours"] = System.Double.Parse(I.GetAttribute("Hours")); } } } } if (UseMDB) { new System.Data.OleDb.OleDbCommandBuilder((System.Data.OleDb.OleDbDataAdapter)Sql); // For MS Acess database } else { Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteCommandBuilder"), Sql); // For SQLite database } Sql.Update(D); // Updates changed to database D.AcceptChanges(); X.RemoveAll(); } // --- Load data from database --- { System.Xml.XmlElement G, BB, B, I; G = X.CreateElement("Grid"); X.AppendChild(G); BB = X.CreateElement("Body"); G.AppendChild(BB); B = X.CreateElement("B"); BB.AppendChild(B); foreach (System.Data.DataRow R in D.Rows) { I = X.CreateElement("I"); B.AppendChild(I); I.SetAttribute("id", R[0].ToString()); I.SetAttribute("Project", R[1].ToString()); I.SetAttribute("Resource", R[2].ToString()); I.SetAttribute("Week", R[3].ToString()); I.SetAttribute("Hours", R[4].ToString()); } TGData.Value = X.InnerXml; } }
private void timer1_Tick(object sender, EventArgs e) { try { string appPath = Path.GetDirectoryName(Application.ExecutablePath); XmlDocument xDoc = new XmlDocument(); var web = new WebClient(); try { web.DownloadFile(new Uri(string.Format("https://api-content.dropbox.com/1/files/auto/{0}?access_token={1}", "Data.xml", Properties.Settings.Default.AccessToken)), (appPath + "\\" + "Data.xml").Replace("Data.xml", "Data.xml")); web.DownloadProgressChanged += new DownloadProgressChangedEventHandler(web_DownloadProgressChanged); xDoc.Load(appPath + "\\" + "Data.xml"); XmlRootAttribute xRoot = new XmlRootAttribute(); xRoot.ElementName = "user"; xRoot.IsNullable = true; XmlSerializer sr = new XmlSerializer(typeof(Information)); FileStream read = new FileStream("Data.xml", FileMode.Open, FileAccess.Read, FileShare.Read); Information Info = (Information)sr.Deserialize(read); read.Close(); textBox1.Text = Info.Url; xDoc.RemoveAll(); timer1.Stop(); timer2.Start(); } catch { timer2.Start(); timer1.Stop(); } } catch (WebException ex) { } }
public ISceneEntity FromXml2Format(string xmlData, IScene scene) { //MainConsole.Instance.DebugFormat("[SOG]: Starting deserialization of SOG"); //int time = Util.EnvironmentTickCount(); XmlDocument doc = new XmlDocument(); try { doc.LoadXml(xmlData); SceneObjectGroup grp = InternalFromXml2Format(doc, scene); xmlData = null; return grp; } catch (Exception e) { MainConsole.Instance.ErrorFormat("[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData); return null; } finally { doc.RemoveAll(); doc = null; } }
private void Clean(XmlDocument xml) { xml.RemoveAll(); xml = null; }
private string buildNotation(String GraphicsCode, String XMLData) { try { //Load data XmlReader datareader = XmlReader.Create(new StringReader(XMLData)); XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(XMLData); XmlNode XmlDataNode = xdoc.DocumentElement; string dataNodeName = XmlDataNode.Name; xdoc.RemoveAll(); //create transformation XmlElement stylesheet = xdoc.CreateElement("stylesheet", "xsl"); stylesheet.SetAttribute("xmlns:xsl", "http://www.w3.org/1999/XSL/Transform"); stylesheet.Prefix = "xsl"; stylesheet.SetAttribute("version", "1.0"); if (visType == VisualisationType.XAML) { stylesheet.SetAttribute("xmlns:x", "http://schemas.microsoft.com/winfx/2006/xaml"); stylesheet.SetAttribute("xmlns:local", "clr-namespace:CONVErT;assembly=CONVErT"); stylesheet.SetAttribute("xmlns", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); } else if (visType == VisualisationType.SVG) { //don't know what will go here for now! Possibly script //to use for adding interaction to SVG } XmlElement mainTemplate = stylesheet.OwnerDocument.CreateElement("xsl", "template", "http://www.w3.org/1999/XSL/Transform"); //mainTemplate.Prefix = "xsl"; stylesheet.AppendChild(mainTemplate); XmlAttribute matchAttr = xdoc.CreateAttribute("match"); matchAttr.Value = "/"; mainTemplate.Attributes.Append(matchAttr); XmlElement callTemplate = xdoc.CreateElement("xsl", "apply-templates", "http://www.w3.org/1999/XSL/Transform"); mainTemplate.AppendChild(callTemplate); XmlAttribute selectAttr = xdoc.CreateAttribute("select"); string selectStr = dataNodeName;//templates.First().Attributes.GetNamedItem("match").Value; selectAttr.AppendChild(xdoc.CreateTextNode(selectStr) as XmlNode); callTemplate.Attributes.Append(selectAttr); //create transforamtion Collection<XmlNode> transXSLTemplates = parseAnnotatedGraphics(GraphicsCode, dataNodeName, XmlDataNode); foreach (XmlNode x in transXSLTemplates) stylesheet.AppendChild(stylesheet.OwnerDocument.ImportNode(x, true)); //for removing text XmlNode applytemplatesText = stylesheet.OwnerDocument.CreateElement("xsl", "template", "http://www.w3.org/1999/XSL/Transform"); //valueofNode.Prefix = "xsl"; XmlAttribute selectAttr1 = stylesheet.OwnerDocument.CreateAttribute("match"); selectAttr1.Value = "text()"; applytemplatesText.Attributes.Append(selectAttr1); stylesheet.AppendChild(applytemplatesText); String transXSL = prettyPrinter.PrintToString(stylesheet); //MessageBox.Show(transXSL); XmlReader xslreader = XmlReader.Create(new StringReader(transXSL)); //transformation output StringBuilder output = new StringBuilder(""); XmlWriter outputwriter = XmlWriter.Create(output); //run transformation XslCompiledTransform myXslTransform = new XslCompiledTransform(); myXslTransform.Load(xslreader); myXslTransform.Transform(datareader, outputwriter); String s = prettyPrinter.PrintToString(output.ToString()); return s; } catch (CallforUseErrorException cuex)//with new annotations for @linkto it will not happen! but keep it just in case { logger.log("Error in use of callfor: Call for does not support attribute generation", ReportIcon.Error); ReportStatusBar.ShowStatus("Error procesing annotated graphics: see exception!", ReportIcon.Error); return null; } catch (Exception ex) { ReportStatusBar.ShowStatus("(createNotation): Something went wrong -> " + ex.Message, ReportIcon.Error); return null; } }