public void updateCartFile(List<CartObject> newCartObj) { bool found = false; string cartFile = "C:\\Users\\Kiran\\Desktop\\cart.xml"; if (!File.Exists(cartFile)) { XmlTextWriter xWriter = new XmlTextWriter(cartFile, Encoding.UTF8); xWriter.Formatting = Formatting.Indented; xWriter.WriteStartElement("carts"); xWriter.WriteStartElement("cart"); xWriter.WriteAttributeString("emailId", Session["emailId"].ToString()); xWriter.Close(); } XmlDocument doc = new XmlDocument(); doc.Load(cartFile); foreach (CartObject cartItem in newCartObj) { foreach (XmlNode xNode in doc.SelectNodes("carts")) { XmlNode cartNode = xNode.SelectSingleNode("cart"); if (cartNode.Attributes["emailId"].InnerText == Session["emailId"].ToString()) { found = true; XmlNode bookNode = doc.CreateElement("book"); XmlNode nameNode = doc.CreateElement("name"); nameNode.InnerText = cartItem.itemName; XmlNode priceNode = doc.CreateElement("price"); priceNode.InnerText = cartItem.itemPrice.ToString(); XmlNode quantityNode = doc.CreateElement("quantity"); quantityNode.InnerText = "1"; bookNode.AppendChild(nameNode); bookNode.AppendChild(priceNode); bookNode.AppendChild(quantityNode); cartNode.AppendChild(bookNode); } } if(!found) { XmlNode cartNode = doc.CreateElement("cart"); cartNode.Attributes["emailId"].InnerText = Session["emailId"].ToString(); XmlNode bookNode = doc.CreateElement("book"); XmlNode nameNode = doc.CreateElement("name"); nameNode.InnerText = cartItem.itemName; XmlNode priceNode = doc.CreateElement("price"); priceNode.InnerText = cartItem.itemPrice.ToString(); XmlNode quantityNode = doc.CreateElement("quantity"); quantityNode.InnerText = "1"; bookNode.AppendChild(nameNode); bookNode.AppendChild(priceNode); bookNode.AppendChild(quantityNode); cartNode.AppendChild(bookNode); doc.DocumentElement.AppendChild(cartNode); } } doc.Save(cartFile); }
public void Save(string path) { XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("Resources"); doc.AppendChild(root); XmlElement sheetsElem = doc.CreateElement("SpriteSheets"); foreach (KeyValuePair<string, SpriteSheet> pair in SpriteSheets) { XmlElement elem = doc.CreateElement(pair.Key); pair.Value.Save(doc, elem); sheetsElem.AppendChild(elem); } root.AppendChild(sheetsElem); XmlElement spritesElem = doc.CreateElement("Sprites"); foreach (KeyValuePair<string, Sprite> pair in Sprites) { XmlElement elem = doc.CreateElement(pair.Key); pair.Value.Save(doc, elem); spritesElem.AppendChild(elem); } root.AppendChild(spritesElem); XmlElement animsElem = doc.CreateElement("Animations"); foreach (KeyValuePair<string, Animation> pair in Animations) { XmlElement elem = doc.CreateElement(pair.Key); pair.Value.Save(doc, elem); animsElem.AppendChild(elem); } root.AppendChild(animsElem); doc.Save(path); }
private bool OverWriting() { //private async Task<bool> OverWriting() { if (ListingQueue.Any()) { XmlDocument xmlDoc; XmlElement xmlEle; XmlNode newNode; xmlDoc = new XmlDocument(); xmlDoc.Load("ImageData.xml"); // XML문서 로딩 newNode = xmlDoc.SelectSingleNode("Images"); // 추가할 부모 Node 찾기 xmlEle = xmlDoc.CreateElement("Image"); newNode.AppendChild(xmlEle); newNode = newNode.LastChild; xmlEle = xmlDoc.CreateElement("ImagePath"); // 추가할 Node 생성 xmlEle.InnerText = ListingQueue.Peek(); ListingQueue.Dequeue(); newNode.AppendChild(xmlEle); // 위에서 찾은 부모 Node에 자식 노드로 추가.. xmlDoc.Save("ImageData.xml"); // XML문서 저장.. xmlDoc = null; return true; } return false; }
/// 获取token,如果存在且没过期,则直接取token /// <summary> /// 获取token,如果存在且没过期,则直接取token /// </summary> /// <returns></returns> public static string GetExistAccessToken() { // 读取XML文件中的数据 string filepath = System.Web.HttpContext.Current.Server.MapPath("/XMLToken.xml"); FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader str = new StreamReader(fs, System.Text.Encoding.UTF8); XmlDocument xml = new XmlDocument(); xml.Load(str); str.Close(); str.Dispose(); fs.Close(); fs.Dispose(); string Token = xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText; DateTime AccessTokenExpires = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText); //如果token过期,则重新获取token if (DateTime.Now >= AccessTokenExpires) { AccessToken mode = Getaccess(); //将token存到xml文件中,全局缓存 xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText = mode.access_token; DateTime _AccessTokenExpires = DateTime.Now.AddSeconds(mode.expires_in); xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText = _AccessTokenExpires.ToString(); xml.Save(filepath); Token = mode.access_token; } return Token; }
public static string UpdateSagaXMLFile(ref DataTable _XMLDt, string XMLpath) { try { XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(XMLpath); XmlNode xmlnode = xmldoc.DocumentElement.ChildNodes[0]; xmlnode["ODBCDriverName"].InnerText = _XMLDt.Rows[0]["ODBCDriverName"].ToString(); xmlnode["HostName"].InnerText = _XMLDt.Rows[0]["HostName"].ToString(); xmlnode["ServerName"].InnerText = _XMLDt.Rows[0]["ServerName"].ToString(); xmlnode["ServiceName"].InnerText = _XMLDt.Rows[0]["ServiceName"].ToString(); xmlnode["Protocol"].InnerText = _XMLDt.Rows[0]["Protocol"].ToString(); xmlnode["DatabaseName"].InnerText = _XMLDt.Rows[0]["DatabaseName"].ToString(); xmlnode["UserId"].InnerText = _XMLDt.Rows[0]["UserId"].ToString(); xmlnode["Password"].InnerText = _XMLDt.Rows[0]["Password"].ToString(); xmlnode["ClientLocale"].InnerText = _XMLDt.Rows[0]["ClientLocale"].ToString(); xmlnode["DatabaseLocale"].InnerText = _XMLDt.Rows[0]["DatabaseLocale"].ToString(); xmldoc.Save(XMLpath); return ""; } catch (Exception err) { return err.Message; } }
public static void AddFP(long factionID, int addPoints) // Add Faction Points { CheckFP(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filename); XmlNode selectedFaction = xmlDoc.SelectSingleNode("//Faction[@FactionID='" + factionID + "']"); try { XmlAttributeCollection factioncheck = selectedFaction.Attributes; } catch (Exception) { // Create new faction element. XmlNode Faction = xmlDoc.CreateElement("Faction"); XmlAttribute FactionID = xmlDoc.CreateAttribute("FactionID"); XmlAttribute CurrentPoints = xmlDoc.CreateAttribute("CurrentPoints"); XmlNode rootNode = xmlDoc.SelectSingleNode("/FactionPoints"); FactionID.Value = Convert.ToString(factionID); CurrentPoints.Value = Convert.ToString(addPoints); ; Faction.Attributes.Append(FactionID); Faction.Attributes.Append(CurrentPoints); rootNode.AppendChild(Faction); xmlDoc.Save(filename); return; } XmlAttributeCollection attributeList = selectedFaction.Attributes; XmlNode attributeCurrentPoints = attributeList.Item(1); int currentPoints = Convert.ToInt32(attributeCurrentPoints.Value); int newPoints = currentPoints + addPoints; attributeCurrentPoints.Value = Convert.ToString(newPoints); xmlDoc.Save(filename); }
private void Continue_Click(object sender, RoutedEventArgs e) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\App.config"); XmlNode appSettingsNode = xmlDoc.SelectSingleNode("configuration/appSettings"); foreach (XmlNode childNode in appSettingsNode) { string selection = childNode.Attributes["key"].Value; switch (selection) { case "MagicWebPath": childNode.Attributes["value"].Value = webPathBox.Text; break; case "InputPath": childNode.Attributes["value"].Value = inputPathBox.Text; break; case "OutputPath": childNode.Attributes["value"].Value = outputPathBox.Text; break; default: break; } } xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\App.config"); xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); }
public Page2() { InitializeComponent(); XmlDocument xd = new XmlDocument(); xd.Load(QQMusic.MainWindow.skins+"\\List\\config.xml"); xd.Save(QQMusic.MainWindow.skins + "\\List\\config.xml.bak"); XmlNodeList node = xd.GetElementsByTagName("DlgItem"); int height=0; int temp; foreach (XmlNode xn in node) { XmlElement xe = (XmlElement)xn; if (xe.GetAttribute("id").Equals("DlgItem_Advertisement")) { height = int.Parse(xe.GetAttribute("height")); xe.SetAttribute("height","0"); textBlock1.Inlines.Add("广告高度:" + height+" 像素\n"); } } foreach (XmlNode xn in node) { XmlElement xe = (XmlElement)xn; if (xe.GetAttribute("id").IndexOf("List")!=-1) { temp = height + int.Parse(xe.GetAttribute("height")); xe.SetAttribute("height", ""+temp); textBlock1.Inlines.Add(xe.GetAttribute("id") + " 高度改变为:" + temp + " 像素\n"); } } xd.Save(QQMusic.MainWindow.skins + "\\List\\config.xml"); textBlock1.Inlines.Add("皮肤配置文件修改完成,已经自动备份。"); }
public static void WriteLog(string header,List<string> msgs) { string timeStamp = DateTime.Now.ToString("yyyyMMdd"); FileInfo activeLogInfo = new FileInfo(Environment.CurrentDirectory + "\\AppLog\\" + "LogFile_" + timeStamp + ".xml"); XmlDocument logDoc=new XmlDocument(); if (!activeLogInfo.Exists) { logDoc.LoadXml("<root></root>"); logDoc.Save(Environment.CurrentDirectory + "\\AppLog\\" + "LogFile_" + timeStamp + ".xml"); } logDoc.Load(Environment.CurrentDirectory + "\\AppLog\\" + "LogFile_" + timeStamp + ".xml"); XmlNode newItemNode = XmlHelper.CreateNode(logDoc, "item", ""); XmlHelper.SetAttribute(newItemNode, "recordedtime", DateTime.Now.ToString()); XmlHelper.SetAttribute(newItemNode, "header", header); foreach(string msg in msgs) { XmlNode msgNode = XmlHelper.CreateNode(logDoc, "msg", msg); newItemNode.AppendChild(msgNode); } logDoc.SelectSingleNode("/root").AppendChild(newItemNode); lock(logDoc) { logDoc.Save(Environment.CurrentDirectory + "\\AppLog\\" + "LogFile_" + timeStamp + ".xml"); } }
private void btn_thaydoi_Click(object sender, EventArgs e) { int i = 0; XmlNodeList xmlphienam, xmlnghia, xmltienganh; XmlDocument xmldoc = new XmlDocument(); xmldoc.Load("Source.xml"); xmltienganh = xmldoc.GetElementsByTagName("English"); xmlphienam = xmldoc.GetElementsByTagName("Phonetic"); xmlnghia = xmldoc.GetElementsByTagName("Vietnamese"); if (rd_phienam.Checked == true) { for (i = 0; i < xmltienganh.Count; i++) { if (xmltienganh[i].InnerText == txt_timkiem.Text) { xmlphienam[i].InnerText = txt_fix.Text; xmldoc.Save("Source.xml"); MessageBox.Show("Sửa phiên âm thành công !"); } } } if (rd_nghia.Checked == true) { for (i = 0; i < xmltienganh.Count; i++) { if (xmltienganh[i].InnerText == txt_timkiem.Text) { xmlnghia[i].InnerText = txt_nghiaviet.Text; xmldoc.Save("Source.xml"); MessageBox.Show("Sửa phiên âm thành công !"); } } } laydulieu(); }
public static void WriteFile() { string configPath = KEY_CHANGER_FOLD + "/" + KEY_CHANGER_CONFIG_FILE + ".xml"; XmlDocument xmlDoc = new XmlDocument(); if (!File.Exists(configPath)) { XmlDeclaration dec = xmlDoc.CreateXmlDeclaration(INIT_VERSION_STR, INIT_ENCODING_STR, null); xmlDoc.AppendChild(dec); XmlElement rootInit = xmlDoc.CreateElement(DOC_ROOT_STR); xmlDoc.AppendChild(rootInit); xmlDoc.Save(configPath); } else { xmlDoc.Load(configPath); } XmlNode root = xmlDoc.SelectSingleNode(DOC_ROOT_STR); root.RemoveAll(); foreach (KeyChangeItem item in KeyChangeManager.Instance.KeyChangeItemCollection) { WriteItem(item, ref xmlDoc, ref root); } xmlDoc.Save(configPath); }
public DefaultSettings() { xmlDoc = new XmlDocument(); Assembly asmblyMyGen = System.Reflection.Assembly.GetAssembly(typeof(NewAbout)); string version = asmblyMyGen.GetName().Version.ToString(); try { xmlDoc.Load(Application.StartupPath + @"\Settings\DefaultSettings.xml"); if(this.Version != version) { // Our Version has changed, write any new settings and their defaults this.FillInMissingSettings(version); xmlDoc.Save(Application.StartupPath + @"\Settings\DefaultSettings.xml"); } } catch { // Our file doesn't exist, let's create it StringBuilder defaultXML = new StringBuilder(); defaultXML.Append(@"<?xml version='1.0' encoding='utf-8'?>"); defaultXML.Append(@"<DefaultSettings Version='" + version + "' FirstTime='true'>"); defaultXML.Append(@"</DefaultSettings>"); xmlDoc.LoadXml(defaultXML.ToString()); this.FillInMissingSettings(version); xmlDoc.Save(Application.StartupPath + @"\Settings\DefaultSettings.xml"); } }
public void RecordAgent() { #region CLIENT RECORD if (!File.Exists(Generate.xmlPath)) return; XmlDocument xmld = new XmlDocument(); try { xmld.Load(Generate.xmlPath); } catch { Thread.Sleep(50); xmld.Load(Generate.xmlPath); } foreach (XmlElement xmle in xmld.GetElementsByTagName("clients")) { Coming c = new Coming(); c.id = xmle["id"].InnerText; c.lep = xmle["lep"].InnerText; c.macAddress = xmle["macAddress"].InnerText; c.licence = xmle["licence"].InnerText; c.Session = Convert.ToInt32(xmle["Session"].InnerText); c.port = Convert.ToInt32(xmle["port"].InnerText); c.Address = xmle["Address"].InnerText; c.cep = new IPEndPoint(IPAddress.Parse(c.Address), c.port); Agent.clients.Add(c.id, c); } try { xmld.Save(Generate.xmlPath); } catch { Thread.Sleep(50); xmld.Save(Generate.xmlPath); } Generate.isFirst = false; ("SERVER WORKING FIRST TIME & TRANSFERRED XML DATA TO Agent.clients").p2pDEBUG(); #endregion }
public void GenerateSettingsFile(WorkSettings settings) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.AppendChild(xmlDoc.CreateElement("PartCoverSettings")); if (settings.TargetPath != null) AppendValue(xmlDoc.DocumentElement, "Target", settings.TargetPath); if (settings.TargetWorkingDir != null) AppendValue(xmlDoc.DocumentElement, "TargetWorkDir", settings.TargetWorkingDir); if (settings.TargetArgs != null) AppendValue(xmlDoc.DocumentElement, "TargetArgs", settings.TargetArgs); if (settings.LogLevel > 0) AppendValue(xmlDoc.DocumentElement, "LogLevel", settings.LogLevel.ToString(CultureInfo.InvariantCulture)); if (settings.SettingsFile != null) AppendValue(xmlDoc.DocumentElement, "Output", settings.SettingsFile); if (settings.PrintLongHelp) AppendValue(xmlDoc.DocumentElement, "ShowHelp", settings.PrintLongHelp.ToString(CultureInfo.InvariantCulture)); if (settings.PrintVersion) AppendValue(xmlDoc.DocumentElement, "ShowVersion", settings.PrintVersion.ToString(CultureInfo.InvariantCulture)); foreach (string item in settings.IncludeItems) AppendValue(xmlDoc.DocumentElement, "Rule", "+" + item); foreach (string item in settings.ExcludeItems) AppendValue(xmlDoc.DocumentElement, "Rule", "-" + item); try { if ("console".Equals(settings.GenerateSettingsFileName, StringComparison.InvariantCulture)) xmlDoc.Save(Console.Out); else xmlDoc.Save(settings.GenerateSettingsFileName); } catch (Exception ex) { throw new SettingsException("Cannot write settings (" + ex.Message + ")"); } }
protected Boolean Authenticate(string email, string passwd) { string file = "C:\\Users\\Kiran\\Desktop\\userCred.xml"; if (File.Exists(file)) { XmlDocument xdoc = new XmlDocument(); xdoc.Load(file); foreach (XmlNode xNode in xdoc.SelectNodes("users/user")) if ((xNode.SelectSingleNode("email").InnerText == email) && (xNode.SelectSingleNode("password").InnerText == passwd)) { xdoc.Save(file); return true; } xdoc.Save(file); return false; } else { return false; } //string userCredFile = "~/ UserCred.xml"; //DataSet ds = new DataSet(); //FileStream fs = new FileStream(Server.MapPath(userCredFile), //FileMode.Open, FileAccess.Read); //StreamReader reader = new StreamReader(fs); //ds.ReadXml(reader); //fs.Close(); }
// Methods public static void F_AddKey(string i_StrKey, string i_StrValue) { if (!F_KeyExists(i_StrKey)) { throw new ArgumentNullException("Key", "<" + i_StrKey + "> does not exist in the configuration. Update failed."); } XmlDocument document = new XmlDocument(); document.Load(pathConfig); XmlNode node = document.SelectSingleNode(singleNote); try { if (node != null) { XmlNode newChild = node.FirstChild.Clone(); if (newChild.Attributes != null) { newChild.Attributes["key"].Value = i_StrKey; newChild.Attributes["value"].Value = i_StrValue; } node.AppendChild(newChild); } document.Save(pathConfig); document.Save(ConfigurationFile); } catch (Exception exception) { throw exception; } }
protected static void loadRoutesXFile() { string xmlFilePath = HttpContext.Current.Server.MapPath("~/App_Data") + "\\routes.xml"; XmlDocument routesXml = new XmlDocument(); routesXml.Load(xmlFilePath); XmlNode root = routesXml.DocumentElement; //Remove all attribute and child nodes. root.RemoveAll(); routesXml.Save(xmlFilePath); XmlNode routes = routesXml.SelectSingleNode("routes"); var route = JUTCLinq.SelectAllRoutes(); foreach (var r in route) { XmlNode newRoute = routesXml.CreateNode(XmlNodeType.Element, "route", null); //XmlAttribute stopNo = stopsXml.CreateAttribute("StopNo"); XmlNode routeNo = routesXml.CreateNode(XmlNodeType.Attribute, "routeNo", null); routeNo.Value = r.RouteNo.ToString(); newRoute.Attributes.SetNamedItem(routeNo); XmlNode totDist = routesXml.CreateNode(XmlNodeType.Attribute, "totalDistance", null); totDist.Value = r.TotalDistance.ToString(); newRoute.Attributes.SetNamedItem(totDist); XmlNode tripTime = routesXml.CreateNode(XmlNodeType.Attribute, "tripTime", null); tripTime.Value = r.TripTime.ToString(); newRoute.Attributes.SetNamedItem(tripTime); string stops = r.RouteStops.ToString(); string[] stopsArr = stops.Split(','); string distance = r.RouteDistances.ToString(); string[] distancesArr = distance.Split(','); for (int cnt = 0; cnt < stopsArr.Length; cnt++) { int digit = cnt + 1; XmlNode newStop = routesXml.CreateNode(XmlNodeType.Element, "stop"+ digit, null); newStop.InnerText = stopsArr[cnt]; newRoute.AppendChild(newStop); XmlNode newDist = routesXml.CreateNode(XmlNodeType.Element, "distance" + digit, null); newDist.InnerText = distancesArr[cnt]; newRoute.AppendChild(newDist); } routesXml.GetElementsByTagName("routes")[0].InsertAfter(newRoute, routesXml.GetElementsByTagName("routes")[0].LastChild); } routesXml.Save(xmlFilePath); }
public static void WriteFile(EnumInfo file) { if (file == null) return; if (!file.IsNeedWrite()) return; string configPath = EnuminfoConfig.ENUMINFO_FOLD_PATH + "/" + file.Name + ".xml"; XmlDocument xmlDoc = new XmlDocument(); if (!File.Exists(configPath)) { XmlDeclaration dec = xmlDoc.CreateXmlDeclaration(EnuminfoConfig.INIT_VERSION_STR, EnuminfoConfig.INIT_ENCODING_STR, null); xmlDoc.AppendChild(dec); XmlElement rootInit = xmlDoc.CreateElement(EnuminfoConfig.DOC_ROOT_STR); xmlDoc.AppendChild(rootInit); xmlDoc.Save(configPath); } else { xmlDoc.Load(configPath); } XmlNode root = xmlDoc.SelectSingleNode(EnuminfoConfig.DOC_ROOT_STR); root.RemoveAll(); XmlElement xmlItem = null; foreach (EnumItem item in file._EnumItemCollection) { XmlElement xmlColumn = xmlDoc.CreateElement(EnuminfoConfig.ENUMINFO_ELEMENT_COLUMN); xmlItem = xmlDoc.CreateElement(EnuminfoConfig.ENUMINFO_ELEMENT_NAME); xmlItem.InnerText = item.Name; xmlColumn.AppendChild(xmlItem); xmlItem = xmlDoc.CreateElement(EnuminfoConfig.ENUMINFO_ELEMENT_CODE); xmlItem.InnerText = item.ItemCode; xmlColumn.AppendChild(xmlItem); xmlItem = xmlDoc.CreateElement(EnuminfoConfig.ENUMINFO_ELEMENT_VALUE); xmlItem.InnerText = item.ItemValue; xmlColumn.AppendChild(xmlItem); xmlItem = xmlDoc.CreateElement(EnuminfoConfig.ENUMINFO_ELEMENT_DESC); xmlItem.InnerText = item.ItemDesc; xmlColumn.AppendChild(xmlItem); root.AppendChild(xmlColumn); } xmlDoc.Save(configPath); file.AlreadyWrite(); }
public static void save(IEnumerable<Employee> lst ) { //XmlNamespaceManager xmlns = new XmlNamespaceManager(); //xmlns.AddNamespace("tns","http://localhost/Employee.xsd"); if (null == lst) return; XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", "yes")); bool haserror = false; doc.AppendChild(doc.CreateElement("Employees")); //doc.DocumentElement.SetAttribute("xmlns", "http://localhost/Employee.xsd"); //doc.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); //doc.DocumentElement.SetAttribute("xsi:noNamespaceSchemaLocation", "Employee.xsd"); foreach (Employee emp in _lst) { doc.ChildNodes[1].AppendChild(buildEmployeeNode(emp,doc)); } doc.Save("_employees.xml"); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; XmlReader reader = XmlReader.Create("_employees.xml",settings); XmlSchema s = doc.Schemas.Add("http://localhost/Employee.xsd", "Employee.xsd"); doc.Load(reader); try { doc.Validate((Object sender, ValidationEventArgs e) => { switch (e.Severity) { case XmlSeverityType.Error: haserror = true; break; case XmlSeverityType.Warning: break; default: break; } }); } catch (Exception e) { } finally { reader.Close(); System.IO.File.Delete("_employees.xml"); } if (!haserror) doc.Save("Employees.xml"); }
public static void saveXMLDocument(XmlDocument xml, string filename) { System.IO.FileInfo file = new System.IO.FileInfo("../../XML/"); file.Directory.Create(); if ((filename != "") && (filename != null)) { xml.Save("../../XML/" + filename + ".xml"); } else { xml.Save("../../XML/" + DateTime.Now.ToString() + ".xml"); } }
static void Main(string[] args) { string file = @"C:\git_vistit\tips-main\src\centralen\Tips\TipsData\TipsDataModel\TipsModel.edmx"; XmlDocument doc = new XmlDocument(); doc.Load(file); doc.Save(file + "_" + DateTime.Now.Ticks); fixHead(doc); fixStorageModels(doc); fixConceptualModels(doc); fixMappings(doc); fixDiagram(doc); doc.Save(file); }
public static void UpdateManifest(string fullPath) { XmlDocument doc = new XmlDocument(); doc.Load(fullPath); if (doc == null) { Debug.LogError("Couldn't load " + fullPath); return; } XmlNode manNode = FindChildNode(doc, "manifest"); XmlNode applicationNode = FindChildNode(manNode, "application"); if (applicationNode == null) { Debug.LogError("Error parsing " + fullPath); return; } string ns = manNode.GetNamespaceOfPrefix("android"); findOrPrependElement("uses-permission", "name", ns, "com.farsitel.bazaar.permission.PAY_THROUGH_BAZAAR", manNode, doc); findOrPrependElement("uses-permission", "name", ns, "android.permission.INTERNET", manNode, doc); ns = applicationNode.GetNamespaceOfPrefix("android"); XmlElement applicationElement = FindChildElement(manNode, "application"); applicationElement.SetAttribute("name", ns, "com.soomla.store.SoomlaApp"); findOrAppendIabActivity(ns, applicationNode, doc); doc.Save(fullPath); }
public void AddItem(string cardKey, string name, string lastname, string username, string password, string XMLFile) { XmlDocument doc = new XmlDocument(); doc.Load("userdatabase.xml"); XmlElement newUser = doc.CreateElement("user"); newUser.SetAttribute("cardkey", cardKey); XmlElement newUserName = doc.CreateElement("username"); newUserName.InnerText = username; newUser.AppendChild(newUserName); XmlElement newPassword = doc.CreateElement("password"); newPassword.InnerText = password; newUser.AppendChild(newPassword); XmlElement newName = doc.CreateElement("name"); newName.InnerText = name; newUser.AppendChild(newName); XmlElement newLastName = doc.CreateElement("lastname"); newLastName.InnerText = lastname; newUser.AppendChild(newLastName); doc.FirstChild.AppendChild(newUser); doc.Save("userdatabase.xml"); }
public void RemoveItem(string cardkey, string XMLFile) { XmlDocument doc = new XmlDocument(); doc.Load("userdatabase.xml"); doc.FirstChild.RemoveChild(doc.SelectSingleNode("//user[@cardkey='" + cardkey + "']")); doc.Save("userdatabase.xml"); }
protected void Button1_Click(object sender, EventArgs e) { XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(Server.MapPath("Quotes.xml")); XmlElement parentelement = xmldoc.CreateElement("Item"); XmlElement ID = xmldoc.CreateElement("ID"); ID.InnerText = _txtPN.Value; XmlElement QTY = xmldoc.CreateElement("QTY"); QTY.InnerText = _txtQty.Value; XmlElement Product = xmldoc.CreateElement("Product"); Product.InnerText = _txtProduct.Value; XmlElement Cost = xmldoc.CreateElement("Cost"); Cost.InnerText = _txtCost.Value; parentelement.AppendChild(ID); parentelement.AppendChild(QTY); parentelement.AppendChild(Product); parentelement.AppendChild(Cost); xmldoc.DocumentElement.AppendChild(parentelement); xmldoc.Save(Server.MapPath("Quotes.xml")); _txtQty.Value = string.Empty; _txtProduct.Value = string.Empty; _txtCost.Value = string.Empty; _txtPN.Value = string.Empty; if (this.IsPostBack) { this.Get_Xml(); } }
public static void Save(string languageID, NameValueCollection translations) { string stub = Resource1.ResourceManager.GetString("ResxTemplate"); string xml = BuildFileName(languageID); StreamWriter writer = new StreamWriter(xml, false, Encoding.UTF8); writer.Write(stub); writer.Close(); XmlDocument doc = new XmlDocument(); doc.Load(xml); XmlNode nRoot = doc.SelectSingleNode("/root"); foreach (string key in translations.Keys) { if (translations[key] == null) continue; XmlNode nValue = doc.CreateElement("value"); nValue.InnerText = translations[key]; XmlNode nKey = doc.CreateElement("data"); XmlAttribute attr = nKey.OwnerDocument.CreateAttribute("name"); attr.InnerText = key; nKey.Attributes.Append(attr); attr = nKey.OwnerDocument.CreateAttribute("xml:space"); attr.InnerText = "preserve"; nKey.Attributes.Append(attr); nKey.AppendChild(nValue); nRoot.AppendChild(nKey); } doc.Save(xml); }
public static PrintTicket ModifyPrintTicket(PrintTicket ticket, string featureName, string newValue) { if (ticket == null) { throw new ArgumentNullException("ticket"); } var xmlDoc = new XmlDocument(); xmlDoc.Load(ticket.GetXmlStream()); var manager = new XmlNamespaceManager(xmlDoc.NameTable); manager.AddNamespace(xmlDoc.DocumentElement.Prefix, xmlDoc.DocumentElement.NamespaceURI); var xpath = string.Format("//psf:Feature[contains(@name, 'InputBin')]/psf:Option", featureName); var node = xmlDoc.SelectSingleNode(xpath, manager); if (node != null) { node.Attributes["name"].Value = newValue; } var printTicketStream = new MemoryStream(); xmlDoc.Save(printTicketStream); printTicketStream.Position = 0; var modifiedPrintTicket = new PrintTicket(printTicketStream); return modifiedPrintTicket; }
private void DoFilters() { string filtersFile = vcxproj + ".filters"; m_doc = new XmlDocument(); m_doc.Load(filtersFile); XmlElement cppNode = FindCppItemGroup(); XmlElement headersNode = FindHeadersItemGroup(); XmlElement cppFilter = FindCppFilter(); XmlElement hFilter = FindhFilter(); AddFiles(cppNode, "cpp", "ClCompile", "FCS Converters\\Source Files" ); AddFiles(headersNode, "h", "ClInclude", "FCS Converters\\Header Files"); string tempFile = Path.GetTempFileName(); m_doc.Save(tempFile); string oldContent = File.Exists(vcxproj) ? File.ReadAllText(vcxproj) : ""; string newContent = File.ReadAllText(tempFile); if (oldContent != newContent) { File.Copy(tempFile, filtersFile, true); } File.Delete(tempFile); }
//read XML file for patent info public static SortedList<int, Patent> GetPatents() { XmlDocument doc = new XmlDocument(); //if file doesn't exist, create it if (!File.Exists("Patents.xml")) doc.Save("Patents.xml"); SortedList<int, Patent> patents = new SortedList<int, Patent>(); XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.IgnoreWhitespace = true; readerSettings.IgnoreComments = true; XmlReader readXml = null; try { readXml = XmlReader.Create(path, readerSettings); if (readXml.ReadToDescendant("Patent")) //read to first Patent node { do { Patent patent = new Patent(); patent.Number = Convert.ToInt32(readXml["Number"]); readXml.ReadStartElement("Patent"); patent.AppNumber = readXml.ReadElementContentAsString(); patent.Description = readXml.ReadElementContentAsString(); patent.FilingDate = DateTime.Parse(readXml.ReadElementContentAsString()); patent.Inventor = readXml.ReadElementContentAsString(); patent.Inventor2 = readXml.ReadElementContentAsString(); int key = patent.Number; //assign key to value patents.Add(key, patent); //add key-value pair to list } while (readXml.ReadToNextSibling("Patent")); } } catch (XmlException ex) { MessageBox.Show(ex.Message, "Xml Error"); } catch (IOException ex) { MessageBox.Show(ex.Message, "IO Exception"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Exception Occurred"); } finally { if (readXml != null) readXml.Close(); } return patents; }
/// <summary> /// 从XML文档中读取节点追加到另一个XML文档中 /// </summary> /// <param name="filePath">需要读取的XML文档绝对路径</param> /// <param name="xPath">范例: @"Skill/First/SkillItem"</param> /// <param name="toFilePath">被追加节点的XML文档绝对路径</param> /// <param name="toXPath">范例: @"Skill/First/SkillItem"</param> /// <returns></returns> public static bool AppendChild(string filePath, string xPath, string toFilePath, string toXPath) { try { XmlDocument doc = new XmlDocument(); doc.Load(toFilePath); XmlNode xn = doc.SelectSingleNode(toXPath); XmlNodeList xnList = ReadNodes(filePath, xPath); if (xnList != null) { foreach (XmlElement xe in xnList) { XmlNode n = doc.ImportNode(xe, true); xn.AppendChild(n); } doc.Save(toFilePath); } return true; } catch { return false; } }
//设置web.config private void SetWebConfig(string connectionString, out ConcurrentDictionary <string, string> messages) { messages = new ConcurrentDictionary <string, string>(); System.IO.FileInfo FileInfo = new FileInfo(Server.MapPath("~/web.config")); if (!FileInfo.Exists) { messages[string.Format("文件 : {0} 不存在", Server.MapPath("~/web.config"))] = ""; } System.Xml.XmlDocument xmldocument = new System.Xml.XmlDocument(); xmldocument.Load(FileInfo.FullName); bool FoundIt = false; XmlNode connNode = xmldocument.SelectSingleNode("//connectionStrings"); if (connNode.HasChildNodes) { for (int i = 0; i < connNode.ChildNodes.Count; i++) { XmlNode Node = connNode.ChildNodes[i]; if (Node.Name == "add") { try { if (Node.Attributes.GetNamedItem("name").Value == "SqlServer") { Node.Attributes.GetNamedItem("connectionString").Value = connectionString; } FoundIt = true; } catch (Exception e) { messages[e.Message] = e.StackTrace; FoundIt = true; } } } if (!FoundIt) { messages["修改 web.config 时出错"] = ""; } xmldocument.Save(FileInfo.FullName); } }
public void SaveTestToFile(string tFileName) { FileInfo tFileInfo = new FileInfo(tFileName); if (false == tFileInfo.Exists) { mStreamWriter = tFileInfo.CreateText(); } else { tFileInfo.Delete(); mStreamWriter = tFileInfo.CreateText(); } mStreamWriter.Close(); XmlDocument tDoc = new System.Xml.XmlDocument(); XmlElement tElementRoot = tDoc.CreateElement("DialogueInfoList"); tDoc.AppendChild(tElementRoot); int ti = 0; int tCount = mDialogueINfoList.Count; CDialogueInfo tInfo = null; XmlElement tElement_0 = null; for (ti = 0; ti < tCount; ti++) { tInfo = mDialogueINfoList[ti]; XmlElement tElement = tDoc.CreateElement("DialogueInfo"); tElement_0 = null; tElement_0 = tDoc.CreateElement("mId"); tElement_0.InnerText = tInfo.mId.ToString(); tElement.AppendChild(tElement_0); tElement_0 = null; tElement_0 = tDoc.CreateElement("mDialogue"); tElement_0.InnerText = tInfo.mDialogue; tElement.AppendChild(tElement_0); tElementRoot.AppendChild(tElement); } tDoc.Save(tFileName); }
static void RemoveVeryHidden(string fileName) { var docWorkbook = new System.Xml.XmlDocument(); docWorkbook.Load(fileName); var sheets = docWorkbook.GetElementsByTagName("sheet"); foreach (XmlNode sheet in sheets) { if (sheet.Attributes["state"] != null) { sheet.Attributes.Remove(sheet.Attributes["state"]); } } docWorkbook.Save(fileName); }
public static void SaveRecent() { if (recent != null) { XmlDocument doc = new System.Xml.XmlDocument(); XmlElement root = doc.CreateElement("recent"); doc.AppendChild(root); foreach (GPLocationProvider lp in recent) { root.AppendChild(lp.getXmlElement(doc, "location")); } doc.Save(GetRecentFileName()); } }
static void AddWorkbookProtection(string fileName, string password) { var docWorkbook = new System.Xml.XmlDocument(); docWorkbook.Load(fileName); XmlNode workbook = docWorkbook.DocumentElement; XmlElement workbookProtection = workbook.OwnerDocument.CreateElement("workbookProtection", docWorkbook.DocumentElement.NamespaceURI); workbookProtection.SetAttribute("workbookAlgorithmName", "SHA-512"); workbookProtection.SetAttribute("workbookHashValue", GenerateHash(password)); workbookProtection.SetAttribute("workbookSaltValue", salt); workbookProtection.SetAttribute("workbookSpinCount", spinCount); workbookProtection.SetAttribute("lockStructure", "1"); workbook.InsertAfter(workbookProtection, docWorkbook.GetElementsByTagName("xr:revisionPtr")[0]); docWorkbook.Save(fileName); }
private void btnSave_Click(object sender, System.EventArgs e) { int num = 0; string filename = System.Web.HttpContext.Current.Request.MapPath(Globals.ApplicationPath + string.Format("/Templates/master/{0}/config/HeaderMenu.xml", this.themName)); System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument(); xmlDocument.Load(filename); System.Xml.XmlNode xmlNode = xmlDocument.SelectSingleNode("root"); if (!int.TryParse(this.txtCategoryNum.Text, out num)) { this.ShowMsg("请输入有效果的数字", false); return; } xmlNode.Attributes["CategoryNum"].Value = num.ToString(); xmlDocument.Save(filename); }
public static void removeAppconfigAppSetting(string path, string key) { System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.Load(path); System.Xml.XmlNode xNode; System.Xml.XmlElement xElem1; xNode = xDoc.SelectSingleNode("//appSettings"); xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']"); if (xElem1 == null) { return; } xNode.RemoveChild(xElem1); xDoc.Save(path); }
/// <summary> /// 添加一项AppSettting /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void AddAppSetting(string key, string value) { XmlDocument xmlDoc = new System.Xml.XmlDocument(); string FullFilePath = AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.FriendlyName + ".config"; if (File.Exists(FullFilePath)) { xmlDoc.Load(FullFilePath); XmlNode AppSettingNode = xmlDoc.SelectNodes("configuration/appSettings")[0]; XmlElement AddElement = xmlDoc.CreateElement("add"); AddElement.SetAttribute("key", key); AddElement.SetAttribute("value", value); AppSettingNode.AppendChild(AddElement); xmlDoc.Save(FullFilePath); } }
private bool setASPNETProcessInfinite() { const string processModelNode = "/configuration/system.web/processModel"; const string infinite = "Infinite"; const string responseDeadlockInterval = "responseDeadlockInterval"; try { string sConfigFile = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() + "Config\\machine.config"; System.Xml.XmlNode node = null; System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.Load(sConfigFile); node = xmlDoc.SelectSingleNode(processModelNode); if (node == null) { // The processModel attribute doesn't exist, which basically // means that they've either heavily modified their ASP.NET // configuration or there is a very bad error with their system. return(false); } // Check node value System.Xml.XmlAttribute attrDeadlockInterval = node.Attributes[responseDeadlockInterval]; if (attrDeadlockInterval != null) { attrDeadlockInterval.InnerText = infinite; } else { node.Attributes.Append(xmlDoc.CreateAttribute(String.Empty, responseDeadlockInterval, infinite)); } // Overwrite the original file. xmlDoc.Save(sConfigFile); } catch (System.Exception) { // If an error occurred (such as the file being secured, etc.), just // return false. return(false); } return(true); }
public void RemoveCodeFromText() { string xmlPath = @"C:\PhD\Workbrench\GitHub_NeturalNetworks\Datasets\IssueDetailsRoslyn_02112019_3_RemoveCode.xml"; System.IO.StreamReader xmlStreamReader = new System.IO.StreamReader(xmlPath); System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.Load(xmlStreamReader); xmlStreamReader.Close(); var rulesDescNodes = xmlDoc.DocumentElement.GetElementsByTagName("IssueDetail"); if (rulesDescNodes != null) { foreach (XmlNode node in rulesDescNodes) { /*Remove Code from Description*/ var _valueD = node.ChildNodes[2].InnerText; int startIndex_D = _valueD.IndexOf("```"); int endIndex_D = _valueD.LastIndexOf("```"); int length_D = endIndex_D - startIndex_D + 1; if (startIndex_D > -1 && endIndex_D > -1) { _valueD = _valueD.Remove(startIndex_D, length_D); node.ChildNodes[2].InnerText = _valueD; } /*Remove Code From Title_Description*/ var _value = node.ChildNodes[3].InnerText; int startIndex = _value.IndexOf("```"); int endIndex = _value.LastIndexOf("```"); int length = endIndex - startIndex + 1; if (startIndex > -1 && endIndex > -1) { _value = _value.Remove(startIndex, length); node.ChildNodes[3].InnerText = _value; } } xmlDoc.Save(@"C:\PhD\Workbrench\GitHub_NeturalNetworks\Datasets\IssueDetailsRoslyn_02112019_3_RemoveCode.xml"); } MessageBox.Show("Done!"); }
private void SaveHeaderMenu(int id, int displaySequence) { string filename = System.Web.HttpContext.Current.Request.MapPath(Globals.ApplicationPath + string.Format("/Templates/sites/" + Hidistro.Membership.Context.HiContext.Current.User.UserId.ToString() + "/{0}/config/HeaderMenu.xml", this.themName)); System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument(); xmlDocument.Load(filename); System.Xml.XmlNodeList childNodes = xmlDocument.SelectSingleNode("root").ChildNodes; foreach (System.Xml.XmlNode xmlNode in childNodes) { if (xmlNode.Attributes["Id"].Value == id.ToString()) { xmlNode.Attributes["DisplaySequence"].Value = displaySequence.ToString(); break; } } xmlDocument.Save(filename); }
#pragma warning restore 0168 public static bool SaveConfiguration() { if (!m_bLoaded) { return(true); } try { m_xmlDoc.Save(m_strConfigurationFile); } catch (System.Exception) { return(false); } return(true); }
public void IdBasedElementSet_DefinedInConfig() { _engine = new LoadCalculator.LoadCalculatorLinkableEngine(); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load("./config.xml"); XmlElement root = doc.DocumentElement; XmlNodeList outputExchangeItems = root.SelectNodes("//OutputExchangeItem"); foreach (XmlNode exchangeItem in outputExchangeItems) { XmlNode elementSet = exchangeItem.SelectSingleNode("ElementSet"); XmlNode numelem = doc.CreateElement("NumberOfElements"); numelem.InnerText = "10"; elementSet.AppendChild(numelem); } doc.Save("./config_temp.xml"); ArrayList componentArguments = new ArrayList(); componentArguments.Add(new Argument("ConfigFile", "./config_temp.xml", true, "none")); _engine.Initialize((IArgument[])componentArguments.ToArray(typeof(IArgument))); int out_count = _engine.OutputExchangeItemCount; for (int i = 0; i <= out_count - 1; i++) { OutputExchangeItem oe = (OutputExchangeItem)_engine.GetOutputExchangeItem(i); Debug.Write("Testing Element Count..."); Assert.IsTrue(oe.ElementSet.ElementCount == 10); Debug.WriteLine("done."); Debug.Write("Testing Element Type..."); Assert.IsTrue(oe.ElementSet.ElementType == ElementType.IDBased); Debug.WriteLine("done."); Debug.Write("Testing Element Conv2SI..."); Assert.IsTrue(oe.Quantity.Unit.ConversionFactorToSI >= 0); Debug.WriteLine("done."); Debug.Write("Testing Element Offset2SI..."); Assert.IsTrue(oe.Quantity.Unit.OffSetToSI >= 0); Debug.WriteLine("done."); } Assert.IsTrue(_engine.TimeHorizon.Start.ModifiedJulianDay == CalendarConverter. Gregorian2ModifiedJulian(new DateTime(2009, 10, 27, 08, 30, 00))); doc = null; System.IO.File.Delete("./config_temp.xml"); _engine.Finish(); }
string getPlaylist(string id, bool isProductionId = false) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); if (isProductionId) { doc.InnerXml = string.Format(SOAP_TEMPLATE, "<itv:ProductionId>" + id + "</itv:ProductionId>", ""); } else { doc.InnerXml = string.Format(SOAP_TEMPLATE, "", id); } try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://secure-mercury.itv.com/PlaylistService.svc?wsdl"); req.Headers.Add("SOAPAction", "http://tempuri.org/PlaylistService/GetPlaylist"); req.Referer = "http://www.itv.com/Mercury/Mercury_VideoPlayer.swf?v=null"; req.ContentType = "text/xml;charset=\"utf-8\""; req.Accept = "text/xml"; req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"; req.Method = "POST"; WebProxy proxy = getProxy(); if (proxy != null) { req.Proxy = proxy; } Stream stream; using (stream = req.GetRequestStream()) doc.Save(stream); using (stream = req.GetResponse().GetResponseStream()) using (StreamReader sr = new StreamReader(stream)) { string responseXml = sr.ReadToEnd(); Log.Debug("ITVPlayer: Playlist response:\r\n\t {0}", responseXml); return(responseXml); } } catch (Exception ex) { Log.Warn("ITVPlayer: Failed to get playlist - {0}\r\n{1}", ex.Message, ex.StackTrace); return(null); } }
/// <summary> /// 保存web.config设置 /// </summary> /// <param name="xmlTargetElement">关键字</param> /// <param name="xmlText">value</param> /// 2007.05.09 修改 y.xiaobin public static void SaveXmlElementValue(string xmlTargetElement, string xmlText) { string returnInt = null; string filename = HttpContext.Current.Server.MapPath("~") + @"/Web.config"; System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument(); xmldoc.Load(filename); System.Xml.XmlNodeList topM = xmldoc.DocumentElement.ChildNodes; foreach (System.Xml.XmlNode element in topM) { if (element.Name == "appSettings") { System.Xml.XmlNodeList node = element.ChildNodes; if (node.Count > 0) { foreach (System.Xml.XmlNode el in node) { if (el.Name == "add") { if (el.Attributes["key"].InnerXml == xmlTargetElement) { //保存web.config数据 el.Attributes["value"].Value = xmlText; xmldoc.Save(HttpContext.Current.Server.MapPath(@"~/Web.config")); return; } } } } else { returnInt = "Web.Config配置文件未配置"; } break; } else { returnInt = "Web.Config配置文件未配置"; } } if (returnInt != null) { throw new Exception(returnInt); } }
static void AddVeryHidden(string fileName) { var docWorkbook = new System.Xml.XmlDocument(); docWorkbook.Load(fileName); var sheets = docWorkbook.GetElementsByTagName("sheet"); foreach (XmlElement sheet in sheets) { if (sheets.Item(0) == sheet) { continue; } sheet.SetAttribute("state", "veryHidden"); } docWorkbook.Save(fileName); }
private static void ProtectedConfiguration(string path) { XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(path); //Cria a seção criptografada var xmlContent = @"<configProtectedData><providers><add name='TripleDESProtectedConfigurationProvider' type='CriptoTools.TripleDESProtectedConfigurationProvider, CriptoTools' /></providers></configProtectedData>"; XElement element = XDocument.Parse(xmlContent).Root; var xmlProtected = new XmlDocument(); xmlProtected.LoadXml(element.ToString()); var nodeProtected = xmlProtected.FirstChild; XmlNode nodeConfiguration = doc.SelectSingleNode("/configuration"); var importNodeProvider = doc.ImportNode(nodeProtected, true); nodeConfiguration.InsertAfter(importNodeProvider, nodeConfiguration.FirstChild); // Pega a seção que será criptografada XmlNode node = doc.SelectSingleNode("/configuration/connectionStrings"); //Encripta os dados do nó var criptoNode = provider.Encrypt(node); //Deleta todos os childs nodes e attributos node.RemoveAll(); //Importa o no criptografado var importNodeCripto = doc.ImportNode(criptoNode, true); //Insere no nó de connection string node.InsertAfter(importNodeCripto, node.FirstChild); //Insere o atributo referencia para o configuration provider XmlAttribute attr = doc.CreateAttribute("configProtectionProvider"); attr.Value = "TripleDESProtectedConfigurationProvider"; node.Attributes.Append(attr); doc.Save(path); }
private static void ProtectedConfiguration(string path) { XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(path); //Creates an encrypted Section var xmlContent = @"<configProtectedData><providers><add name='TripleDESProtectedConfigurationProvider' type='CriptoProtectedConfigurationProvider.TripleDESProtectedConfigurationProvider, CriptoProtectedConfigurationProvider' /></providers></configProtectedData>"; XElement element = XDocument.Parse(xmlContent).Root; var xmlProtected = new XmlDocument(); xmlProtected.LoadXml(element.ToString()); var nodeProtected = xmlProtected.FirstChild; XmlNode nodeConfiguration = doc.SelectSingleNode("/configuration"); var importNodeProvider = doc.ImportNode(nodeProtected, true); nodeConfiguration.InsertAfter(importNodeProvider, nodeConfiguration.FirstChild); // Get the section that will be encrypted XmlNode node = doc.SelectSingleNode("/configuration/connectionStrings"); //Encripta os dados do nó var criptoNode = provider.Encrypt(node); //Remove all childs nodes and attributes node.RemoveAll(); //Import the encrypted node var importNodeCripto = doc.ImportNode(criptoNode, true); //Insert the node in connectionString node.InsertAfter(importNodeCripto, node.FirstChild); //Inserts the attribute reference to the provider configuration XmlAttribute attr = doc.CreateAttribute("configProtectionProvider"); attr.Value = "TripleDESProtectedConfigurationProvider"; node.Attributes.Append(attr); doc.Save(path); }
public void MontarXmlReciNFe(string Recibo) { string WSstats = null; XmlEnvio = null; WSstats = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"; WSstats += "<consReciNFe xmlns=\"http://www.portalfiscal.inf.br/nfe\" versao=\"3.10\">"; WSstats += "<tpAmb>1</tpAmb>"; WSstats += "<nRec>" + Recibo + "</nRec>"; WSstats += "</consReciNFe>"; System.Xml.XmlDocument XmlArq = new System.Xml.XmlDocument(); XmlArq.PreserveWhitespace = true; XmlArq.LoadXml(WSstats); XmlArq.Save("C:/teste.xml"); XmlEnvio = XmlArq.DocumentElement; }
public static bool SaveXml() { try { string dllDir = System.Reflection.Assembly.GetExecutingAssembly().Location; dllDir = dllDir.Substring(0, dllDir.LastIndexOf('\\'));//删除文件名 XmlTextWriter writer = new XmlTextWriter(dllDir + @"\..\" + U8.Interface.Bus.SysInfo.xmlFileName, Encoding.Default); writer.Formatting = Formatting.Indented; ConfigXml.Save(writer); writer.Close(); return(true); } catch (Exception ee) { return(false); } }
static void RemoveWorkbookProtection(string fileName) { var docWorkbook = new System.Xml.XmlDocument(); docWorkbook.Load(fileName); XmlNodeList protections = docWorkbook.GetElementsByTagName("workbookProtection"); try { foreach (XmlNode element in protections) { element.ParentNode.RemoveChild(element); } } catch { } docWorkbook.Save(fileName); }
/// <summary> /// Change the ASP.NET process model to runas Local System /// </summary> private bool changeASPNETProcessModel() { try { String machineConfigPath = HttpRuntime.MachineConfigurationDirectory + "\\machine.config"; System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.Load(machineConfigPath); System.Xml.XmlNode processModelNode = xmlDoc.SelectSingleNode(@"//configuration/system.web/processModel"); processModelNode.Attributes["userName"].Value = "System"; xmlDoc.Save(machineConfigPath); } catch (Exception) { return(false); } return(true); }
public void SaveRuleList(List <RewriterRule> ruleList) { System.Xml.XmlDocument xml = new System.Xml.XmlDocument(); System.Xml.XmlDeclaration xmldecl; xmldecl = xml.CreateXmlDeclaration("1.0", "utf-8", null); xml.AppendChild(xmldecl); System.Xml.XmlElement xmlelem = xml.CreateElement("", "rewrite", ""); foreach (RewriterRule rule in ruleList) { System.Xml.XmlElement e = xml.CreateElement("", "item", ""); e.SetAttribute("lookfor", rule.LookFor); e.SetAttribute("sendto", rule.SendTo); xmlelem.AppendChild(e); } xml.AppendChild(xmlelem); xml.Save(HttpContext.Current.Server.MapPath(string.Format("//config/rewrite.config", "/"))); }
/// <summary> /// 检测XXX.config的读写权限 /// </summary> /// <param name="fileName">存放Config物理路径 如:Server.MapPath("~/Web.config")</param> /// <returns>如果指定的XXX.config.config的权限能读写,则为 true;否则为 false。</returns> public static bool CheckConfigReadWrite(string fileName) { var fileInfo = new FileInfo(fileName); if (!fileInfo.Exists) { return(false); } var xmldocument = new System.Xml.XmlDocument(); xmldocument.Load(fileInfo.FullName); try { var moduleNode = xmldocument.SelectSingleNode("//appSettings"); if (moduleNode != null && moduleNode.HasChildNodes) { for (int i = 0; i < moduleNode.ChildNodes.Count; i++) { var node = moduleNode.ChildNodes[i]; if (node.Name == "add") { if (node.Attributes != null) { var sop = node.Attributes.GetNamedItem("key").Value; var sopValue = node.Attributes.GetNamedItem("value").Value; if (sop != "SopInitialization") { continue; } moduleNode.RemoveChild(node); break; } } } } xmldocument.Save(fileInfo.FullName); } catch { return(false); } return(true); }
private void btnInstall_Click(object sender, EventArgs e) { //If all values entered aren't blank, execute. if ((txtHostname.Text != "") && (txtDatabaseName.Text != "") && (txtDatabaseUsername.Text != "") && (txtDatabasePassword.Text != "")) { //Set variables to input. string Hostname, Name, Username, Password, Connection; Hostname = txtHostname.Text; Name = txtDatabaseName.Text; Username = txtDatabaseUsername.Text; Password = txtDatabasePassword.Text; Connection = "SERVER=" + Hostname + ";DATABASE=" + Name + ";UID=" + Username + ";PASSWORD="******";"; MySqlConnection connectionMySQL = new MySqlConnection(Connection); connectionMySQL.Open(); //If content exists in database, proceed setting database information. Else, execute SQL to create database. try { MySqlCommand checkIfExists = new MySqlCommand("SELECT * FROM serverOperatingSystems", connectionMySQL); MySqlDataReader rdr = checkIfExists.ExecuteReader(); } catch (Exception) { MySqlCommand installIfNotFound = new MySqlCommand("SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO'; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = '+00:00'; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; CREATE TABLE `backupNodeInformation`( `backupNodeID` int(11) NOT NULL, `backupNodeCompany` int(11) NOT NULL, `backupNodeLocation` int(11) NOT NULL, `backupNodeHostname` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `backupNodeUsername` varchar(30) COLLATE utf8_unicode_ci NOT NULL, `backupNodePassword` varchar(8192) COLLATE utf8_unicode_ci NOT NULL, `backupNodeOS` int(11) NOT NULL, `backupNodeIP` varchar(17) COLLATE utf8_unicode_ci NOT NULL, `backupNodeProcessor` varchar(40) COLLATE utf8_unicode_ci NOT NULL, `backupNodeRAM` varchar(10) COLLATE utf8_unicode_ci NOT NULL, `backupNodePort` int(10) NOT NULL, `backupNodeTransfer` varchar(4) COLLATE utf8_unicode_ci NOT NULL, `backupNodeBackupPath` varchar(128) COLLATE utf8_unicode_ci NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `failedLoginAttempts` ( `attemptID` int(11) NOT NULL, `attemptUsername` varchar(128) COLLATE utf8_unicode_ci NOT NULL, `attemptIP` varchar(123) COLLATE utf8_unicode_ci NOT NULL, `attemptTimeStamp` datetime NOT NULL, `attemptTries` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `serverCommands` ( `serverCommandID` int(11) NOT NULL, `serverCompany` int(11) NOT NULL, `serverOS` int(11) NOT NULL, `commandName` varchar(128) COLLATE utf8_unicode_ci NOT NULL, `serverCommand` varchar(8192) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `serverInformation` ( `serverID` int(11) NOT NULL, `serverCompany` int(11) NOT NULL, `serverLocation` int(11) NOT NULL, `serverHostname` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `serverUsername` varchar(30) COLLATE utf8_unicode_ci NOT NULL, `serverPassword` varchar(8192) COLLATE utf8_unicode_ci NOT NULL, `serverOS` int(11) NOT NULL, `serverIP` varchar(17) COLLATE utf8_unicode_ci NOT NULL, `serverProcessor` varchar(40) COLLATE utf8_unicode_ci NOT NULL, `serverRAM` varchar(10) COLLATE utf8_unicode_ci NOT NULL, `serverPort` int(10) NOT NULL, `serverTransfer` varchar(4) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `serverLocations` ( `locationID` int(11) NOT NULL, `companyID` int(11) NOT NULL, `locationName` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `locationLongitude` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `locationLatitude` varchar(20) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `serverOperatingSystems` ( `operatingSystemsID` int(11) NOT NULL, `operatingSystemsName` varchar(50) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; INSERT INTO `serverOperatingSystems` (`operatingSystemsID`, `operatingSystemsName`) VALUES (1, 'CentOS 5.10'), (2, 'CentOS 5.11'), (3, 'CentOS 5.5'), (4, 'CentOS 5.8'), (5, 'CentOS 5.9'), (6, 'CentOS 6.2'), (7, 'CentOS 6.3'), (8, 'CentOS 6.4'), (9, 'CentOS 6.5'), (10, 'CentOS 6.6'), (11, 'CentOS 6.9'), (12, 'CentOS 7.0'), (13, 'CentOS 7.1'), (14, 'CentOS 7.3'), (15, 'Debian 5.0'), (16, 'Debian 6.0'), (17, 'Debian 7.0'), (18, 'Debian 7.1'), (19, 'Debian 7.2'), (20, 'Debian 7.3'), (21, 'Debian 7.4'), (22, 'Debian 7.6'), (23, 'Debian 7.8'), (24, 'Debian 8.0'), (25, 'Debian 8.7'), (26, 'Fedora 13'), (27, 'Fedora 15'), (28, 'Fedora 16'), (29, 'Fedora 17'), (30, 'Fedora 18'), (31, 'Fedora 19'), (32, 'Fedora 20'), (33, 'Fedora 21'), (34, 'Scientific 6.3'), (35, 'Scientific 6.4'), (36, 'Scientific 6.6'), (37, 'Scientific 7.0'), (38, 'Scientific 7.1'), (39, 'Suse 11.3'), (40, 'Suse 12.2'), (41, 'Suse 12.3'), (42, 'Suse 13.1'), (43, 'Ubuntu 10.04'), (44, 'Ubuntu 10.10'), (45, 'Ubuntu 11.04'), (46, 'Ubuntu 11.10'), (47, 'Ubuntu 12.04'), (48, 'Ubuntu 12.10'), (49, 'Ubuntu 13.04'), (50, 'Ubuntu 13.10'), (51, 'Ubuntu 14.04'), (52, 'Ubuntu 15.04'), (53, 'Ubuntu 16.04'); CREATE TABLE `serverPort` ( `portID` int(11) NOT NULL, `portSpeed` varchar(20) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; INSERT INTO `serverPort` (`portID`, `portSpeed`) VALUES (6, '100Gbps'), (2, '100Mbps'), (5, '10Gbps'), (1, '10Mbps'), (3, '1Gbps'), (4, '3Gbps'); CREATE TABLE `systemReplies` ( `replyID` int(11) NOT NULL, `ticketID` int(11) NOT NULL, `userID` int(11) NOT NULL, `replyContent` varchar(8192) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `systemTickets` ( `ticketID` int(11) NOT NULL, `userCompanyID` int(11) NOT NULL, `ticketUpdated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `ticketCustomer` int(11) NOT NULL, `ticketRegarding` varchar(1024) COLLATE utf8_unicode_ci NOT NULL, `ticketSubject` varchar(200) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `userAccounts` ( `userID` int(11) NOT NULL, `userLogin` varchar(128) COLLATE utf8_unicode_ci NOT NULL, `userPassword` varchar(8192) COLLATE utf8_unicode_ci NOT NULL, `userForename` varchar(64) COLLATE utf8_unicode_ci NOT NULL, `userSurname` varchar(64) COLLATE utf8_unicode_ci NOT NULL, `userEmailAddress` varchar(128) COLLATE utf8_unicode_ci NOT NULL, `userImage` varchar(256) COLLATE utf8_unicode_ci NOT NULL, `userCompany` int(5) NOT NULL, `userRole` int(10) NOT NULL, `userIPAddress` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL, `userLastLogin` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `userCompanies` ( `companyID` int(11) NOT NULL, `ownerID` int(11) NOT NULL, `companyName` varchar(256) COLLATE utf8_unicode_ci NOT NULL, `companyDateCreated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `userPermissions` ( `permID` int(11) NOT NULL, `permRole` varchar(30) COLLATE utf8_unicode_ci NOT NULL, `permDateModified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `permChangePassword` tinyint(1) NOT NULL, `permChangeUsername` tinyint(1) NOT NULL, `permChangeEmail` tinyint(1) NOT NULL, `permViewServers` tinyint(1) NOT NULL, `permEditServers` tinyint(4) NOT NULL, `permDeleteServers` tinyint(1) NOT NULL, `permViewLocations` tinyint(1) NOT NULL, `permEditLocations` tinyint(1) NOT NULL, `permDeleteLocations` tinyint(1) NOT NULL, `permCreateTicket` tinyint(1) NOT NULL, `permAdminTicketView` tinyint(1) NOT NULL, `permCloseTicket` tinyint(1) NOT NULL, `permAddAction` tinyint(1) NOT NULL, `permEditAction` tinyint(1) NOT NULL, `permDeleteAction` tinyint(1) NOT NULL, `permRunCustomAction` tinyint(1) NOT NULL, `permAdminViewUsers` tinyint(1) NOT NULL, `permAdminEditUserInfo` tinyint(1) NOT NULL, `permAdminForcePassReset` tinyint(1) NOT NULL, `permAdminAddUser` tinyint(1) NOT NULL, `permAdminDelUser` tinyint(1) NOT NULL, `permAdminChangePermissions` tinyint(1) NOT NULL, `permControlServers` tinyint(1) NOT NULL, `permManageBackupSystem` tinyint(1) NOT NULL, `permCreateLocation` tinyint(1) NOT NULL, `permCreateServer` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; INSERT INTO `userPermissions` (`permID`, `permRole`, `permDateModified`, `permChangePassword`, `permChangeUsername`, `permChangeEmail`, `permViewServers`, `permEditServers`, `permDeleteServers`, `permViewLocations`, `permEditLocations`, `permDeleteLocations`, `permCreateTicket`, `permAdminTicketView`, `permCloseTicket`, `permAddAction`, `permEditAction`, `permDeleteAction`, `permRunCustomAction`, `permAdminViewUsers`, `permAdminEditUserInfo`, `permAdminForcePassReset`, `permAdminAddUser`, `permAdminDelUser`, `permAdminChangePermissions`, `permControlServers`, `permManageBackupSystem`, `permCreateLocation`, `permCreateServer`) VALUES (1, 'Admin', '2018-03-15 10:35:03', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), (2, 'System Administrator', '2018-03-15 10:36:09', 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0), (3, 'Datacentre Manager', '2018-03-15 10:36:55', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1), (4, 'Account Manager', '2018-03-15 10:37:42', 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0); ALTER TABLE `backupNodeInformation` ADD PRIMARY KEY (`backupNodeID`), ADD KEY `backupNodeCompany` (`backupNodeCompany`), ADD KEY `backupNodeLocation` (`backupNodeLocation`), ADD KEY `backupNodeOS` (`backupNodeOS`), ADD KEY `backupNodePort` (`backupNodePort`); ALTER TABLE `failedLoginAttempts` ADD PRIMARY KEY (`attemptID`); ALTER TABLE `serverCommands` ADD PRIMARY KEY (`serverCommandID`), ADD KEY `serverCompany` (`serverCompany`), ADD KEY `serverOS` (`serverOS`); ALTER TABLE `serverInformation` ADD PRIMARY KEY (`serverID`), ADD KEY `serverLocation` (`serverLocation`), ADD KEY `serverOS` (`serverOS`), ADD KEY `serverCompanyOwner` (`serverCompany`), ADD KEY `serverPort` (`serverPort`); ALTER TABLE `serverLocations` ADD PRIMARY KEY (`locationID`), ADD KEY `companyID` (`companyID`), ADD KEY `locationName` (`locationName`); ALTER TABLE `serverOperatingSystems` ADD PRIMARY KEY (`operatingSystemsID`), ADD KEY `operatingSystemsName` (`operatingSystemsName`); ALTER TABLE `serverPort` ADD PRIMARY KEY (`portID`), ADD KEY `portSpeed` (`portSpeed`); ALTER TABLE `systemReplies` ADD PRIMARY KEY (`replyID`), ADD KEY `ticketID` (`ticketID`), ADD KEY `userID` (`userID`); ALTER TABLE `systemTickets` ADD PRIMARY KEY (`ticketID`), ADD KEY `userCompanyID` (`userCompanyID`), ADD KEY `ticketCustomer` (`ticketCustomer`); ALTER TABLE `userAccounts` ADD PRIMARY KEY (`userID`), ADD KEY `userRole` (`userRole`); ALTER TABLE `userCompanies` ADD PRIMARY KEY (`companyID`); ALTER TABLE `userPermissions` ADD PRIMARY KEY (`permID`); ALTER TABLE `backupNodeInformation` MODIFY `backupNodeID` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `failedLoginAttempts` MODIFY `attemptID` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `serverCommands` MODIFY `serverCommandID` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `serverInformation` MODIFY `serverID` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `serverLocations` MODIFY `locationID` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `serverOperatingSystems` MODIFY `operatingSystemsID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=54; ALTER TABLE `serverPort` MODIFY `portID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; ALTER TABLE `systemReplies` MODIFY `replyID` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `systemTickets` MODIFY `ticketID` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `userAccounts` MODIFY `userID` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `userCompanies` MODIFY `companyID` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `userPermissions` MODIFY `permID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; ALTER TABLE `backupNodeInformation` ADD CONSTRAINT `backupNodeInformation_ibfk_1` FOREIGN KEY (`backupNodeCompany`) REFERENCES `userCompanies` (`companyID`), ADD CONSTRAINT `backupNodeInformation_ibfk_2` FOREIGN KEY (`backupNodeLocation`) REFERENCES `serverLocations` (`locationID`), ADD CONSTRAINT `backupNodeInformation_ibfk_3` FOREIGN KEY (`backupNodeOS`) REFERENCES `serverOperatingSystems` (`operatingSystemsID`), ADD CONSTRAINT `backupNodeInformation_ibfk_4` FOREIGN KEY (`backupNodePort`) REFERENCES `serverPort` (`portID`); ALTER TABLE `serverCommands` ADD CONSTRAINT `serverCommands_ibfk_1` FOREIGN KEY (`serverCompany`) REFERENCES `userCompanies` (`companyID`), ADD CONSTRAINT `serverCommands_ibfk_2` FOREIGN KEY (`serverOS`) REFERENCES `serverOperatingSystems` (`operatingSystemsID`); ALTER TABLE `serverInformation` ADD CONSTRAINT `serverInformation_ibfk_1` FOREIGN KEY (`serverCompany`) REFERENCES `userCompanies` (`companyID`), ADD CONSTRAINT `serverInformation_ibfk_2` FOREIGN KEY (`serverLocation`) REFERENCES `serverLocations` (`locationID`), ADD CONSTRAINT `serverInformation_ibfk_3` FOREIGN KEY (`serverOS`) REFERENCES `serverOperatingSystems` (`operatingSystemsID`), ADD CONSTRAINT `serverInformation_ibfk_4` FOREIGN KEY (`serverPort`) REFERENCES `serverPort` (`portID`); ALTER TABLE `serverLocations` ADD CONSTRAINT `serverLocations_ibfk_1` FOREIGN KEY (`companyID`) REFERENCES `userCompanies` (`companyID`); ALTER TABLE `systemReplies` ADD CONSTRAINT `systemReplies_ibfk_1` FOREIGN KEY (`ticketID`) REFERENCES `systemTickets` (`ticketID`), ADD CONSTRAINT `systemReplies_ibfk_2` FOREIGN KEY (`userID`) REFERENCES `userAccounts` (`userID`); ALTER TABLE `systemTickets` ADD CONSTRAINT `systemTickets_ibfk_1` FOREIGN KEY (`ticketCustomer`) REFERENCES `userAccounts` (`userID`), ADD CONSTRAINT `systemTickets_ibfk_2` FOREIGN KEY (`userCompanyID`) REFERENCES `userCompanies` (`companyID`); ALTER TABLE `userAccounts` ADD CONSTRAINT `userAccounts_ibfk_2` FOREIGN KEY (`userRole`) REFERENCES `userPermissions` (`permID`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;", connectionMySQL); installIfNotFound.ExecuteNonQuery(); } string xmlFile = "setup.xml"; //Set lines of XML file. System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.Load(xmlFile); xmlDoc.SelectSingleNode("Settings/Setup").InnerText = "Yes"; xmlDoc.SelectSingleNode("Settings/IP").InnerText = Hostname; xmlDoc.SelectSingleNode("Settings/Database").InnerText = Name; xmlDoc.SelectSingleNode("Settings/Username").InnerText = Username; xmlDoc.SelectSingleNode("Settings/Password").InnerText = Password; xmlDoc.Save(xmlFile); ConnectionString = "SERVER=" + Hostname + ";DATABASE=" + Name + ";UID=" + Username + ";PASSWORD="******";"; Hide(); setupEmailConfiguration email = new setupEmailConfiguration(); email.ShowDialog(); } else { System.Windows.Forms.MessageBox.Show("Please enter data into the form."); } }
public static void Save(Model model) { XmlDocument document = new System.Xml.XmlDocument(); XmlElement root = document.CreateElement("wimygit_config"); document.AppendChild(root); XmlElement recentRepositories = document.CreateElement("recent_repositories"); foreach (string recentRepository in model.RecentRepositoryPaths) { XmlElement element = document.CreateElement("recent_repository"); element.InnerText = recentRepository; recentRepositories.AppendChild(element); } root.AppendChild(recentRepositories); XmlElement lastTabs = document.CreateElement("last_tabs"); foreach (var lastTabInfo in model.LastTabInfos) { XmlElement element = document.CreateElement("last_tab"); XmlElement directory = document.CreateElement("directory"); directory.InnerText = lastTabInfo.Directory; element.AppendChild(directory); XmlElement is_focused = document.CreateElement("is_focused"); is_focused.InnerText = lastTabInfo.IsFocused.ToString(); element.AppendChild(is_focused); lastTabs.AppendChild(element); } root.AppendChild(lastTabs); string saveFilePath = GetSaveFilePath(); if (File.Exists(saveFilePath) == false) { string directoryName = Path.GetDirectoryName(saveFilePath); Directory.CreateDirectory(directoryName); } document.Save(saveFilePath); }
string getPlaylist(string id, bool isProductionId = false) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); if (isProductionId) { doc.InnerXml = string.Format(SOAP_TEMPLATE, "<itv:ProductionId>" + id + "</itv:ProductionId>", ""); } else { doc.InnerXml = string.Format(SOAP_TEMPLATE, "", id); } try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://mercury.itv.com/PlaylistService.svc"); req.Headers.Add("SOAPAction", "http://tempuri.org/PlaylistService/GetPlaylist"); req.Referer = "http://www.itv.com/mediaplayer/ITVMediaPlayer.swf?v=12.18.4/[[DYNAMIC]]/2"; req.ContentType = "text/xml;charset=\"utf-8\""; req.Accept = "text/xml"; req.Method = "POST"; WebProxy proxy = getProxy(); if (proxy != null) { req.Proxy = proxy; } Stream stream; using (stream = req.GetRequestStream()) doc.Save(stream); using (stream = req.GetResponse().GetResponseStream()) using (StreamReader sr = new StreamReader(stream)) { string responseXml = sr.ReadToEnd(); Log.Debug("ITVPlayer: Playlist response:\r\n\t {0}", responseXml); return(responseXml); } } catch (Exception ex) { Log.Warn("ITVPlayer: Failed to get playlist - {0}\r\n{1}", ex.Message, ex.StackTrace); return(null); } }
public static void SaveXmlFile(string filename, System.Xml.XmlDocument doc) { System.IO.FileStream fs = null; try { fs = new System.IO.FileStream(filename , System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Delete); doc.Save(fs); } finally { if (fs != null) { fs.Close(); } } }
public static Condition FromString(string filters) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(Condition.GetFiltersXmlString(filters)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); doc.Save(ms); ms.Flush(); ms.Position = 0; Condition c = new Condition(); System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(Condition)); System.Xml.XmlReader rdr = System.Xml.XmlReader.Create(ms); c = (Condition)ser.Deserialize(rdr); ms.Close(); FixCondition(c); return(c); }
public static string FormatXML(System.Xml.XmlDocument doc) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings { Indent = true, IndentChars = "\t", NewLineChars = "\r\n", NewLineHandling = System.Xml.NewLineHandling.Replace }; settings.OmitXmlDeclaration = true; using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, settings)) { doc.Save(writer); } return(sb.ToString()); }