public void CreateDumpFile() { try { System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument(); System.Xml.Linq.XElement xel = new System.Xml.Linq.XElement("DumpList"); foreach (var item in EquipmentManagerInstance.EquipmentList) { var list = new List<object>(); var xml = Utility.UtilityClass.ObjectToXml(item.Value); if (xml != null) { var equipXml = new System.Xml.Linq.XElement("Equipment"); var name = new System.Xml.Linq.XElement("Name"); name.Value = item.Key; var value = new System.Xml.Linq.XElement("Value"); value.Add(xml); equipXml.Add(name); equipXml.Add(value); xel.Add(equipXml); } } doc.Add(xel); string filename = DateTime.Now.ToString("yyyy-MM-dd_HHmmss") + ".xml"; string path = System.IO.Path.Combine(ConfigClasses.GlobalConst.ROOT_PATH, "DumpFile"); if (System.IO.Directory.Exists(path) == false) System.IO.Directory.CreateDirectory(path); string pathAndFilename = System.IO.Path.Combine(path, filename); doc.Save(pathAndFilename); } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.ToString()); } }
public void WriteInFile(String filename) { try { System.Xml.Linq.XDocument xDoc = new System.Xml.Linq.XDocument(new System.Xml.Linq.XDeclaration("1.0", "UTF-16", null), xelement); System.IO.StringWriter sw = new System.IO.StringWriter(); System.Xml.XmlWriter xWrite = System.Xml.XmlWriter.Create(sw); xDoc.Save(xWrite); xWrite.Close(); xDoc.Save(filename); } catch { } }
/// <summary> ///修改版本号 /// </summary> public void EditVersion(string ResourceName) { try { string version = "0"; string fileName = System.Web.HttpContext.Current.Server.MapPath("SysResourceVersion\\SysResourceVersion.xml"); System.Xml.Linq.XDocument sourceFile = System.Xml.Linq.XDocument.Load(fileName); var ent = from xml in sourceFile.Root.Elements("Resource") where xml.Attribute("Name").Value == ResourceName select xml; if (ent.Count() > 0) { var tmp = ent.FirstOrDefault(); if (tmp.Attribute("Version").Value != null) { version = tmp.Attribute("Version").Value; } double ver; double.TryParse(version, out ver); tmp.Attribute("Version").Value = (ver + 1).ToString(); tmp.Attribute("EditDate").Value = System.DateTime.Now.ToString(); sourceFile.Save(fileName); } } catch (Exception ex) { Tracer.Debug("权限系统SysDictionaryBLL-EditVersion" + ResourceName + System.DateTime.Now.ToString() + " " + ex.ToString()); } }
public void Save(string fileName) { // 创建文件对象。 System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName); // 如果文件对象所在目录不存在,则创建。 if (!System.IO.Directory.Exists(fileInfo.DirectoryName)) { System.IO.Directory.CreateDirectory(fileInfo.DirectoryName); } // 创建Xml文档。 System.Xml.Linq.XDocument xDocument = new System.Xml.Linq.XDocument(new System.Xml.Linq.XDeclaration("1.0", "utf-8", "")); // 添加Xml根节点。 xDocument.Add(new System.Xml.Linq.XElement(XmlRootName)); // 遍历配置文件中的配置组集合。 foreach (ConfigurationGroup configurationGroup in _ConfigurationGroupDictionary.Values) { // 创建并添加Xml组节点。 System.Xml.Linq.XElement xGroup = new System.Xml.Linq.XElement(XmlGroupNodeName); xGroup.SetAttributeValue(XmlKeyAttributeName, configurationGroup.Key); xDocument.Root.Add(xGroup); // 遍历配置组中的配置项集合。 foreach (ConfigurationItem configurationItem in configurationGroup) { // 创建并添加Xml项节点。 System.Xml.Linq.XElement xItem = new System.Xml.Linq.XElement(XmlItemNodeName); xItem.SetAttributeValue(XmlKeyAttributeName, configurationItem.Key); xItem.SetAttributeValue(XmlValueAttributeName, configurationItem.Encrypted ? Studio.Security.DESManager.Encrypt(configurationItem.Value) : configurationItem.Value); xItem.SetAttributeValue(XmlEncryptedAttributeName, configurationItem.Encrypted); xGroup.Add(xItem); } } // 保存到文件。 xDocument.Save(fileInfo.FullName); }
public void AddFile <T>(string input, T data) { if (!System.IO.File.Exists(Path.Combine(GetFullPath(), input))) { switch (Parser) { case StorageSystem.FileType.XML: var document = new System.Xml.Linq.XDocument(); using (var writer = document.CreateWriter()) new XmlSerializer(typeof(T)).Serialize(writer, data); document.Save(Path.Combine(GetFullPath(), input + ".xml")); break; case StorageSystem.FileType.JSON: var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented); System.IO.File.WriteAllText(Path.Combine(GetFullPath(), input + ".json"), jsonData); break; } } }
// TODO: Remove IfDef #if NETSTANDARD public static void Save(this System.Xml.Linq.XDocument xdoc, string fileName, System.Xml.Linq.SaveOptions options) { using (var fileStream = System.IO.File.Create(fileName)) { xdoc.Save(fileStream, options); } }
public static void UpdateDebugMode(string newValue) { string name = "DebugMode"; System.Xml.Linq.XDocument xDoc = System.Xml.Linq.XDocument.Load(GetConfigFilePath()); ConfigUtils.GetElement(xDoc, name).Value = newValue; xDoc.Save(GetConfigFilePath()); }
public static void SaveSafe(this System.Xml.Linq.XDocument doc, string path) { if (!Validation.CanWrite(path)) { DebugConsole.ThrowError($"Cannot save XML document to \"{path}\": failed validation"); return; } doc.Save(path); }
public static void SaveSafe(this System.Xml.Linq.XDocument doc, string path) { if (!Validation.CanWrite(path, false)) { DebugConsole.ThrowError($"Cannot save XML document to \"{path}\": modifying the files in this folder/with this extension is not allowed."); return; } doc.Save(path); }
private void M_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (System.Windows.Forms.MessageBox.Show("Would you like to save your map settings?", "Save Map?", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes) { Mapper m = (Mapper)sender; System.Xml.Linq.XElement ele = m.MapTreeView.WriteToXElement(_MapDirectory); System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument(ele); doc.Save(_MapDirectory + "/mapper.xml"); } }
public void XDocument() { LinqXmlDocument document = LinqXmlDocument.Parse(s_documents[DocumentName].Content); string minifiedContent; using (var writer = new StringWriter()) { document.Save(writer, LinqXmlSaveOptions.DisableFormatting); minifiedContent = writer.ToString(); } }
/// <summary> /// Функция удаления запись с экрана и xml /// </summary> /// <param name="sender">Объект</param> /// <param name="e">Событие</param> private void btn_Click(object sender, RoutedEventArgs e) { //Отчистка всех массивов с данными Themes.Clear(); Texts.Clear(); DataTimes.Clear(); buttonsMas.Clear(); System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load(file);//Открытие xml файла //Поиск совпадений по атрибуту num foreach (System.Xml.Linq.XElement xnode in xdoc.Root.Nodes()) { string st = (sender as Button).Name; //Получение названия кнопки по передаваемому объекту string numBut = ""; //Номер кнопки for (int i = 0; i < st.Length; i++) //Поиск номера кнопки в названии { if (st[i] == '1' || st[i] == '2' || st[i] == '3' || st[i] == '4' || st[i] == '5' || st[i] == '6' || st[i] == '7' || st[i] == '8' || st[i] == '9' || st[i] == '0') { numBut += st[i]; } } //Удаления соответствующего узла из xml if (xnode.Attribute("Num").Value == numBut.ToString()) { xnode.Remove(); } } //Заполнение атрибутов узла заного int x = 0; foreach (System.Xml.Linq.XElement xnode in xdoc.Root.Nodes()) { xnode.Attribute("Num").Value = x.ToString(); x++; } //Обработка исключения //При быстром удалении нескольких элементов файл не успевает закрыться и снова открыться try { xdoc.Save(file); } catch { MessageBox.Show("Повторите попытку через несколько секунд", "Слиокшом быстро"); } //Пересоздание заметок на экране listPanel.Children.Clear(); XmlRead(); createPanel(); }
public static void SaveBlogConnectionInfo(MP.BlogConnectionInfo coninfo, string filename) { var doc = new System.Xml.Linq.XDocument(); var p = new System.Xml.Linq.XElement("blogconnectioninfo"); doc.Add(p); p.Add(new System.Xml.Linq.XElement("blogurl", coninfo.BlogUrl)); p.Add(new System.Xml.Linq.XElement("blogid", coninfo.BlogId)); p.Add(new System.Xml.Linq.XElement("metaweblog_url", coninfo.MetaWeblogUrl)); p.Add(new System.Xml.Linq.XElement("username", coninfo.Username)); p.Add(new System.Xml.Linq.XElement("password", coninfo.Password)); doc.Save(filename); }
public static void SaveBlogConnectionInfo(MP.BlogConnectionInfo coninfo, string filename) { var doc = new System.Xml.Linq.XDocument(); var p = new System.Xml.Linq.XElement("blogconnectioninfo"); doc.Add(p); p.Add(new System.Xml.Linq.XElement("blogurl", coninfo.BlogUrl)); p.Add(new System.Xml.Linq.XElement("blogid", coninfo.BlogId)); p.Add(new System.Xml.Linq.XElement("metaweblog_url", coninfo.MetaWeblogUrl)); p.Add(new System.Xml.Linq.XElement("username", coninfo.Username)); p.Add(new System.Xml.Linq.XElement("password", coninfo.Password)); doc.Save(filename); }
public void Save(string filename) { var doc = new System.Xml.Linq.XDocument(); var p = new System.Xml.Linq.XElement("blogconnectioninfo"); doc.Add(p); p.Add(new System.Xml.Linq.XElement("blogurl", this.BlogURL)); p.Add(new System.Xml.Linq.XElement("blogid", this.BlogID)); p.Add(new System.Xml.Linq.XElement("metaweblog_url", this.MetaWeblogURL)); p.Add(new System.Xml.Linq.XElement("username", this.Username)); p.Add(new System.Xml.Linq.XElement("password", this.Password)); doc.Save(filename); }
/// <summary> /// Formats an <see cref="System.Xml.Linq.XDocument"/>. /// </summary> /// <param name="doc">The document to format.</param> /// <returns> /// A formatted XML document <see cref="string"/>. /// </returns> public static string Format(this System.Xml.Linq.XDocument doc) { var sb = new System.Text.StringBuilder(); var xw = new System.Xml.XmlTextWriter(new StringWriter(sb)) { Formatting = System.Xml.Formatting.Indented }; doc.Save(xw); return(sb.ToString()); }
/// <summary> /// Gets if the xml file has changed. /// </summary> /// <exception cref="System.ObjectDisposedException">XMLOblect is disposed.</exception> private bool Has_changed() { if (disposedValue) { throw new System.ObjectDisposedException("XMLOblect is disposed."); } System.IO.MemoryStream outxmlData = new System.IO.MemoryStream(); doc.Save(outxmlData); byte[] OutXmlBytes = outxmlData.ToArray(); if (System.IO.File.Exists(cached_xmlfilename)) { byte[] dataOnFile = System.IO.File.ReadAllBytes(cached_xmlfilename); if (!System.Linq.Enumerable.SequenceEqual(dataOnFile, OutXmlBytes)) { return(true); } } else { return(true); } return(false); }
public void WriteInFile(String filename) { try { System.Xml.Linq.XDocument xDoc = new System.Xml.Linq.XDocument(new System.Xml.Linq.XDeclaration("1.0", "UTF-16", null), xelement); System.IO.StringWriter sw = new System.IO.StringWriter(); System.Xml.XmlWriter xWrite = System.Xml.XmlWriter.Create(sw); xDoc.Save(xWrite); xWrite.Close(); xDoc.Save(filename); } catch { } }
private static FileStreamResult ToZippedFileStreamResult(System.Xml.Linq.XDocument xDocument) { var memoryStream = new MemoryStream(); using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { var data = archive.CreateEntry("data.xml"); using (var entryStream = data.Open()) { xDocument.Save(entryStream); } } memoryStream.Seek(0, SeekOrigin.Begin); return(new FileStreamResult(memoryStream, "application/zip")); }
public ActionResult SendMessage(string txtName, string txtEmail, string txtPhone, string txtAddress, string txtTag, string txtFax, string txtMessage) { System.Xml.Linq.XDocument xdocFeedXML = System.Xml.Linq.XDocument.Load(HttpContext.Server.MapPath(@"../App_Data\Contacts.xml")); txtName = System.Web.HttpUtility.HtmlEncode((txtName ?? "").Trim()); txtEmail = System.Web.HttpUtility.HtmlEncode((txtEmail ?? "").Trim()); txtPhone = System.Web.HttpUtility.HtmlEncode((txtPhone ?? "").Trim()); txtAddress = System.Web.HttpUtility.HtmlEncode((txtAddress ?? "").Trim()); txtTag = System.Web.HttpUtility.HtmlEncode((txtTag ?? "").Trim()); txtFax = System.Web.HttpUtility.HtmlEncode((txtFax ?? "").Trim()); txtMessage = System.Web.HttpUtility.HtmlEncode((txtMessage ?? "").Trim()); xdocFeedXML.Root.Add(new System.Xml.Linq.XElement("contact", new System.Xml.Linq.XAttribute("name", txtName), new System.Xml.Linq.XAttribute("email", txtEmail), new System.Xml.Linq.XAttribute("phone", txtPhone), new System.Xml.Linq.XAttribute("address", txtAddress), new System.Xml.Linq.XAttribute("tag", txtTag), new System.Xml.Linq.XAttribute("fax", txtFax), new System.Xml.Linq.XAttribute("message", txtMessage) )); xdocFeedXML.Save(HttpContext.Server.MapPath(@"../App_Data\Contacts.xml")); string[] emails = { "*****@*****.**", "*****@*****.**", "*****@*****.**" }; for (int x = 0; x < emails.Length; x++) { using (System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(fromEmail, emails[x], "You've got Mail!!", txtMessage)) { mm.IsBodyHtml = true; mm.Bcc.Add(fromEmail); System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(host, port); smtp.EnableSsl = true; System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential(fromEmail, pw); smtp.UseDefaultCredentials = false; smtp.Credentials = NetworkCred; smtp.Send(mm); } } return(Redirect("Contact?complete=1")); }
//http://msdn.microsoft.com/en-us/library/dn189154.aspx public static void UpdatePlayReadyConfigurationXMLFile(Guid keyId, string contentKeyB64) { System.Xml.Linq.XNamespace xmlns = "http://schemas.microsoft.com/iis/media/v4/TM/TaskDefinition#"; string keyDeliveryServiceUriStr = "http://playready.directtaps.net/pr/svc/rightsmanager.asmx"; Uri keyDeliveryServiceUri = new Uri(keyDeliveryServiceUriStr); string xmlFileName = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\..\..", @"MediaEncryptor_PlayReadyProtection.xml"); // Prepare the encryption task template System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Load(xmlFileName); var licenseAcquisitionUrlEl = doc .Descendants(xmlns + "property") .Where(p => p.Attribute("name").Value == "licenseAcquisitionUrl") .FirstOrDefault(); var contentKeyEl = doc .Descendants(xmlns + "property") .Where(p => p.Attribute("name").Value == "contentKey") .FirstOrDefault(); var keyIdEl = doc .Descendants(xmlns + "property") .Where(p => p.Attribute("name").Value == "keyId") .FirstOrDefault(); // Update the "value" property for each element. if (licenseAcquisitionUrlEl != null) { licenseAcquisitionUrlEl.Attribute("value").SetValue(keyDeliveryServiceUri); } if (contentKeyEl != null) { contentKeyEl.Attribute("value").SetValue(contentKeyB64); } if (keyIdEl != null) { keyIdEl.Attribute("value").SetValue(keyId); } doc.Save(xmlFileName); }
static void Main() { // Try to load the config, if it doesn't exist then simply create a default // config and add some standard keys to it. Config c = null; try { c = new Config("appconfig.xml"); } catch (FileNotFoundException e) { System.Xml.Linq.XDocument xdoc = new System.Xml.Linq.XDocument(); xdoc.Add(new System.Xml.Linq.XElement("configfile")); xdoc.Save("appconfig.xml"); c = new Config("appconfig.xml", xdoc); c.setConfig("ActicationPoint", (10).ToString()); c.setConfig("SamlePeriod", (2000).ToString()); c.setConfig("Cooldown", (5000).ToString()); } // Load the values from the config file. int act_point = c.getConfig <int>("ActivationPoint", 10); int sample_period = c.getConfig <int>("SamplePeriod", 2000); int cooldown = c.getConfig <int>("Cooldown", 5000); // Set up a trigger on N keys pressed in less than M seconds // and set up a handler for reaching the activation point that // mutes the microphone. mRateTrigger = new RateTrigger(act_point, sample_period); MicrophoneHandling mic = new MicrophoneHandling(cooldown); mRateTrigger.ActivationPointReached += mic.TriggeredLimit; // Set up hooks and stuff for the application. _hookID = SetHook(_proc); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); UnhookWindowsHookEx(_hookID); }
/// <summary> /// /// </summary> /// <param name="xdocument"></param> /// <param name="strXmlFilePath"></param> /// <param name="encoding"></param> /// <param name="declaration">编写 XML 声明</param> /// <param name="indent">该值指示是否缩进元素</param> public static void WriteXml(System.Xml.Linq.XDocument xdocument, string strXmlFilePath, Encoding encoding, bool indent) { StringBuilder sb = new StringBuilder(); System.Xml.XmlWriterSettings xws = new System.Xml.XmlWriterSettings(); xws.OmitXmlDeclaration = true; xws.Encoding = encoding; xws.Indent = indent; try { sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(sb, xws)) { xdocument.Save(xw); } using (StreamWriter sw = new StreamWriter(strXmlFilePath)) { sw.Write(sb.ToString()); } } catch (Exception ex) { } }
public async Task <IActionResult> Put(int id, [FromForm] DocumentoRequestDto documentoDto) { try { var documento = _mapper.Map <Documento>(documentoDto); documento.Id = id; //Aqui pongo un if para el put :v string stCadenaConnect = string.Empty; stCadenaConnect = "Data Source= LAPTOP-H34OREV3 ;Initial Catalog=EkayPRUEBAS ;user id=sa ; password=Ingrid1234;"; string cValue = ""; string cValue2 = ""; string cValue3 = ""; string stConnection = stCadenaConnect; string ruta = string.Empty; string nombre = string.Empty; string apellido = string.Empty; using (SqlConnection oConn = new SqlConnection(stConnection)) { SqlCommand cmd = new SqlCommand("sp_TraerDocumento", oConn); cmd.CommandType = System.Data.CommandType.StoredProcedure; using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd)) { sqlAdapter.SelectCommand.Parameters.AddWithValue("@id", id); } oConn.Open(); cmd.ExecuteNonQuery(); SqlDataReader _Reader = cmd.ExecuteReader(); if (_Reader.Read()) { cValue = _Reader[0].ToString(); cValue2 = _Reader[1].ToString(); cValue3 = _Reader[2].ToString(); } string respuesta = cValue + "," + cValue2 + "," + cValue3; oConn.Close(); char delimitador = ','; string[] valores = respuesta.Split(delimitador); ruta = valores[0].ToString(); nombre = valores[1].ToString(); apellido = valores[2].ToString(); } //extraer txt ruta = ruta.Replace("\\", "/"); string readText = System.IO.File.ReadAllText(ruta); //GENERAR XLM DE FIRMA string stXMLBody = string.Empty; System.Xml.Linq.XDocument xmlDoc = null; try { xmlDoc = new System.Xml.Linq.XDocument(new System.Xml.Linq.XDeclaration("1.0", "UTF-8", null), //tipo de escritura de xml UTF8 // aqui hay un error new System.Xml.Linq.XElement("XML", new System.Xml.Linq.XAttribute("version", "1.0"), // titulo del XML //Contenido del XML new System.Xml.Linq.XElement("Certificado", readText), new System.Xml.Linq.XElement("NombreFirmante", nombre), new System.Xml.Linq.XElement("ApellidoFirmante", apellido), new System.Xml.Linq.XElement("Key", documentoDto.Key.FileName), new System.Xml.Linq.XElement("CER", documentoDto.Cer.FileName) ) ); //creo un archivo de tipo escritura var wr = new StringWriter(new StringBuilder()); xmlDoc.Save(wr); //lo que se escribio arriba lo guardo en un documento xml stXMLBody = wr.ToString(); // se crea el archivo de tipo string para devolver el xml var filePath2 = Path.Combine(Environment.CurrentDirectory, "Archivos", "certificado" + DateTime.Now.ToString("hhmm") + ".xml"); //creo ruta System.IO.File.WriteAllText(filePath2, stXMLBody); //guardo el archivo en la ruta indicada documentoDto.Certificado = filePath2; //guardo la nueva ruta en el campo Certificado de la Bd } catch (Exception ex) { stXMLBody = ex.Message; } documento.Certificado = documentoDto.Certificado; await _service.UpdateDocumento(documento); var documentoresponseDto = _mapper.Map <Documento, DocumentoResponseDto>(documento); var response = new ApiResponse <DocumentoResponseDto>(documentoresponseDto);// aqui esta el error //correo confirmar /* System.Net.Mail.MailMessage mssg = new System.Net.Mail.MailMessage(); * mssg.To.Add(documentoDto.CorreoF); * mssg.Subject = "Firma de Documento (completada) | E-Kay"; * mssg.SubjectEncoding = System.Text.Encoding.UTF8; * string remitente = documentoDto.Correo; * mssg.Bcc.Add(remitente); * mssg.IsBodyHtml = true; * mssg.Body = "El documento "+ documento.NombreArchivo + " ha sido firmado exitosamente por: " + documentoDto.NombreF + ", en fecha: " + DateTime.Now; * mssg.BodyEncoding = System.Text.Encoding.UTF8; * mssg.From = new System.Net.Mail.MailAddress("*****@*****.**"); * * * System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient(); * cliente.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Firmando3LFutuR0"); * cliente.Port = 587; * cliente.EnableSsl = true; * cliente.Host = "smtp.gmail.com"; * * try * { * cliente.Send(mssg); * } * catch (Exception ex) * { * return BadRequest(ex.Message); * }*/ return(Ok(response)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
private void SauvegarderFichier() { App.MainVM.stop(); while (App.MainVM.Runnin) { } var MainVMXML = new System.Xml.Linq.XElement("MainVM"); MainVMXML.Add(new System.Xml.Linq.XElement("Dim", App.MainVM.Dim)); MainVMXML.Add(new System.Xml.Linq.XElement("TitreApplication", App.MainVM.TitreApplication)); MainVMXML.Add(new System.Xml.Linq.XElement("VitesseExec", App.MainVM.VitesseExec)); MainVMXML.Add(new System.Xml.Linq.XElement("Runnin", false)); var TerrainXML = new System.Xml.Linq.XElement("Terrain"); TerrainXML.Add(new System.Xml.Linq.XElement("NbTours", App.MainVM.Terrain.NbTours)); var CasesXML = new System.Xml.Linq.XElement("Cases"); foreach (CaseAbstrait caseAbs in App.MainVM.Terrain.Cases) { var CaseXML = new System.Xml.Linq.XElement("Case"); CaseXML.Add(new System.Xml.Linq.XElement("Class", caseAbs.GetType().Name)); CaseXML.Add(new System.Xml.Linq.XElement("CordX", caseAbs.CordX)); CaseXML.Add(new System.Xml.Linq.XElement("CordY", caseAbs.CordY)); CaseXML.Add(new System.Xml.Linq.XElement("PheromoneMaison", caseAbs.PheromoneMaison)); CaseXML.Add(new System.Xml.Linq.XElement("PheromoneNourriture", caseAbs.PheromoneNourriture)); CaseXML.Add(new System.Xml.Linq.XElement("NbTours", caseAbs.NbTours)); if (caseAbs is CaseNourriture) { var NourritureXML = new System.Xml.Linq.XElement("Nourriture"); NourritureXML.Add(new System.Xml.Linq.XElement("Poids", ((CaseNourriture)caseAbs).Nourriture.Poids)); CaseXML.Add(NourritureXML); } if (caseAbs is CaseFourmiliere) { var FourmiliereXML = new System.Xml.Linq.XElement("Fourmiliere"); FourmiliereXML.Add(new System.Xml.Linq.XElement("NombreNourritures", ((CaseFourmiliere)caseAbs).Fourmiliere.NombreNourritures)); FourmiliereXML.Add(new System.Xml.Linq.XElement("NombreTours", ((CaseFourmiliere)caseAbs).Fourmiliere.NombreTours)); CaseXML.Add(FourmiliereXML); } var FourmisXML = new System.Xml.Linq.XElement("Fourmis"); foreach (Fourmi fourmi in caseAbs.Fourmis) { var FourmiXML = new System.Xml.Linq.XElement("Fourmi"); FourmiXML.Add(new System.Xml.Linq.XElement("Vie", fourmi.Vie)); FourmiXML.Add(new System.Xml.Linq.XElement("StrategieFourmi", fourmi.StrategieFourmi.GetType().Name)); FourmisXML.Add(FourmiXML); } CaseXML.Add(FourmisXML); CasesXML.Add(CaseXML); } TerrainXML.Add(CasesXML); MainVMXML.Add(TerrainXML); var StatistiqueXML = new System.Xml.Linq.XElement("Statistique"); StatistiqueXML.Add(new System.Xml.Linq.XElement("NombreFourmis", App.MainVM.Statistique.NombreFourmis)); StatistiqueXML.Add(new System.Xml.Linq.XElement("NombreTours", App.MainVM.Statistique.NombreTours)); MainVMXML.Add(StatistiqueXML); var Sauvegarde = new System.Xml.Linq.XDocument(MainVMXML); SaveFileDialog SFDialog = new SaveFileDialog(); SFDialog.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments); SFDialog.DefaultExt = "xml"; SFDialog.AddExtension = true; SFDialog.Filter = "XML Files|*.xml|All Files|*.*"; SFDialog.FilterIndex = 1; if (SFDialog.ShowDialog() == true && SFDialog.FileName.Length > 0) { Sauvegarde.Save(SFDialog.FileName); System.Media.SystemSounds.Beep.Play(); MessageBox.Show("Fichier Sauvegardé !", "Sauvegarde", MessageBoxButton.OK); } }
public static void CheckModsVisibility() { HashSet <string> compilerOpLines = new HashSet <string>(); System.Xml.Linq.XDocument linkxml = new System.Xml.Linq.XDocument(); var flags = new HashSet <string>(ResManager.PreRuntimeDFlags); var mods = GetAllModsOrPackages(); for (int i = 0; i < mods.Length; ++i) { var mod = mods[i]; if (!IsModOptional(mod) || flags.Contains(mod)) { // enable string defpath; bool defPathExists = false; var pdir = GetModRootInPackage(mod); if (!string.IsNullOrEmpty(pdir)) { defpath = pdir + "/mcs.rsp"; if (defPathExists = System.IO.File.Exists(defpath)) { var pname = GetPackageName(mod); compilerOpLines.Add("-define:MOD_" + pname.ToUpper().Replace(".", "_")); } else { defpath = "Assets/Mods/" + mod + "/Link/mcs.rsp"; } } else { defpath = "Assets/Mods/" + mod + "/Link/mcs.rsp"; } if (defPathExists || System.IO.File.Exists(defpath)) { compilerOpLines.Add("-define:MOD_" + mod.ToUpper().Replace(".", "_")); try { compilerOpLines.UnionWith(System.IO.File.ReadAllLines(defpath)); } catch (Exception e) { Debug.LogException(e); } } string linkxmlpath; bool linkxmlPathExists = false; if (!string.IsNullOrEmpty(pdir)) { linkxmlpath = pdir + "/link.xml"; if (linkxmlPathExists = System.IO.File.Exists(linkxmlpath)) { } else { linkxmlpath = "Assets/Mods/" + mod + "/Link/link.xml"; } } else { linkxmlpath = "Assets/Mods/" + mod + "/Link/link.xml"; } if (linkxmlPathExists || System.IO.File.Exists(linkxmlpath)) { CapsEditorUtils.MergeXml(linkxml, linkxmlpath); } CapsEditorUtils.UnhideFile("Assets/Mods/" + mod); if (System.IO.File.Exists("Assets/Mods/" + mod + ".meta")) { CapsEditorUtils.UnhideFile("Assets/Mods/" + mod + ".meta"); } foreach (var sdir in UniqueSpecialFolders) { var moddir = "Assets/" + sdir + "/Mods/" + mod; if (System.IO.Directory.Exists(moddir)) { CapsEditorUtils.UnhideFile(moddir); if (System.IO.File.Exists(moddir + ".meta")) { CapsEditorUtils.UnhideFile(moddir + ".meta"); } } } } else { // disable CapsEditorUtils.HideFile("Assets/Mods/" + mod); if (System.IO.File.Exists("Assets/Mods/" + mod + ".meta")) { System.IO.File.Delete("Assets/Mods/" + mod + ".meta"); } foreach (var sdir in UniqueSpecialFolders) { var moddir = "Assets/" + sdir + "/Mods/" + mod; if (System.IO.Directory.Exists(moddir)) { CapsEditorUtils.HideFile(moddir); if (System.IO.File.Exists(moddir + ".meta")) { System.IO.File.Delete(moddir + ".meta"); } } } } } if (linkxml.Root != null) { linkxml.Save("Assets/link.xml"); } else { System.IO.File.Delete("Assets/link.xml"); } compilerOpLines.Remove(""); HashSet <string> existCompilerOpLines = new HashSet <string>(); if (System.IO.File.Exists("Assets/mcs.rsp")) { try { existCompilerOpLines.UnionWith(System.IO.File.ReadAllLines("Assets/mcs.rsp")); existCompilerOpLines.Remove(""); } catch (Exception e) { Debug.LogException(e); } } bool hasdiff = true; if (existCompilerOpLines.Count == compilerOpLines.Count) { var diff = new HashSet <string>(compilerOpLines); diff.ExceptWith(existCompilerOpLines); hasdiff = diff.Count > 0; } if (hasdiff) { if (System.IO.File.Exists("Assets/mcs.rsp")) { System.IO.File.Delete("Assets/mcs.rsp"); } if (System.IO.File.Exists("Assets/csc.rsp")) { System.IO.File.Delete("Assets/csc.rsp"); } var lines = compilerOpLines.ToArray(); Array.Sort(lines); System.IO.File.WriteAllLines("Assets/mcs.rsp", lines); System.IO.File.WriteAllLines("Assets/csc.rsp", lines); AssetDatabase.ImportAsset("Assets/mcs.rsp"); AssetDatabase.ImportAsset("Assets/csc.rsp"); EditorApplication.LockReloadAssemblies(); try { AssetDatabase.ImportAsset(CapsEditorUtils.__ASSET__, ImportAssetOptions.ForceUpdate); } catch { } AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(ScriptableObject.CreateInstance <CapsModDesc>())), ImportAssetOptions.ForceUpdate); // Update all package... //foreach (var kvp in _PackageName2ModName) //{ // var pname = kvp.Key; // AssetDatabase.ImportAsset("Packages/" + pname, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ImportRecursive); //} ReimportAllAssemblyDefinitions(); EditorApplication.UnlockReloadAssemblies(); } AssetDatabase.Refresh(); }
private void RemoveFromXml(string pathToRemove) { System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load("XmlData.xml"); xdoc.Root.Elements("imageLink").Select(el => el).Where(el => el.Value == pathToRemove).ToList().ForEach(el => el.Remove()); xdoc.Save("XmlData.xml"); }
public static ActionResult InstallPdfScribePrinter(Session session) { ActionResult printerInstalled; String driverSourceDirectory = session.CustomActionData["DriverSourceDirectory"]; String outputCommand = session.CustomActionData["OutputCommand"]; String outputCommandArguments = session.CustomActionData["OutputCommandArguments"]; String CurrentDir = session.CustomActionData["CurrentDir"]; String transform = session.CustomActionData["TRANSFORMS"]; SessionLogWriterTraceListener installTraceListener = new SessionLogWriterTraceListener(session); installTraceListener.TraceOutputOptions = TraceOptions.DateTime; PdfScribeInstaller installer = new PdfScribeInstaller(); installer.AddTraceListener(installTraceListener); try { System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument(); doc = System.Xml.Linq.XDocument.Load(CurrentDir + "\\" + "config.xml"); session.Log("Parameters Loaded:" + (doc.Root != null)); session.Log("Parameter Count:" + doc.Descendants("Parameter").Count()); var parameters = doc.Descendants("Parameter").ToDictionary(n => n.Attribute("Name").Value, v => v.Attribute("Value").Value); if (parameters.Any()) { session.Log("Parameters loaded into Dictionary Count: " + parameters.Count()); //Set the Wix Properties in the Session object from the XML file foreach (var parameter in parameters) { if (parameter.Key == "PrinterName" || parameter.Key == "PortName" || parameter.Key == "HardwareId") { session.CustomActionData[parameter.Key] = parameter.Value; } } } else { session.Log("No Parameters loaded"); } string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string specificFolder = Path.Combine(folder, "PdfScribe"); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (transform == ":instance2") { string printer2 = System.IO.Path.Combine(specificFolder, "scribe2"); System.IO.Directory.CreateDirectory(printer2); doc.Save(@printer2 + "\\" + "Config.xml"); } else if (transform == ":instance3") { string printer3 = System.IO.Path.Combine(specificFolder, "scribe3"); System.IO.Directory.CreateDirectory(printer3); doc.Save(@printer3 + "\\" + "Config.xml"); } else if (transform == ":instance4") { string printer4 = System.IO.Path.Combine(specificFolder, "scribe4"); System.IO.Directory.CreateDirectory(printer4); doc.Save(@printer4 + "\\" + "Config.xml"); } else if (transform == ":instance5") { string printer5 = System.IO.Path.Combine(specificFolder, "scribe5"); System.IO.Directory.CreateDirectory(printer5); doc.Save(@printer5 + "\\" + "Config.xml"); } else if (transform == ":instance6") { string printer6 = System.IO.Path.Combine(specificFolder, "scribe6"); System.IO.Directory.CreateDirectory(printer6); doc.Save(@printer6 + "\\" + "Config.xml"); } else if (transform == ":instance7") { string printer7 = System.IO.Path.Combine(specificFolder, "scribe7"); System.IO.Directory.CreateDirectory(printer7); doc.Save(@printer7 + "\\" + "Config.xml"); } else if (transform == ":instance8") { string printer8 = System.IO.Path.Combine(specificFolder, "scribe8"); System.IO.Directory.CreateDirectory(printer8); doc.Save(@printer8 + "\\" + "Config.xml"); } else if (transform == ":instance9") { string printer9 = System.IO.Path.Combine(specificFolder, "scribe9"); System.IO.Directory.CreateDirectory(printer9); doc.Save(@printer9 + "\\" + "Config.xml"); } else if (transform == ":instance10") { string printer10 = System.IO.Path.Combine(specificFolder, "scribe10"); System.IO.Directory.CreateDirectory(printer10); doc.Save(@printer10 + "\\" + "Config.xml"); } else if (transform == "" || transform == ":instance") { string printer1 = System.IO.Path.Combine(specificFolder, "scribe"); System.IO.Directory.CreateDirectory(printer1); doc.Save(@printer1 + "\\" + "Config.xml"); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } catch (Exception ex) { session.Log("ERROR in custom action SetInstallerProperties {0}", ex.ToString()); MessageBox.Show(ex.Message); return(ActionResult.Failure); } //Update Printer variables for Specific Instance if (installer.UpdateVal(session.CustomActionData["PrinterName"], session.CustomActionData["PortName"], session.CustomActionData["HardwareId"])) { //MessageBox.Show("Success"); //MessageBox.Show(installer.PRINTERNAME+"POrt="+installer.PORTNAME+"HD="+installer.HARDWAREID); } else { MessageBox.Show("Failed To Update Instance Setup"); } try { if (installer.InstallPdfScribePrinter(driverSourceDirectory, outputCommand, outputCommandArguments)) { printerInstalled = ActionResult.Success; } else { printerInstalled = ActionResult.Failure; } installTraceListener.CloseAndWriteLog(); } finally { if (installTraceListener != null) { installTraceListener.Dispose(); } } return(printerInstalled); }
public int WriteToFile(string FilePath) { if (this.Title == "") { this.Title = null; } if (this.Link == "") { this.Link = null; } if (this.Description == "") { this.Description = null; } if (this.Generator == "") { this.Generator = null; } if (this.Docs == "") { this.Docs = null; } if (this.Language == "") { this.Language = null; } if (this.PublicationDate == "") { this.PublicationDate = null; } if (this.LastBuildDate == "") { this.LastBuildDate = null; } System.Xml.Linq.XElement ListElements = new System.Xml.Linq.XElement("channel", new System.Xml.Linq.XElement("title", this.Title), new System.Xml.Linq.XElement("link", this.Link), new System.Xml.Linq.XElement("description", this.Description), new System.Xml.Linq.XElement("generator", this.Generator), new System.Xml.Linq.XElement("docs", this.Docs), new System.Xml.Linq.XElement("language", this.Language), new System.Xml.Linq.XElement("pubDate", this.PublicationDate), new System.Xml.Linq.XElement("lastBuildDate", this.LastBuildDate)); foreach (item Item in ItemList) { if (Item.Title == "") { Item.Title = null; } if (Item.Link == "") { Item.Link = null; } if (Item.Description == "") { Item.Description = null; } if (Item.PublicationDate == "") { Item.PublicationDate = null; } ListElements.Add( new System.Xml.Linq.XElement("item", new System.Xml.Linq.XElement("title", Item.Title), new System.Xml.Linq.XElement("link", Item.Link), new System.Xml.Linq.XElement("description", Item.Description), new System.Xml.Linq.XElement("pubDate", Item.PublicationDate))); } System.Xml.Linq.XDocument XmlRSSFile = new System.Xml.Linq.XDocument( new System.Xml.Linq.XElement("rss", new System.Xml.Linq.XAttribute("version", "2.0"), ListElements)); XmlRSSFile.Declaration = new System.Xml.Linq.XDeclaration("1.0", "ISO-8859-15", "true"); try { XmlRSSFile.Save(FilePath); } catch { } return(1); }