public string GetTheDefaultFileName(string sLocalDirectory) { string sLine = ""; try { XmlDataDocument xDFile = new XmlDataDocument(); xDFile.Load("data\\Default.xml"); XmlNodeList fileNodes = xDFile.SelectNodes("Document/File"); foreach (XmlNode node in fileNodes) { if (File.Exists(sLocalDirectory + node.InnerText.Trim())) { sLine = node.InnerText.Trim(); break; } } } catch (XmlException eXML) { Console.WriteLine("An ConfigFile Exception Occurred : " + eXML.ToString()); } if (File.Exists(sLocalDirectory + sLine) == true) { return(sLine); } else { return(""); } }
private void import(string filename) { try { XmlDataDocument xml_doc = new XmlDataDocument(); xml_doc.Load(filename); var lessonNodes = xml_doc.SelectNodes("//lesson"); foreach (XmlNode ln in lessonNodes) { int id = Convert.ToInt32(getAttributeOrDefault(ln, "id", "-1")); string description = getAttributeOrDefault(ln, "description", "No description set"); var lesson = new LessonNode(id, description); var pairNodes = ln.SelectNodes("pair"); foreach (XmlNode pn in pairNodes) { lesson.PairStore.AddNode(new PairNode(SelectTextNode(pn, "en"), SelectTextNode(pn, "de"))); } LessonStore.AddNode(lesson); } } catch (FileNotFoundException) { } }
private void button5_Click(object sender, EventArgs e) { XmlDocument doc = new XmlDocument(); //create a dataset DataSet ds = new DataSet("XMLProducts"); //connect to the northwind database and //select all of the rows from products table and from suppliers table //make sure you connect string matches you server configuration SqlConnection conn = new SqlConnection(_connectString); SqlDataAdapter daProduct = new SqlDataAdapter("SELECT Name, StandardCost, ProductCategoryID FROM SalesLT.Product", conn); SqlDataAdapter daCategory = new SqlDataAdapter("SELECT ProductCategoryID, Name from SalesLT.ProductCategory", conn); //Fill DataSet from both SqlAdapters daProduct.Fill(ds, "Products"); daCategory.Fill(ds, "Categories"); //Add the relation ds.Relations.Add(ds.Tables["Categories"].Columns["ProductCategoryID"], ds.Tables["Products"].Columns["ProductCategoryID"]); //Write the Xml to a file so we can look at it later ds.WriteXml("Products.xml", XmlWriteMode.WriteSchema); //load data into grid dataGridView1.DataSource = ds.Tables[0]; //create the XmlDataDocument doc = new XmlDataDocument(ds); //Select the productname elements and load them in the grid XmlNodeList nodeLst = doc.SelectNodes("//XMLProducts/Products"); textBox1.Text = ""; foreach (XmlNode node in nodeLst) { textBox1.Text += node.InnerXml + "\r\n"; } }
public void XMLToDataSet(string sXML) { DetDs.Tables.Clear(); if (sXML == String.Empty) { return; } XmlDocument doc = new XmlDataDocument(); doc.LoadXml(sXML); XmlNodeList ndl = doc.SelectNodes("tournamentprize/players"); GetTableParameters(ndl); }
private void processaCCO() { if (dbClass.execmd("select vl_parametro from parametro where cd_parametro = 'DIRTMP'", true) == "") { dbClass.execmd("insert into parametro values ('DIRTMP','c:\\temp\\','Diretório temporário','U','SISTEMA',getdate())", true); } string filePath = dbClass.execmd("select vl_parametro from parametro where cd_parametro = 'DIRTMP'", true); XmlDataDocument arq_Xml; arq_Xml = new XmlDataDocument(); FileUpload2.SaveAs(filePath + FileUpload2.FileName); arq_Xml.Load(filePath + FileUpload2.FileName); if (arq_Xml.SelectSingleNode("mensagemSIB/cabecalho/destino/registroANS") != null) { if (dbClass.execmd("select vl_parametro from parametro where cd_parametro = 'CDRANS'", true) != arq_Xml.SelectSingleNode("mensagemSIB/cabecalho/destino/registroANS").InnerText) { lblMensagem.Text = "Arquivo de retorno do SIB não pertence à empresa"; return; } } else { lblMensagem.Text = "Arquivo não é um arquivo de retorno válido do SIB"; return; } XmlNodeList lista = arq_Xml.SelectNodes("mensagemSIB/mensagem/ansParaOperadora/resultadoProcessamento/arquivoProcessado/registrosIncluidos/registroIncluido"); int qt = 0; foreach (XmlNode incluido in lista) { string cco = incluido.SelectSingleNode("cco").InnerText; string cdUsuario = incluido.Attributes[0].InnerText; string nmUsuario = incluido.SelectSingleNode("nomeBeneficiario").InnerText; dbClass.execmd("update usuario set cco = '" + cco.Substring(0, 10) + "',dg_cco = '" + cco.Substring(10, 2) + "' where codigo_completo = " + cdUsuario, false); qt++; } lblMensagem.Text = "Quantidade de CCO's alimentados : " + qt; }
private void btnGentrateReport_Click(object sender, EventArgs e) { XmlDataDocument xml = new XmlDataDocument(); xml.Load(@"XML Document\ReportsFormat.xml"); XmlNodeList nodeList = xml.SelectNodes("/crClientPayableReconciliationStatement.rpt/CheckValue"); foreach (XmlNode node in nodeList) { if (node["FirstAmount"].InnerText != "" || node["SecondAmount"].InnerText != "" || node["Remarks"].InnerText != "") //returns empty or "" { MessageBox.Show(String.Format("Data From xml is {0} {1} {2}", node["FirstAmount"].InnerText, node["SecondAmount"].InnerText, node["Remarks"].InnerText)); } if (node["FirstAmount"].InnerText == "" || node["FirstAmount"].InnerText == "" || node["Remarks"].InnerText == "") //returns empty or "" { MessageBox.Show(String.Format("Data From xml is {0} {1} {2}", node["FirstAmount"].InnerText, node["SecondAmount"].InnerText, node["Remarks"].InnerText)); } } /* * double payable=0.0; * double receivable = 0.0; * payable = 47311025.39; * receivable = -14820280.88; * receivable = payable + receivable; * _reportDate = Convert.ToDateTime(dtpReportDate.Value.ToShortDateString()); * * ClientPayableRecounciliationStatementBAL ClientPayableRecounciliationStatementBAL = new ClientPayableRecounciliationStatementBAL(); * DataTable data = new DataTable(); * // data = ClientPayableRecounciliationStatementBAL.GetStatement(_reportDate); * * frmReportViewer frmReportViewer = new frmReportViewer(); * crClientPayableReconciliationStatement crClientPayableReconciliationStatement = new crClientPayableReconciliationStatement(); * * * ((TextObject)crClientPayableReconciliationStatement.ReportDefinition.Sections[2].ReportObjects["txtDate"]).Text = _reportDate.ToShortDateString();//String.Format("{0:#,###0.00}", Convert.ToDouble(TaxDataSet.Tables[2].Rows[0][0]));// DepositWithdraw.Rows[0][0].ToString(); * ((TextObject)crClientPayableReconciliationStatement.ReportDefinition.Sections[2].ReportObjects["txtPayableClientsAmount1"]).Text = String.Format("{0:#,###0.00}", Convert.ToDouble(payable));// DepositWithdraw.Rows[0][1].ToString(); * ((TextObject)crClientPayableReconciliationStatement.ReportDefinition.Sections[2].ReportObjects["txtreceivableClientsAmount1"]).Text = String.Format("{0:#,###0.00}", Convert.ToDouble(receivable));//DepositWithdraw.Rows[0][1].ToString(); * //((TextObject)crClientPayableReconciliationStatement.ReportDefinition.Sections[2].ReportObjects["Market_Value_Total"]).Text = String.Format("{0:#,###0.00}", Convert.ToDouble(TaxDataSet.Tables[2].Rows[0][2]));//DepositWithdraw.Rows[0][1].ToString(); * * * // crClientPayableReconciliationStatement.SetDataSource(data); * frmReportViewer.crvReportViewer.ReportSource = crClientPayableReconciliationStatement; * frmReportViewer.Show(); * */ }
private void btnLoadURL_Click(object sender, EventArgs e) { if (!String.IsNullOrEmpty(txtURL.Text)) { string url = txtURL.Text; if (!url.Contains("http://")) { url = "http://" + url; } if (!url.EndsWith("/")) { url += "/"; } url += "admin/file/?file=schema.xml"; // Set the reader settings. XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; settings.IgnoreProcessingInstructions = true; settings.IgnoreWhitespace = true; // Create a resolver with default credentials. XmlUrlResolver resolver = new XmlUrlResolver(); resolver.Credentials = System.Net.CredentialCache.DefaultCredentials; // Set the reader settings object to use the resolver. settings.XmlResolver = resolver; // Create the XmlReader object. XmlReader reader = XmlReader.Create(url, settings); XmlDataDocument xmlDoc = new XmlDataDocument(); xmlDoc.Load(reader); XmlNodeList nodes = xmlDoc.SelectNodes("//field"); dgvSchema.Rows.Clear(); foreach (XmlNode node in nodes) { XmlAttributeCollection attribs = node.Attributes; List <string> fieldAttribs = new List <string>(); foreach (XmlAttribute attrib in attribs) { fieldAttribs.Add(attrib.Value); } dgvSchema.Rows.Add(fieldAttribs.ToArray()); } } }
private void PopulateProviders() { ProviderComboBox.Items.Clear(); ProviderComboBox.Items.Insert(0, "Select One"); XmlNodeList nodeList = settings.SelectNodes("Languages/Language"); if (nodeList != null && nodeList.Count > 0) { foreach (XmlNode node in nodeList) { ProviderComboBox.Items.Add(node.Attributes["From"].Value); } } ProviderComboBox.SelectedIndex = 0; }
[ValidateInput(false)]//允许html public ActionResult ResetItemSortNo() { string returnUrl = DoRequest.GetFormString("returnurl").Trim(); string xmlString = DoRequest.GetFormString("xml", false).Replace("<", "<").Replace(">", ">"); try { XmlDataDocument xmlDoc = new XmlDataDocument(); xmlDoc.LoadXml(xmlString); List <ModifyRecommendList> items = new List <ModifyRecommendList>(); XmlNodeList nodes = xmlDoc.SelectNodes("items/item"); if (nodes != null) { #region 新增分类 foreach (XmlNode item in nodes) { ModifyRecommendList iem = new ModifyRecommendList(); iem.ri_id = Utils.StrToInt(item.Attributes["ItemID"].Value).ToString(); iem.sort_no = (Utils.IsNumber(item.Attributes["SortNo"].Value) ? (int.Parse(item.Attributes["SortNo"].Value)) : 1000).ToString(); items.Add(iem); } #endregion } int returnValue = -1; var res = ModifyRecommendItemSortNo.Do(items); if (res != null && res.Header != null && res.Header.Result != null && res.Header.Result.Code != null) { returnValue = Utils.StrToInt(res.Header.Result.Code, -1); } if (returnValue == 0) { return(Json(new { error = false, message = "保存成功 ^_^" })); } } catch (Exception) { return(Json(new { error = true, message = "Xml解析失败..." })); } return(Json(new { error = true, message = "保存失败" })); }
private static void SetConnString(string key, string value, string configFile) { try { XmlDataDocument config = new XmlDataDocument(); config.Load(configFile); XmlNodeList nl = config.SelectNodes("//configuration/connectionStrings/add");// GetElementsByTagName("appSettings")[0].ChildNodes; for (int index = 0; index < nl.Count; index++) { if (nl[index].Attributes["name"].Value.ToLower().CompareTo(key.Trim().ToLower()) == 0) { nl[index].Attributes["connectionString"].Value = value; } } config.Save(configFile); } catch (IOException) { } }
//装载查询条件 // private void load_QuerySetting() { try { strFileName = TemplateDesignerHost.Function.SystemPath + "HIS_QUERY_SETTING.xml"; doc.Load(strFileName); nodes = doc.SelectNodes("设置/系统设置"); foreach (XmlNode node in nodes) { this.cmbCondition.Items.Add(node.Attributes["名称"].Value); } } catch {} first = false; this.cmbCondition.SelectedIndex = 0; }
public static void ConvertFormResx(string filePath, string targetLang, string destinationPath) { XmlDataDocument xmldoc = new XmlDataDocument(); XmlNodeList xmlnode; int i = 0; string strEng = string.Empty; List <string> strConverted = new List <string>(); FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite); xmldoc.Load(fs); xmlnode = xmldoc.GetElementsByTagName("data"); XmlNodeList aNodes = xmldoc.SelectNodes("/root/data"); for (i = 0; i < aNodes.Count; i++) { string attrVal = aNodes[i].Attributes["name"].Value; if (attrVal.EndsWith(".Text")) { XmlNodeList aInnerNodes = aNodes[i].ChildNodes; string sNew = aInnerNodes[1].InnerXml; if (sNew.Contains("&")) { sNew = sNew.Replace("&", string.Empty); } if (!string.IsNullOrEmpty(sNew)) { strConverted = Internalization.YandexTranslate.Translate(targetLang, sNew); aInnerNodes[1].InnerXml = strConverted[0]; } } } fs.Close(); if (destinationPath == string.Empty) { xmldoc.Save(Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + "_" + targetLang + Path.GetExtension(filePath)); } else { xmldoc.Save(destinationPath + "_" + targetLang + Path.GetExtension(filePath)); } }
/// <summary> /// Determines if we need to save the definition. /// Logic :: compares wf compilation time, with AsmCreateDate on wf def file /// if AsmCreateDate !=Wf assembly compilation time, we will load it /// </summary> /// <returns>true/false</returns> public bool IsNewOrUpdatedWfDefinition(Activity rootActivity) { if (!File.Exists(_workflowDefPath)) { return(true); } else { XmlDataDocument xmldoc = new XmlDataDocument(); xmldoc.LoadXml(GetWorkflowDefinitionString()); XmlNodeList rootActivities = xmldoc.SelectNodes("/Activity"); if (rootActivities != null) { DateTime savedWfCompliteTime = DateTime.Parse(rootActivities[0].Attributes["WfCompliteTime"].Value); return(!GetWfCompilationTimestamp(rootActivity) .Equals(savedWfCompliteTime)); } return(true); } }
public static void GetStringValueFromResource(string filePath, string targetLang, string destinationPath) { List <String> resxValue = new List <string>(); XmlDataDocument xmldoc = new XmlDataDocument(); XmlNodeList xmlnode; int i = 0; string strEng = string.Empty; List <string> strConverted = new List <string>(); FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite); xmldoc.Load(fs); xmlnode = xmldoc.GetElementsByTagName("value"); XmlNodeList aNodes = xmldoc.SelectNodes("/root/data/value"); foreach (XmlNode aNode in aNodes) { if (aNode.InnerText != null) { string currentValue = aNode.InnerText; if (currentValue.Contains("&")) { currentValue = currentValue.Replace("&", String.Empty); } if (!string.IsNullOrEmpty(currentValue)) { strConverted = Internalization.YandexTranslate.Translate(targetLang, currentValue); aNode.InnerText = strConverted[0]; } } } fs.Close(); if (destinationPath == string.Empty) { xmldoc.Save(Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + "_" + targetLang + Path.GetExtension(filePath)); } else { xmldoc.Save(destinationPath + "_" + targetLang + Path.GetExtension(filePath)); } }
//const System.Xml.XPath.XPathExpression XPATH_FAVORITES = System.Xml.XPath.XPathExpression.Compile(NODE_XPATH_FAVORITE_COLLECTION + @"\" + NODE_XPATH_FAVORITE_TAG); static FavoritesManagement() { string xPathFfavorites = NODE_XPATH_FAVORITE_COLLECTION + @"/" + NODE_XPATH_FAVORITE_TAG; XmlDocument doc = new XmlDataDocument(); try { doc.Load(FAVORITE_FILE); } catch (FileNotFoundException) { favorites = new List <KeyValuePair <string, string> >(0); return; } catch (XmlException) { favorites = new List <KeyValuePair <string, string> >(0); return; } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } //return; XmlNodeList nodes = doc.SelectNodes(xPathFfavorites); favorites = new List <KeyValuePair <string, string> >(nodes.Count); foreach (XmlNode n in nodes) { favorites.Add ( new KeyValuePair <string, string> ( n.Attributes[XML_ATTRIBUTE_LABEL].Value, n.Attributes[XML_ATTRIBUTE_PATH].Value ) ); } }
private static void Main() { using (var dataSet = new DataSet("XmlProducts")) using (var connection = new SqlConnection(AdvWorksConnectionString)) using ( var productDataAdapter = new SqlDataAdapter("SELECT Name, StandardCost, ProductCategoryID FROM SalesLT.Product", connection)) using ( var categoryDataAdapter = new SqlDataAdapter("SELECT ProductCategoryID, Name FROM SalesLT.ProductCategory", connection)) { productDataAdapter.Fill(dataSet, "Products"); categoryDataAdapter.Fill(dataSet, "Categories"); // Добавление отношения dataSet.Relations.Add(dataSet.Tables["Categories"].Columns["ProductCategoryID"], dataSet.Tables["Products"].Columns["ProductCategoryID"]); // Запись кода XML в файл для просмотра в будущем dataSet.WriteXml("Products.xml", XmlWriteMode.WriteSchema); // Создание экземпляра XmlDataDocument var xmlDataDocument = new XmlDataDocument(dataSet); XmlNodeList nodeList = xmlDataDocument.SelectNodes("//XmlProducts/Products"); var stringBuilder = new StringBuilder(); if (nodeList != null) { foreach (XmlNode node in nodeList) { stringBuilder.Append(node).Append(Environment.NewLine); } } } }
public void ImportEndNoteXml(XmlDataDocument xmlDocument) { GreyFoxContactManager authorsManager = new GreyFoxContactManager("kitYari_Authors"); GreyFoxContactManager publishersManager = new GreyFoxContactManager("kitYari_Publishers"); YariMediaRecordManager mediaRecordManager = new YariMediaRecordManager(); YariMediaKeywordManager mediaKeywordManager = new YariMediaKeywordManager(); XmlNodeList bookNodes = xmlDocument.SelectNodes("//XML/RECORDS/RECORD"); XmlNode bookNode; externalRecordCount = bookNodes.Count; OnStart(new YariImporterEventArgs("Started Import.", 0)); for (int bookIndex = 0; bookIndex < bookNodes.Count; bookIndex++) { bookNode = bookNodes[bookIndex]; YariMediaRecord r = new YariMediaRecord(); foreach (XmlNode childNode in bookNode.ChildNodes) { // check for null records which signify existing titles of // the same name. if (r == null) { break; } switch (childNode.Name) { case "ISBN": if (childNode.InnerText.Length > 15) { r.Isbn = childNode.InnerText.Substring(0, 15); } else { r.Isbn = childNode.InnerText; } break; case "REFNUM": r.EndNoteReferenceID = int.Parse(childNode.InnerText); // if(mediaRecordManager.EndNoteReferenceIDExists(r.EndNoteReferenceID)) // { // OnRecordSkipped(new YariImporterEventArgs( // "Record Skipped - '" + r.EndNoteReferenceID + "'; EndNote Reference ID already exists.", bookIndex)); // r = null; // } break; case "YEAR": try { r.PublishYear = int.Parse(childNode.InnerText); } catch { r.PublishYear = 0; } break; case "TITLE": r.Title = childNode.InnerText; if (mediaRecordManager.TitleExists(r.title)) { OnRecordSkipped(new YariImporterEventArgs( "Record Skipped - '" + r.title + "'; title already exists.", bookIndex)); r = null; } break; case "PUBLISHER": r.Publisher = childNode.InnerText; break; case "PAGES": try { r.Pages = int.Parse(childNode.InnerText); } catch {} break; case "EDITION": r.Edition = childNode.InnerText; break; case "LABEL": r.Label = childNode.InnerText; break; case "KEYWORDS": r.keywords = new YariMediaKeywordCollection(); foreach (XmlNode keywordNode in childNode.ChildNodes) { string[] keywords = keywordNode.InnerText.Split(new char[] { ',', ';' }); foreach (string keyword in keywords) { r.Keywords.Add(mediaKeywordManager.FindByKeyword(keyword.Trim().ToLower(), true)); } } break; case "ABSTRACT": r.AbstractText = childNode.InnerText; break; case "NOTES": r.ContentsText = childNode.InnerText; break; case "AUTHORS": foreach (XmlNode authorNode in childNode.ChildNodes) { // // Split author fields in case the firstName is joined with // an ampersand or 'and' text. // string authorText = authorNode.InnerText.Replace(" & ", " and "); int andIndex = authorText.ToLower().IndexOf(" and "); if (andIndex != -1) { string authorA = authorText.Substring(0, andIndex).Trim(); string authorB = authorText.Substring(andIndex + 5, authorText.Length - (authorA.Length + 6)).Trim(); } r.Authors += authorText + " "; } break; } } // save the record if it does not exist. if (r != null) { r.AmazonRefreshDate = DateTime.MinValue; r.AmazonFillDate = DateTime.MinValue; r.AmazonReleaseDate = DateTime.MinValue; r.Save(); OnRecordImported( new YariImporterEventArgs("Imported Record - '" + r.Title + "'.", bookIndex, r)); } } OnFinish(new YariImporterEventArgs("Finished import.", bookNodes.Count)); }
public string GetEditParaInfo() { string Boid = Request["BOID"]; string NS = Request["NS"].Trim(); string DataType = ""; string ParaName = ""; string editor = ""; string data = ""; string ParaValue = ""; XmlDataDocument document = new XmlDataDocument(); PropertyManager manager = new PropertyManager(); IList <PropertyModel> propertyList = manager.GetListByID(Boid); valueDomain = new Dictionary <string, string>(); foreach (PropertyModel prop in propertyList) { editor = ""; if (prop.NS == NS) { document.LoadXml(prop.MdSource);//从对象参数值域中得到参数类型 XmlNodeList datastore = document.SelectNodes("PropertySet"); foreach (XmlNode node in datastore) { XmlNodeList column = node.ChildNodes; foreach (XmlNode nd in column) { DataType = nd.Attributes["t"].Value; ParaName = nd.Attributes["n"].Value; if (DataType == "String") { editor = "textbox"; } else if (DataType == "Decimal") { editor = "spinner"; } else { editor = "datepicker', format: 'yyyy-MM-dd "; } if (nd.InnerText.Length != 0) { editor = "selectvalue"; } if (!valueDomain.Keys.Contains(ParaName))//给各个参数赋值类型 { valueDomain.Add(ParaName, editor); } } } document = new XmlDataDocument(); document.LoadXml(prop.MD); datastore = document.SelectNodes("PropertySet"); foreach (XmlNode node in datastore) { XmlNodeList column = node.ChildNodes; foreach (XmlNode nd in column) { ParaValue = ""; if (nd.FirstChild != null) { ParaValue = nd.FirstChild.Value; } if (data == "") { data = "{id:'1', name: '" + nd.Attributes["n"].Value + "', value: '" + ParaValue + "', editor: '" + GetParaType(nd.Attributes["n"].Value) + "'}"; } else { data = data + "," + "{id:'1', name: '" + nd.Attributes["n"].Value + "', value: '" + ParaValue + "', editor: '" + GetParaType(nd.Attributes["n"].Value) + "'}"; } } if (data != "") { data = @"[" + data + "]"; } } break; } } return(data); }
//把翻译的结果生成到resx文件中,平台部分 private void GenerateToPlatform(string p) { string path, resxFile; string resxEsFile, resxEnFile; // string[] paras = p.Split('*'); path = paras[0]; resxFile = paras[1]; if (!File.Exists(sourcePath + path + resxFile)) { MessageBox.Show(sourcePath + path + resxFile + "文件不存在"); return; } //删除西班牙文的资源文件 resxEsFile = resxFile.Substring(0, resxFile.IndexOf('.')) + ".es.resx"; if (File.Exists(sourcePath + path + resxEsFile)) { File.Delete(sourcePath + path + resxEsFile); } //删除英文的资源文件 resxEnFile = resxFile.Substring(0, resxFile.IndexOf('.')) + ".en.resx"; if (File.Exists(sourcePath + path + resxEnFile)) { File.Delete(sourcePath + path + resxEnFile); } //把翻译的结果写到相应的资源文件中 //XmlDataDocument enXmlDoc = new XmlDataDocument(); //FileStream enFile = new FileStream(sourcePath + path + resxFile, FileMode.Open); //enXmlDoc.PreserveWhitespace = false; //enXmlDoc.Load(enFile); XmlNodeList nodes; //for (int i = 0; i < dgvPlatform.Rows.Count; i++) //{ // nodes = enXmlDoc.SelectNodes("//root/data[@name='" + dgvPlatform.Rows[i].Cells[1].Value.ToString() + "']"); // if (nodes != null && nodes.Count > 0) // { // foreach (XmlNode node in nodes) // { // if (node.NodeType == XmlNodeType.Element) // { // node.ChildNodes[1].InnerText = dgvPlatform.Rows[i].Cells[4].Value.ToString(); // break; // } // } // } //} //enXmlDoc.Save(sourcePath + path + resxEnFile); //enFile.Close(); XmlDataDocument esXmlDoc = new XmlDataDocument(); FileStream esFile = new FileStream(sourcePath + path + resxFile, FileMode.Open); esXmlDoc.PreserveWhitespace = false; esXmlDoc.Load(esFile); for (int i = 0; i < dgvPlatform.Rows.Count; i++) { nodes = esXmlDoc.SelectNodes("//root/data[@name='" + dgvPlatform.Rows[i].Cells[1].Value.ToString() + "']"); if (nodes != null && nodes.Count > 0) { foreach (XmlNode node in nodes) { if (node.NodeType == XmlNodeType.Element) { if (node.ChildNodes.Count > 1) { node.ChildNodes[1].InnerText = dgvPlatform.Rows[i].Cells[3].Value.ToString(); } break; } } } } esXmlDoc.Save(sourcePath + path + resxEsFile); esFile.Close(); }
public ActionResult PostPosition() { int ptype = DoRequest.GetFormInt("ptype", 7); string parent = DoRequest.GetFormString("parent"); string xmlString = DoRequest.GetFormString("xml", false).Replace("<", "<").Replace(">", ">"); try { XmlDataDocument xmlDoc = new XmlDataDocument(); xmlDoc.LoadXml(xmlString); List <RecommendPositionInfo> posList = new List <RecommendPositionInfo>(); List <string> codeList = new List <string>();//id codeList.Add(parent); XmlNodeList nodes = xmlDoc.SelectNodes("items/item"); //XmlNodeList nodes = xmlDoc.SelectNodes("items/item[@Type='create']"); if (nodes != null) { #region 新增分类 foreach (XmlNode item in nodes) { RecommendPositionInfo pos = new RecommendPositionInfo(); string itemType = item.Attributes["Type"].Value.Trim(); string parentValue = item.Attributes["ParentID"].Value.Trim(); string posValue = item.Attributes["Code"].Value.Trim(); int posId = Utils.StrToInt(item.Attributes["PosID"].Value.Trim()); string sortValue = item.Attributes["SortNo"].Value.Trim(); int useplat = Utils.StrToInt(item.Attributes["UsePlat"].Value.Trim(), 7); if (useplat == 4) { useplat = 6; } string flag = item.Attributes["Flag"].Value.Trim(); //if (string.IsNullOrEmpty(parentValue)) //{ // sortValue = "100" + sortValue; //} if (flag.Equals("true")) { pos.op_flag = 0; } else { pos.op_flag = 1; } string nameValue = item.SelectSingleNode("name").InnerText.Trim(); if (string.IsNullOrEmpty(nameValue)) { return(Json(new { error = true, message = "请填写分类名称,或将未填写分类名的行删除..." })); } if (nameValue.Length > 100) { return(Json(new { error = true, message = "分类名不能大于100个字符..." })); } pos.rp_id = posId; pos.rp_name = nameValue; //分类名 pos.parent_rp_code = parentValue; //父类编码 pos.rp_code = posValue; //Utils.IsGuid(classValue) ? classValue : Guid.NewGuid().ToString().ToLower();//分类编码 pos.sort_no = Utils.IsNumber(sortValue) ? int.Parse(sortValue) : 10000; //排序 pos.use_plat = useplat; posList.Add(pos); codeList.Add(pos.rp_code); } #endregion } #region 除分类 List <ShortRecommendPosition> dbList = new List <ShortRecommendPosition>(); var ressrel = GetRecommendPositionByCode.Do(parent, ptype);//非顶级分类 if (ressrel != null && ressrel.Body != null && ressrel.Body.recommend_list != null) { dbList = ressrel.Body.recommend_list; } //StringBuilder sb = new StringBuilder(); //int _deleteCount = 0; System.Text.StringBuilder deletePathList = new System.Text.StringBuilder(); foreach (ShortRecommendPosition item in dbList) { if (!codeList.Contains(item.rp_code.ToLower().Trim())) { deletePathList.Append(item.rp_code.Trim() + ","); } List <ShortRecommendPosition> dbList2 = new List <ShortRecommendPosition>(); var ressrel2 = GetRecommendPositionByCode.Do(item.rp_code, ptype);//非顶级分类 if (ressrel2 != null && ressrel2.Body != null && ressrel2.Body.recommend_list != null) { dbList2 = ressrel2.Body.recommend_list; } foreach (ShortRecommendPosition em in dbList2) { if (!codeList.Contains(em.rp_code.ToLower().Trim())) { deletePathList.Append(em.rp_code.Trim() + ","); } } } #endregion int returnVal = -1; var res = OpRecommendPosition.Do(posList, deletePathList.ToString()); if (res != null && res.Header != null && res.Header.Result != null && res.Header.Result.Code != null) { returnVal = Utils.StrToInt(res.Header.Result.Code, -1); } if (returnVal == 6) { return(Json(new { error = true, message = "该位置ID已存在" })); } if (returnVal == 0) { return(Json(new { error = false, message = "保存成功 ^_^" })); } } catch (Exception) { return(Json(new { error = true, message = "Xml解析失败..." })); } return(Json(new { error = true, message = "保存失败" })); }
public void Load(IDataSet dataSet, string xpathQuery) { //Temporary variables. IDataSet dsTmp = FactoryInstance.CreateDataSet(dataSet.SchemaFile, typeof(BaseDataSet)); bool inserted; //Read schemas inside the datasets. dsTmp.ReadXmlSchema(dsTmp.SchemaFile); dataSet.ReadXmlSchema(dataSet.SchemaFile); //Split the query in parts, with the element name and its filters. string[] parts = xpathQuery.Split('/'); //Reject queries with parent or current node filter expressions. //i.e.: publishers[pub_id="1389" and ./publisherTitles/price>20] should be converted to // publishers[pub_id="1389"]/publisherTitles[price>20] if (xpathQuery.IndexOf(".") != -1) { throw new ArgumentException("Parent or current node references are not allowed in the expression.", "xpathQuery"); } //Save a collection with elements in the query, without its filters. StringCollection queryelements = new StringCollection(); for (int i = 0; i < parts.Length; i++) { if (parts[i].IndexOf("[") == -1) { queryelements.Add(parts[i]); } else { queryelements.Add(parts[i].Substring(0, parts[i].IndexOf("["))); } } //Build a collection of filters, with keys pointing to the element name. StringDictionary queryfilters = new StringDictionary(); for (int i = 0; i < parts.Length; i++) { if (parts[i].IndexOf("[") != -1) { //Append element replacing brackets with node paths. queryfilters.Add(queryelements[i], (parts[i].Replace("[", "/")).Replace("]", "")); } } //Rebuild the query to retrieve the firt node and all the children. StringBuilder sb = new StringBuilder(); inserted = false; sb.Append(parts[0].Replace("]", "")); for (int i = 1; i < queryelements.Count; i++) { //If there's a filter in the element, add the condition to the query. if (queryfilters.ContainsKey(queryelements[i])) { inserted = true; sb.Append(" and ."); for (int j = 1; j < i; j++) { sb.Append("/" + queryelements[j]); } sb.Append("/" + queryfilters[queryelements[i]]); } } //Remove additional "and" if no filter is present in the first element. if (inserted && parts[0].IndexOf("[") == -1) { //Recover the length in characters, not bytes, from the string. int qty = parts[0].ToCharArray().Length; sb.Remove(qty, 5); sb.Insert(qty, "["); } if (inserted || (queryfilters.Count == 1 && parts[0].IndexOf("[") != -1)) { sb.Append("]"); } //Look for an element matching the dataset name, and add it to the query if present in the schema. XmlDocument doc = new XmlDocument(); doc.Load(dataSet.SchemaFile); //Add a namespace resolver for "xsd" prefix. XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable); mgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); //If we find the enclosing dataset element, insert it at the beginning of the query. if (doc.SelectNodes("//xsd:element[@name='" + dsTmp.DataSetName + "']", mgr).Count != 0) { sb.Insert(0, dsTmp.DataSetName + "/"); } //Load document with all the children to start filtering undesired nodes. SqlXmlCommand cmd = new SqlXmlCommand(_connection); //Set the root equal to the DataSetName. cmd.RootTag = dsTmp.DataSetName; cmd.CommandText = sb.ToString(); cmd.CommandType = SqlXmlCommandType.XPath; cmd.SchemaPath = dataSet.SchemaFile; MemoryStream stm = new MemoryStream(); cmd.CommandStream = stm; XmlReader r = cmd.ExecuteXmlReader(); dsTmp.ReadXml(r); SqlXmlAdapter ad = new SqlXmlAdapter(cmd); ad.Fill(dsTmp.GetState()); XmlDataDocument docsrc = new XmlDataDocument(dsTmp.GetState()); XmlDataDocument docdest = new XmlDataDocument(dataSet.GetState()); dataSet.EnforceConstraints = false; //Rebuild the query to retrieve the filtered nodes, and append them without their children. sb = new StringBuilder(); for (int i = 0; i < queryelements.Count; i++) { //Append all the previous node elements in the "chain". for (int j = 0; j < i; j++) { sb.Append(parts[j] + "/"); } //Add the current element filter, without the closing bracket, to append the next conditions. sb.Append(parts[i].Replace("]", "")); inserted = false; //Look for subsequent elements to add to the query. for (int j = i + 1; j < queryelements.Count; j++) { //If there's a filter in the element, add the condition to the query, otherwise ignore it. if (queryfilters.ContainsKey(queryelements[j])) { inserted = true; sb.Append(" and ."); //Append again all the previous node elements in this element "chain". for (int k = i + 1; k < j; k++) { sb.Append("/" + queryelements[k]); } //Add the current filter found. sb.Append("/" + queryfilters[queryelements[j]]); } } //Remove additional "and" if no filter is present in the first element. if (inserted && parts[i].IndexOf("[") == -1) { //Recover the length in characters, not bytes, from the string. int qty = 0; for (int k = 0; k <= i; k++) { qty += parts[k].ToCharArray().Length; } //Add the number of forward slashes appended to concatenate filters. qty += i; sb.Remove(qty, 5); sb.Insert(qty, "["); } //Close the filter expression. if (inserted || parts[i].IndexOf("[") != -1) { sb.Append("]"); } //Execute the XPath query starting from the root document element. XmlNodeList nodes = docsrc.SelectNodes("//" + sb.ToString()); //Iterate the nodes found with the query. foreach (XmlNode node in nodes) { //Retrieve the row corresponding to the node found. DataRow row = docsrc.GetRowFromElement((XmlElement)node); //Import the row into the destination DataSet. dataSet.Tables[row.Table.TableName].ImportRow(row); } sb = new StringBuilder(); } dataSet.EnforceConstraints = true; }
private void processaConferencia() { LabelConf.Text = ""; string filePath = dbClass.execmd("select vl_parametro from parametro where cd_parametro = 'DIRTMP'", true); //FileUpload1.SaveAs(filePath + FileUpload1.FileName); XmlDataDocument arq_Xml; arq_Xml = new XmlDataDocument(); //arq_Xml.Load(filePath + FileUpload1.FileName); //arq_Xml.Load(@"c:\temp\mt\ArqConf3513510220150101.CNX"); arq_Xml.Load(@"c:\temp\st\ArqConf3299670220150101.CNX"); //validar o codigo da empresa if (!getDadoXml(arq_Xml, "mensagemSIB/cabecalho/identificacaoTransacao/tipoTransacao").Equals("'CONFERENCIA CADASTRAL'")) { LabelConf.Text = "Arquivo de conferência inválido !"; return; } string NrRegANS = dbClass.execmd("select vl_parametro from parametro where cd_parametro = 'CDRANS'", true); /* * if (!getDadoXml(arq_Xml, "mensagemSIB/cabecalho/destino/registroANS").Equals("'" + NrRegANS + "'")) * { * LabelConf.Text = "Arquivo não pertence ao convenio registro ANS " + NrRegANS ; * return; * } * */ XmlNodeList lista = arq_Xml.SelectNodes("mensagemSIB/mensagem/ansParaOperadora/conferencia/beneficiario"); dbClass.execmd("delete ANS_CONF", false); LabelConf.Text = "Inicio processamento : " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"); foreach (XmlNode benef in lista) { string sql = "set dateformat dmy insert into ANS_CONF (" + " NrSeqArq,cco,IndDetalhe,cdIdentBenef,NmBenef,DtNasc,Sexo,cpf,NmMaeBenef,NrRegPlanoANS,DtAdesaoPlano,DtCancelamento, " + " DtReinclusao,Logradouro,NrEndereco,ComplLog,Bairro,Cidade,UF,Cep, VinculoBenef,MotivoCancel, CNPJ,cns,flag_compara) values ("; sql += "1,'"; sql += benef.Attributes.Item(0).InnerText + "',"; if (benef.Attributes.Item(1).InnerText.Equals("ATIVO")) { sql += "1,"; //ativo } else { sql += "3,"; //inativo } sql += getDadoXml(benef, "vinculo/codigoBeneficiario") + ","; sql += getDadoXml(benef, "identificacao/nome") + ","; sql += convertData(getDadoXml(benef, "identificacao/dataNascimento")) + ","; string sexo = getDadoXml(benef, "identificacao/sexo"); if (sexo.Equals('1')) { sql += "'M',"; } else { sql += "'F',"; } sql += getDadoXml(benef, "identificacao/cpf") + ","; sql += getDadoXml(benef, "identificacao/nomeMae") + ","; sql += getDadoXml(benef, "vinculo/numeroPlanoANS") + ","; sql += convertData(getDadoXml(benef, "vinculo/dataContratacao")) + ","; sql += convertData(getDadoXml(benef, "vinculo/dataCancelamento")) + ","; sql += convertData(getDadoXml(benef, "vinculo/dataReativacao")) + ","; sql += getDadoXml(benef, "endereco/logradouro") + ","; sql += getDadoXml(benef, "endereco/numero") + ","; sql += getDadoXml(benef, "endereco/complemento") + ","; sql += getDadoXml(benef, "endereco/bairro") + ","; if (benef.SelectSingleNode("endereco/codigoMunicipio") != null) { string nmcidade = dbClass.execmd("select ds_cidade from cidade where cd_ibge = " + getDadoXml(benef, "endereco/codigoMunicipio"), true); if (nmcidade.Length > 0) { sql += "'" + nmcidade + "',"; sql += dbClass.execmd("select uf from cidade where cd_ibge = " + getDadoXml(benef, "endereco/codigoMunicipio"), true) + ","; } else { sql += "null,null,"; } } else { sql += "null,null,"; } sql += getDadoXml(benef, "endereco/cep") + ","; sql += getDadoXml(benef, "vinculo/relacaoDependencia") + ","; sql += getDadoXml(benef, "vinculo/motivoCancelamento") + ","; sql += getDadoXml(benef, "vinculo/cnpjEmpresaContratante") + ","; sql += getDadoXml(benef, "identificacao/cns") + ","; if (eh_numerico(getDadoXml(benef, "vinculo/codigoBeneficiario").Replace("'", ""))) { sql += "1)"; } else { sql += "0)"; } dbClass.execmd(sql, false); } LabelConf.Text += " Fim processamento : " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"); }
public override int getDsCount() { return(dataDocument.SelectNodes("//rrd/ds").Count); }
private void button5_Click(object sender, EventArgs e) { if (openBrandingDialog.ShowDialog() == DialogResult.OK) { string zipName = openBrandingDialog.FileName; string directoryName = String.Format(@"{0}\{1}", TempPath, Path.GetFileNameWithoutExtension(zipName)); string metadataName = String.Format(@"{0}\metadata.xml", directoryName); XmlDataDocument xmldoc = new XmlDataDocument(); XmlNodeList xmlnode; string jsonName; string imageName; string destFileName = saveFileDialog1.FileName; string jsonfile; CreateTempDirectory(directoryName); ZipFile.ExtractToDirectory(zipName, directoryName); if (!File.Exists(metadataName)) { MessageBox.Show("No metadata.xml file found!\nAborting opening process.", "Error opening file", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } FileStream fs = new FileStream(metadataName, FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlnode = xmldoc.GetElementsByTagName("SystemResourcePackage"); if (!(xmlnode == null || xmlnode[0].Attributes["type"].Value != "UniversalBrand")) { txtBrandPackageName.Text = xmlnode[0].Attributes["name"].Value; txtBrandPackageVersion.Text = xmlnode[0].Attributes["version"].Value; //FGE: Get colors-filename xmlnode = xmldoc.SelectNodes("/*[local-name()='SystemResourcePackage'][namespace-uri()='http://schemas.microsoft.com/sqlserver/reporting/2016/01/systemresourcepackagemetadata'][1]/*[local-name()='Contents'][namespace-uri()='http://schemas.microsoft.com/sqlserver/reporting/2016/01/systemresourcepackagemetadata'][1]/*[local-name()='Item'][namespace-uri()='http://schemas.microsoft.com/sqlserver/reporting/2016/01/systemresourcepackagemetadata'][1]"); if (xmlnode != null) { jsonName = String.Format(@"{0}\{1}", directoryName, xmlnode[0].Attributes["path"].Value); using (var streamReader = new StreamReader(jsonName, Encoding.UTF8)) { jsonfile = streamReader.ReadToEnd().Replace("interface", "rsinterface");; _rsbrand = JsonConvert.DeserializeObject <RSBranding>(jsonfile); InitColorPickers(); streamReader.Close(); } } else { MessageBox.Show("XML File has wrong format!\nCannot find node 'colors'", "Error opening file", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //FGE: Get image-filename xmlnode = xmldoc.SelectNodes("/*[local-name()='SystemResourcePackage'][namespace-uri()='http://schemas.microsoft.com/sqlserver/reporting/2016/01/systemresourcepackagemetadata'][1]/*[local-name()='Contents'][namespace-uri()='http://schemas.microsoft.com/sqlserver/reporting/2016/01/systemresourcepackagemetadata'][1]/*[local-name()='Item'][namespace-uri()='http://schemas.microsoft.com/sqlserver/reporting/2016/01/systemresourcepackagemetadata'][2]"); if (xmlnode != null && xmlnode.Count == 1) { imageName = String.Format(@"{0}\{1}", directoryName, xmlnode[0].Attributes["path"].Value); using (FileStream stream = new FileStream(imageName, FileMode.Open, FileAccess.Read)) { pbLogo.Image = Image.FromStream(stream); } } else if (xmlnode == null) { MessageBox.Show("XML File has wrong format!\nCannot find node 'colors'", "Error opening file", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } else { MessageBox.Show("XML File has wrong format!\nEither no nodes were returned or type was not 'UniversalBrand'", "Error opening file", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } fs.Close(); } }
public void loadSAVE(Stream savfile) { //Load save file xmlsav = new XmlDataDocument(); xmlsav.PreserveWhitespace = true; //================================================================= // Here is where we get all the data from the save file and assign // it all to variables. //================================================================= //first we have to ensure that it is infact a valid save file bool isValid = false; try { xmlsav.Load(savfile); //Load the Save file as an XML document XmlNodeList hackNetSaveTag; hackNetSaveTag = xmlsav.GetElementsByTagName("HacknetSave"); if (hackNetSaveTag == null) { //Save file is invalid or corrupted. //Pop-up an error message before canceling the save load MessageBox.Show("The file given was either corrupted or not a valid Hacknet savefile.", "Invalid Save!", MessageBoxButtons.OK, MessageBoxIcon.Error); isValid = false; } else { isValid = true; } } catch { //Empty catch statement, this prevents the program from crashing in the event that something goes wrong. //Log this to debug log Console.WriteLine("DEBUG: Exception handled whilst loading save file."); isValid = false; } if (isValid == false) { MessageBox.Show("The file given was either corrupted or not a valid Hacknet savefile.", "Invalid Save!", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { //Continue loading the save file. XmlNode hnSav = xmlsav.GetElementsByTagName("HacknetSave")[0]; XmlAttributeCollection miscData = hnSav.Attributes; string plrName = miscData.GetNamedItem("Username").InnerText; Console.WriteLine(plrName); //For debugging purposes. userNameInput.Text = plrName; //Set the username input textbox to the current username. textBox1.Text = hnSav.Attributes.GetNamedItem("Language").InnerText; //get language string mailIconDisabled = hnSav.Attributes.GetNamedItem("DisableMailIcon").InnerText; if (mailIconDisabled == "true") { hideMailFlag.Checked = true; } else { hideMailFlag.Checked = false; } //Grab list of computers computers = xmlsav.SelectNodes("//HacknetSave//NetworkMap//network//computer"); Console.WriteLine(computers.Count); for (int i = 0; i < computers.Count; i++) { computerListBox.Items.Add(computers[i].Attributes.GetNamedItem("id").Value); Console.WriteLine(i); Console.WriteLine(computers[i].Attributes.GetNamedItem("id").Value); } XmlNode mission = xmlsav.GetElementsByTagName("mission")[0]; missionInput.Text = mission.Attributes.GetNamedItem("next").Value; goalInput.Text = mission.Attributes.GetNamedItem("goals").Value;; //==================================================== Console.WriteLine("Load completed successfully!"); } }
private void carregaErros() { if (dbClass.execmd("select vl_parametro from parametro where cd_parametro = 'DIRTMP'", true) == "") { dbClass.execmd("insert into parametro values ('DIRTMP','c:\\temp\\','Diretório temporário','U','SISTEMA',getdate())", true); } string filePath = dbClass.execmd("select vl_parametro from parametro where cd_parametro = 'DIRTMP'", true); XmlDataDocument arq_Xml; arq_Xml = new XmlDataDocument(); FileUpload1.SaveAs(filePath + FileUpload1.FileName); arq_Xml.Load(filePath + FileUpload1.FileName); lnkDownloadErros.Visible = false; if (arq_Xml.SelectSingleNode("mensagemSIB/cabecalho/destino/registroANS") != null) { if (dbClass.execmd("select vl_parametro from parametro where cd_parametro = 'CDRANS'", true) != arq_Xml.SelectSingleNode("mensagemSIB/cabecalho/destino/registroANS").InnerText) { lblMensagem.Text = "Arquivo de retorno do SIB não pertence à empresa"; return; } } else { lblMensagem.Text = "Arquivo não é um arquivo de retorno válido do SIB"; return; } XmlNodeList lista = arq_Xml.SelectNodes("mensagemSIB/mensagem/ansParaOperadora/resultadoProcessamento/arquivoProcessado/registrosRejeitados/registroRejeitado"); string linha = ""; //dbClass db = new dbClass(); string nmArquivo = arq_Xml.SelectSingleNode("mensagemSIB/mensagem/ansParaOperadora/resultadoProcessamento/arquivoProcessado/protocoloProcessamento/nomeArquivo").InnerText; nmArquivo = nmArquivo.Substring(0, nmArquivo.Length - 3); StreamWriter arq = new StreamWriter(filePath + "erro_" + nmArquivo + ".txt"); Session["filePath"] = filePath; Session["fileName"] = "erro_" + nmArquivo + ".txt"; Session["temErro"] = "N"; arq.WriteLine("TP CCO/CODIGO CAMPO COM ERRO CONTEUDO ENVIADO DO CAMPO COM ERRO MENSAGEM DE ERRO"); arq.WriteLine("=========================================================================================================================================================================================================================="); if (lista.Count == 0) { lblMensagem.Text = "Não ocorreram erros"; return; } foreach (XmlNode rejeitado in lista) { if (rejeitado.Attributes[2].InnerText == "INCLUSÃO") { linha = "I"; linha += rejeitado.Attributes[0].InnerText.Substring(rejeitado.Attributes[0].InnerText.Length - 8, 8) + " "; string nmUsuario = dbClass.execmd("select nome from usuario where codigo_completo = " + rejeitado.Attributes[0].InnerText, true); if (nmUsuario.Length > 30) { nmUsuario = nmUsuario.Substring(0, 30); } else { nmUsuario = nmUsuario.PadRight(30, ' '); } linha += nmUsuario; } else if (rejeitado.Attributes[2].InnerText == "RETIFICAÇÃO") { linha = "A"; linha += dbClass.execmd("select codigo_completo from usuario where cco = '" + rejeitado.Attributes[0].InnerText.Substring(0, 10) + "'", true).PadRight(8, '0') + " "; string nmUsuario = dbClass.execmd("select nome from usuario where cco = '" + rejeitado.Attributes[0].InnerText.Substring(0, 10) + "'", true); if (nmUsuario.Length > 30) { nmUsuario = nmUsuario.Substring(0, 30); } else { nmUsuario = nmUsuario.PadRight(30, ' '); } linha += nmUsuario + " "; } else if (rejeitado.Attributes[2].InnerText == "EXCLUSÃO") { linha = "E"; linha += dbClass.execmd("select codigo_completo from usuario where cco = '" + rejeitado.Attributes[0].InnerText.Substring(0, 10) + "'", true).PadRight(8, '0') + " "; string nmUsuario = dbClass.execmd("select nome from usuario where cco = '" + rejeitado.Attributes[0].InnerText.Substring(0, 10) + "'", true); if (nmUsuario.Length > 30) { nmUsuario = nmUsuario.Substring(0, 30); } else { nmUsuario = nmUsuario.PadRight(30, ' '); } linha += nmUsuario + " "; } else { linha = "R"; linha += dbClass.execmd("select codigo_completo from usuario where cco = '" + rejeitado.Attributes[0].InnerText.Substring(0, 10) + "'", true).PadRight(8, '0') + " "; string nmUsuario = dbClass.execmd("select nome from usuario where cco = '" + rejeitado.Attributes[0].InnerText.Substring(0, 10) + "'", true); if (nmUsuario.Length > 30) { nmUsuario = nmUsuario.Substring(0, 30); } else { nmUsuario = nmUsuario.PadRight(30, ' '); } linha += nmUsuario + " "; } linha += " "; if (rejeitado.Attributes[0].InnerText.Length < 20) { linha += rejeitado.Attributes[0].InnerText.PadLeft(12, '0') + " "; } else { linha += rejeitado.Attributes[0].InnerText.Substring(18, 12) + " "; } //linha += rejeitado.SelectSingleNode("campoErro/erro/codigoErro").InnerText.PadLeft(10) + " "; try { linha += rejeitado.SelectSingleNode("campoErro/descricaoCampo").InnerText.PadRight(30).Substring(0, 30) + " "; if (rejeitado.SelectSingleNode("campoErro/valorCampo") != null) { linha += rejeitado.SelectSingleNode("campoErro/valorCampo").InnerText.PadRight(70).Substring(0, 70) + " "; } else { linha += "NÃO POSSUI VALOR NO XML".PadRight(70).Substring(0, 70) + " "; } linha += rejeitado.SelectSingleNode("campoErro/erro/mensagemErro").InnerText.PadRight(100).Substring(0, 100) + " "; } catch (Exception) { linha += "ERRO ao ler xml att 0 = " + rejeitado.Attributes[0].InnerText + " att 1 = " + rejeitado.Attributes[1].InnerText; } arq.WriteLine(linha); } Session["temErro"] = "S"; lnkDownloadErros.Visible = true; arq.Close(); }
public ActionResult PostRoleAccessData() { string xmlString = DoRequest.GetFormString("xml", false); xmlString = HttpUtility.UrlDecode(xmlString); int roleid = DoRequest.GetFormInt("id"); string ids = ""; int _count = 0; List <int> idsi = new List <int>(); try { XmlDataDocument xmlDoc = new XmlDataDocument(); xmlDoc.LoadXml(xmlString); XmlNodeList nodes = xmlDoc.SelectNodes("items/item"); if (nodes != null) { foreach (XmlNode item in nodes) { int access = Utils.StrToInt(item.Attributes["accessid"].Value.Trim(), 0); int issel = Utils.StrToInt(item.Attributes["isselect"].Value.Trim(), 0); if (issel == 1) { if (_count == 0) { ids = access.ToString(); } else { ids = ids + "," + access.ToString(); } _count++; idsi.Add(access); } } } } catch (Exception) { return(Json(new { error = true, input = "message", message = "Xml解析失败..." })); } _count = 0; string delids = ""; List <RoleAccessInfo> oldlist = new List <RoleAccessInfo>(); var resrole = QueryRoleAccess.Do(roleid); if (resrole != null && resrole.Body != null && resrole.Body.access_list != null) { oldlist = resrole.Body.access_list; } foreach (RoleAccessInfo item in oldlist) { if (!idsi.Contains(item.access_id)) { if (_count == 0) { delids = item.access_id.ToString(); } else { delids = delids + "," + item.access_id.ToString(); } _count++; } } if (delids.Equals("")) { delids = "0"; } var returnValue = -1; var res = AddRoleAccess.Do(roleid, ids, delids); if (res != null && res.Header != null && res.Header.Result != null && res.Header.Result.Code != null) { returnValue = Utils.StrToInt(res.Header.Result.Code, -1); } if (returnValue == 0) { return(Json(new { error = false, message = "操作成功!" })); } return(Json(new { error = true, message = "操作失败!" })); }
static void Main(string[] args) { if (!Directory.Exists(@".\Reports")) { Directory.CreateDirectory(@".\Reports"); } File.Copy(resultFileName, @".\Reports\TestResult.xml", true); double totalTestcases; double totalPassed; double totalFailed; double totalError; XmlDataDocument xmldoc = new XmlDataDocument(); XmlNodeList xmlResultsnode; errors = new List <ErrorItem>(); sucess = new List <SuccessItem>(); try { //Analize test results file FileStream fstream = new FileStream(resultFileName, FileMode.Open, FileAccess.Read); try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(fstream); LoadTestResults(xmlDoc.DocumentElement); } finally { fstream.Close(); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error occur: "); Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine(ex.Message); Console.Beep(); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(""); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); return; } CreatePlayBack playback = new CreatePlayBack(Directory.GetCurrentDirectory() + @"\Reports\"); playback.CreateReports(); FileStream fs = new FileStream(resultFileName, FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlResultsnode = xmldoc.SelectNodes("//test-results[contains(@ignored,'0')]"); totalTestcases = Convert.ToDouble(xmlResultsnode[0].Attributes["total"].Value); totalFailed = Convert.ToDouble(xmlResultsnode[0].Attributes["failures"].Value); totalError = Convert.ToDouble(xmlResultsnode[0].Attributes["errors"].Value); totalPassed = totalTestcases - totalFailed - totalError; totalFailed = totalFailed + totalError; StringBuilder sb = new StringBuilder(); sb.AppendLine("<Html>"); CreateHtmlHeader(sb); sb.AppendLine("<body background=\"./img/background.jpg\">"); CreateHeadline(sb); CreateSummary(sb, "EDMC Automation", totalTestcases, totalPassed, totalFailed); CreateBody(sb, sucess); CreateChartScript(sb, totalFailed, totalPassed); EndHtml(sb); FileStream f = new FileStream(htmlPath, FileMode.Create, FileAccess.Write); using (StreamWriter s = new StreamWriter(f)) s.WriteLine(sb.ToString()); if (File.Exists(htmlPath)) { Directory.Move(Directory.GetCurrentDirectory() + @"\Reports", Directory.GetCurrentDirectory() + @"\Reports_" + Guid.NewGuid()); Console.WriteLine("Report Generated"); } }