Close() public méthode

public Close ( ) : void
Résultat void
        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);
        }
Exemple #2
1
        private void CreateConfig()
        {
            this.ConfigFileLocation = Path.Combine(this.ThemeDirectory, "Theme.config");

            using (var xml = new XmlTextWriter(this.ConfigFileLocation, Encoding.UTF8))
            {
                xml.WriteStartDocument(true);
                xml.Formatting = Formatting.Indented;
                xml.Indentation = 4;

                xml.WriteStartElement("configuration");
                xml.WriteStartElement("appSettings");

                this.AddKey(xml, "ThemeName", this.Info.ThemeName);
                this.AddKey(xml, "Author", this.Info.Author);
                this.AddKey(xml, "AuthorUrl", this.Info.AuthorUrl);
                this.AddKey(xml, "AuthorEmail", this.Info.AuthorEmail);
                this.AddKey(xml, "ConvertedBy", this.Info.ConvertedBy);
                this.AddKey(xml, "ReleasedOn", this.Info.ReleasedOn);
                this.AddKey(xml, "Version", this.Info.Version);
                this.AddKey(xml, "Category", this.Info.Category);
                this.AddKey(xml, "Responsive", this.Info.Responsive ? "Yes" : "No");
                this.AddKey(xml, "Framework", this.Info.Framework);
                this.AddKey(xml, "Tags", string.Join(",", this.Info.Tags));
                this.AddKey(xml, "HomepageLayout", this.Info.HomepageLayout);
                this.AddKey(xml, "DefaultLayout", this.Info.DefaultLayout);

                xml.WriteEndElement(); //appSettings
                xml.WriteEndElement(); //configuration
                xml.Close();
            }
        }
        static string FormatText(string text)
        {
            XmlTextWriter writer = null;
            XmlDocument doc = new XmlDocument();
            XmlWriterSettings xwSettings = new XmlWriterSettings();
            string formattedText = string.Empty;
            try
            {
                doc.LoadXml(text);

                writer = new XmlTextWriter(".data.xml", null);
                writer.Formatting = Formatting.Indented;
                doc.Save(writer);
                writer.Close();

                using (StreamReader sr = new StreamReader(".data.xml"))
                {
                    formattedText = sr.ReadToEnd();
                }
            }
            finally
            {
                File.Delete(".data.xml");
            }
            return formattedText;
        }
Exemple #4
1
        private bool SaveRegister(string RegisterKey)
        {
            try
            {
                
                Encryption enc = new Encryption();
                FileStream fs = new FileStream("reqlkd.dll", FileMode.Create);
                XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);

                // Khởi động tài liệu.
                w.WriteStartDocument();
                w.WriteStartElement("QLCV");

                // Ghi một product.
                w.WriteStartElement("Register");
                w.WriteAttributeString("GuiNumber", enc.EncryptData(sGuiID));
                w.WriteAttributeString("Serialnumber", enc.EncryptData(sSerial));
                w.WriteAttributeString("KeyRegister", enc.EncryptData(RegisterKey, sSerial + sGuiID));
                w.WriteEndElement();

                // Kết thúc tài liệu.
                w.WriteEndElement();
                w.WriteEndDocument();
                w.Flush();
                w.Close();
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }
Exemple #5
1
        /// <summary>
        /// Define o valor de uma configuração
        /// </summary>
        /// <param name="file">Caminho do arquivo (ex: c:\program.exe.config)</param>
        /// <param name="key">Nome da configuração</param>
        /// <param name="value">Valor a ser salvo</param>
        /// <returns></returns>
        public static bool SetValue(string file, string key, string value)
        {
            var fileDocument = new XmlDocument();
            fileDocument.Load(file);
            var nodes = fileDocument.GetElementsByTagName(AddElementName);

            if (nodes.Count == 0)
            {
                return false;
            }

            for (var i = 0; i < nodes.Count; i++)
            {
                var node = nodes.Item(i);
                if (node == null || node.Attributes == null || node.Attributes.GetNamedItem(KeyPropertyName) == null)
                    continue;
                
                if (node.Attributes.GetNamedItem(KeyPropertyName).Value == key)
                {
                    node.Attributes.GetNamedItem(ValuePropertyName).Value = value;
                }
            }

            var writer = new XmlTextWriter(file, null) { Formatting = Formatting.Indented };
            fileDocument.WriteTo(writer);
            writer.Flush();
            writer.Close();
            return true;
        }
Exemple #6
0
        public override string ToString()
        {
            string doc;

            using (var sw = new StringWriter()) {
                using (var writer = new XmlTextWriter(sw)) {
                    writer.Formatting = Formatting.Indented;
                    //writer.WriteStartDocument();
                    writer.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
                    writer.WriteStartElement("D", "multistatus", "DAV:");
                    for (int i = 0; i < _nameSpaceList.Count; i++) {
                        string tag = string.Format("ns{0}", i);
                        writer.WriteAttributeString("xmlns", tag, null, _nameSpaceList[i]);
                    }

                    foreach (var oneResponse in _ar) {
                        oneResponse.Xml(writer);
                    }
                    writer.WriteEndElement();
                    //writer.WriteEndDocument();
                    writer.Flush();
                    writer.Close();
                    doc = sw.ToString();
                    writer.Flush();
                    writer.Close();
                }
                sw.Flush();
                sw.Close();
            }
            return doc;
        }
    internal void SaveBuildResultToFile(string preservationFile,
        BuildResult result, long hashCode) {

        _writer = new XmlTextWriter(preservationFile, Encoding.UTF8);

        try {
            _writer.Formatting = Formatting.Indented;
            _writer.Indentation = 4;
            _writer.WriteStartDocument();

            // <preserve assem="assemblyFile">
            _writer.WriteStartElement("preserve");

            // Save the type of BuildResult we're dealing with
            Debug.Assert(result.GetCode() != BuildResultTypeCode.Invalid); 
            SetAttribute("resultType", ((int)result.GetCode()).ToString(CultureInfo.InvariantCulture));

            // Save the virtual path for this BuildResult
            if (result.VirtualPath != null)
                SetAttribute("virtualPath", result.VirtualPath.VirtualPathString);

            // Get the hash code of the BuildResult
            long hash = result.ComputeHashCode(hashCode);

            // The hash should always be valid if we got here.
            Debug.Assert(hash != 0, "hash != 0"); 

            // Save it to the preservation file
            SetAttribute("hash", hash.ToString("x", CultureInfo.InvariantCulture));

            // Can be null if that's what the VirtualPathProvider returns
            string fileHash = result.VirtualPathDependenciesHash;
            if (fileHash != null)
                SetAttribute("filehash", fileHash);

            result.SetPreservedAttributes(this);

            SaveDependencies(result.VirtualPathDependencies);

            // </preserve>
            _writer.WriteEndElement();
            _writer.WriteEndDocument();

            _writer.Close();
        }
        catch {

            // If an exception occurs during the writing of the xml file, clean it up
            _writer.Close();
            File.Delete(preservationFile);

            throw;
        }
    }
Exemple #8
0
        private void btnSalvar_Click(object sender, EventArgs e)
        {
            XmlTextWriter myXmlTextWriter = new XmlTextWriter ("config.xml",System.Text.Encoding.UTF8);
            if (Verifica() != 0)
            {
                MessageBox.Show("Os campos com * precisam ser preenchidos.");
            }
            else
            {

                Conn.hostDB = textBox1.Text;
                Conn.Database = textBox2.Text;
                Conn.userDB = textBox3.Text;
                Conn.passwdDB = textBox4.Text;
                Conn.createStringConnection();

                try
                {

                    Conn.Conectar();

                    myXmlTextWriter.WriteStartElement("conectionstring");
                    myXmlTextWriter.WriteAttributeString("hostDB", textBox1.Text);
                    myXmlTextWriter.WriteAttributeString("database", textBox2.Text);
                    myXmlTextWriter.WriteAttributeString("userDB", textBox3.Text);
                    myXmlTextWriter.WriteAttributeString("passwordDB", textBox4.Text);
                    myXmlTextWriter.WriteEndElement();

                    //label6.Text = "Conectado";

                    Conn.ExecuteNonQueryFile("sql.sql");
                    myXmlTextWriter.Flush();
                    myXmlTextWriter.Close();
                    MessageBox.Show("Configuração Salva");
                    OK = true;
                    this.Close();

                }

                catch (Exception ex)
                {
                    MessageBox.Show("Não foi possível conectar. " + ex.Message);
                    myXmlTextWriter.Close();
                    File.Delete("config.xml");

                }

            }
        }
Exemple #9
0
 public static void CreateXml(string path)
 {
     XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8) {
         Formatting = Formatting.Indented
     };
     writer.WriteStartDocument();
     writer.WriteStartElement("root");
     for (int i = 0; i < 5; i++)
     {
         writer.WriteStartElement("Node");
         writer.WriteAttributeString("Text", "这是文章内容!~!!~~");
         writer.WriteAttributeString("ImageUrl", "");
         writer.WriteAttributeString("NavigateUrl", "Url..." + i.ToString());
         writer.WriteAttributeString("Expand", "true");
         for (int j = 0; j < 5; j++)
         {
             writer.WriteStartElement("Node");
             writer.WriteAttributeString("Text", "......名称");
             writer.WriteAttributeString("NavigateUrl", "Url..." + i.ToString());
             writer.WriteEndElement();
         }
         writer.WriteEndElement();
     }
     writer.WriteFullEndElement();
     writer.Close();
 }
Exemple #10
0
        public void RunXslt(String xsltFile, String xmlDataFile, String outputXml)
        {
            XPathDocument input = new XPathDocument(xmlDataFile);

            XslTransform myXslTrans = new XslTransform() ;
            XmlTextWriter output = null;
            try
            {
                myXslTrans.Load(xsltFile);

                output = new XmlTextWriter(outputXml, null);
                output.Formatting = Formatting.Indented;

                myXslTrans.Transform(input, null, output);

            }
            catch (Exception e)
            {
                String msg = e.Message;
                if (msg.IndexOf("InnerException") >0)
                {
                    msg = e.InnerException.Message;
                }

                MessageBox.Show("Error: " + msg + "\n" + e.StackTrace, "Xslt Error File: " + xsltFile, MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            finally
            {
                try { output.Close(); }
                catch (Exception) { }
            }
        }
Exemple #11
0
        /// <summary>
        /// Export a MacGui style plist preset.
        /// </summary>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="preset">
        /// The preset.
        /// </param>
        public static void Export(string path, Preset preset)
        {
            EncodeTask parsed = QueryParserUtility.Parse(preset.Query);
            XmlTextWriter xmlWriter = new XmlTextWriter(path, Encoding.UTF8) { Formatting = Formatting.Indented };

            // Header
            xmlWriter.WriteStartDocument();
            xmlWriter.WriteDocType("plist", "-//Apple//DTD PLIST 1.0//EN",
                                @"http://www.apple.com/DTDs/PropertyList-1.0.dtd", null);

            xmlWriter.WriteStartElement("plist");
            xmlWriter.WriteStartElement("array");

            // Add New Preset Here. Can write multiple presets here if required in future.
            WritePreset(xmlWriter, parsed, preset);

            // Footer
            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndElement();

            xmlWriter.WriteEndDocument();

            // Closeout
            xmlWriter.Close();
        }
        public void WritePictureXMLFile()
        {
            GlobalDataStore.Logger.Debug("Updating Pictures.xml ...");
            List <LabelX.Toolbox.LabelXItem> items        = new List <LabelX.Toolbox.LabelXItem>();
            DirectoryInfo PicturesRootFolderDirectoryInfo = new DirectoryInfo(PicturesRootFolder);

            LabelX.Toolbox.Toolbox.GetPicturesFromFolderTree(PicturesRootFolderDirectoryInfo.FullName, ref items);

            //items = alle ingelezen pictures. Nu gaan wegschrijven.
            System.Xml.XmlDocument doc  = new System.Xml.XmlDocument();
            System.Xml.XmlElement  root = doc.CreateElement("LabelXItems");

            foreach (LabelX.Toolbox.LabelXItem item in items)
            {
                System.Xml.XmlElement itemXML = doc.CreateElement("item");
                itemXML.SetAttribute("name", item.Name);
                itemXML.SetAttribute("hash", item.Hash);

                root.AppendChild(itemXML);
            }

            doc.AppendChild(root);

            MemoryStream ms = new MemoryStream();

            System.Xml.XmlTextWriter tw = new System.Xml.XmlTextWriter(ms, Encoding.UTF8);
            tw.Formatting = System.Xml.Formatting.Indented;
            doc.WriteContentTo(tw);
            doc.Save(PicturesRootFolder + "pictures.xml");


            tw.Close();
        }
Exemple #13
0
        /// <summary>
        /// Saves settings to an XML file
        /// </summary>
        /// <param name="file">The file to save to</param>
        internal static void SaveSettings(string file)
        {
            try
            {
                // Open writer
                System.Xml.XmlTextWriter xmlwriter = new System.Xml.XmlTextWriter(file, System.Text.Encoding.Default);
                xmlwriter.Formatting = System.Xml.Formatting.Indented;

                // Start document
                xmlwriter.WriteStartDocument();
                xmlwriter.WriteStartElement("KMLImporter");

                // ShowAllLabels
                xmlwriter.WriteStartElement("ShowAllLabels");
                xmlwriter.WriteString(ShowAllLabels.ToString(CultureInfo.InvariantCulture));
                xmlwriter.WriteEndElement();

                // End document
                xmlwriter.WriteEndElement();
                xmlwriter.WriteEndDocument();

                // Close writer
                xmlwriter.Flush();
                xmlwriter.Close();
            }
            catch (System.IO.IOException)
            { }
            catch (System.Xml.XmlException)
            { }
        }
Exemple #14
0
        public void createXML(string XmlFilePath, StringBuilder str)
        {
            //   XmlFilePath = this.XmlFilePath;
            try
            {
                if (!File.Exists(XmlFilePath))
                {
                    XmlTextWriter textWritter = new XmlTextWriter(XmlFilePath, Encoding.UTF8);

                    textWritter.WriteStartDocument();

                    textWritter.WriteStartElement("book");

                    textWritter.WriteEndElement();

                    textWritter.Close();
                   // Console.WriteLine("Xml have been created!");
                }
                else
                {
                    //Console.WriteLine("File haven't been created. Xml already exist!");

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            addData(XmlFilePath,str);
        }
        /// <summary>
        /// Export a MacGui style plist preset.
        /// </summary>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="preset">
        /// The preset.
        /// </param>
        /// <param name="build">
        /// The build.PictureModulusPictureModulus
        /// </param>
        public static void Export(string path, Preset preset, string build)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            EncodeTask parsed = new EncodeTask(preset.Task);
            using (XmlTextWriter xmlWriter = new XmlTextWriter(path, Encoding.UTF8) { Formatting = Formatting.Indented })
            {
                // Header
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteDocType(
                    "plist", "-//Apple//DTD PLIST 1.0//EN", @"http://www.apple.com/DTDs/PropertyList-1.0.dtd", null);

                xmlWriter.WriteStartElement("plist");
                xmlWriter.WriteStartElement("array");

                // Add New Preset Here. Can write multiple presets here if required in future.
                WritePreset(xmlWriter, parsed, preset, build);

                // Footer
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndElement();

                xmlWriter.WriteEndDocument();

                // Closeout
                xmlWriter.Close();
            }
        }
Exemple #16
0
        public bool GenerateReport(string fileName)
        {
            bool retCode = false;
            ResetReportViwer();

            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load(rptXslPath);

            if ( File.Exists(fileName) == true)
            {
                XPathDocument myXPathDoc = new XPathDocument(fileName);
                StringWriter sw = new StringWriter();
                XmlWriter xmlWriter = new XmlTextWriter(sw);

                // using makes sure that we flush the writer at the end
                xslt.Transform(myXPathDoc, null, xmlWriter);
                xmlWriter.Flush();
                xmlWriter.Close();

                string xml = sw.ToString();

                HtmlDocument htmlDoc = axBrowser.Document;
                htmlDoc.Write(xml);
                retCode = true;
            }
            else
            {

                retCode = false;
            }

            return retCode;
        }
        public override bool Execute()
        {
            try {
                var document = new XmlDocument();
                document.Load(this.XmlFileName);

                var navigator = document.CreateNavigator();
                var nsResolver = new XmlNamespaceManager(navigator.NameTable);

                if (!string.IsNullOrEmpty(this.Prefix) && !string.IsNullOrEmpty(this.Namespace)) {
                    nsResolver.AddNamespace(this.Prefix, this.Namespace);
                }

                var expr = XPathExpression.Compile(this.XPath, nsResolver);

                var iterator = navigator.Select(expr);
                while (iterator.MoveNext()) {
                    iterator.Current.DeleteSelf();
                }

                using (var writer = new XmlTextWriter(this.XmlFileName, Encoding.UTF8)) {
                    writer.Formatting = Formatting.Indented;
                    document.Save(writer);
                    writer.Close();
                }
            }
            catch (Exception exception) {
                base.Log.LogErrorFromException(exception);
                return false;
            }
            base.Log.LogMessage("Updated file '{0}'", new object[] { this.XmlFileName });
            return true;
        }
Exemple #18
0
 /// <summary>
 /// Utility function to save the documente in UTF8 and Indented
 /// </summary>
 /// <param name="document"></param>
 private static void SaveDocument(Xml.XmlDocument document, string outputFileName, System.Text.Encoding encode)
 {
     Xml.XmlTextWriter textWriter = new Xml.XmlTextWriter(outputFileName, encode);
     textWriter.Formatting = System.Xml.Formatting.Indented;
     document.Save(textWriter);
     textWriter.Close();
 }
Exemple #19
0
        /// <summary>
        /// Attempt to get the list of character types.
        /// </summary>
        public bool GetCharacterTypes()
        {
            omaeSoapClient objService = _objOmaeHelper.GetOmaeService();

            try
            {
                MemoryStream objStream = new MemoryStream();
                XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.UTF8);

                objService.GetCharacterTypes().WriteTo(objWriter);
                // Flush the output.
                objWriter.Flush();
                objStream.Flush();

                XmlDocument objXmlDocument = _objOmaeHelper.XmlDocumentFromStream(objStream);

                // Close everything now that we're done.
                objWriter.Close();
                objStream.Close();

                // Stuff all of the items into a ListItem List.
                foreach (XmlNode objNode in objXmlDocument.SelectNodes("/types/type"))
                {
                    ListItem objItem = new ListItem();
                    objItem.Value = objNode["id"].InnerText;
                    objItem.Name = objNode["name"].InnerText;
                    _lstCharacterTypes.Add(objItem);
                }

                // Add an item for Official NPCs.
                ListItem objNPC = new ListItem();
                objNPC.Value = "4";
                objNPC.Name = "Official NPC Packs";
                _lstCharacterTypes.Add(objNPC);

                // Add an item for Custom Data.
                ListItem objData = new ListItem();
                objData.Value = "data";
                objData.Name = "Data";
                _lstCharacterTypes.Add(objData);

                // Add an item for Character Sheets.
                ListItem objSheets = new ListItem();
                objSheets.Value = "sheets";
                objSheets.Name = "Character Sheets";
                _lstCharacterTypes.Add(objSheets);

                cboCharacterTypes.Items.Clear();
                cboCharacterTypes.DataSource = _lstCharacterTypes;
                cboCharacterTypes.ValueMember = "Value";
                cboCharacterTypes.DisplayMember = "Name";
            }
            catch (EndpointNotFoundException)
            {
                MessageBox.Show(NO_CONNECTION_MESSAGE, NO_CONNECTION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            objService.Close();

            return false;
        }
        // 'Este documento esta para la factura electronica,
        // 'Para la nota de credito es un documento similar pero cambia algunos nodos.
        // 'Lo vemos luego.

        // 'Segun la normativa, estos son los datos basicos que seguramente van a ocupar,
        // 'Es posible que algunos no los ocupen y requieran otros, es normal y los veremos conforme vayamos
        // 'desarrollando la factura. Cuando se envien los datos a Hacienda, ahi seguramente nos daremos cuenta en las pruebas

        public XmlDocument CreaXMLFacturaElectronica()
        {
            try
            {
                mXML = new System.IO.MemoryStream();

                System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(mXML, System.Text.Encoding.UTF8);

                XmlDocument docXML = new XmlDocument();

                GeneraXML(writer);

                mXML.Seek(0, System.IO.SeekOrigin.Begin);

                docXML.Load(mXML);

                writer.Close();

                // Retorna el documento xml y ahi se puede salvar docXML.Save
                return(docXML);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #21
0
        /// <summary>
        /// xml序列化成字符串
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>xml字符串</returns>
        public static string Serialize(object obj)
        {
            string        returnStr  = "";
            XmlSerializer serializer = GetSerializer(obj.GetType());
            MemoryStream  ms         = new MemoryStream();
            XmlTextWriter xtw        = null;
            StreamReader  sr         = null;

            try
            {
                xtw            = new System.Xml.XmlTextWriter(ms, Encoding.UTF8);
                xtw.Formatting = System.Xml.Formatting.Indented;
                serializer.Serialize(xtw, obj);
                ms.Seek(0, SeekOrigin.Begin);
                sr        = new StreamReader(ms);
                returnStr = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (xtw != null)
                {
                    xtw.Close();
                }
                if (sr != null)
                {
                    sr.Close();
                }
                ms.Close();
            }
            return(returnStr);
        }
Exemple #22
0
 public static void WriteXmlInFile(string layer, string msg)
 {
     try
     {
         //XmlDataDocument sourceXML = new XmlDataDocument();
         string xmlFile = HttpContext.Current.Server.MapPath("/log/Exception.xml");
         //create a XML file is not exist
         System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(xmlFile, null);
         //starts a new document
         writer.WriteStartDocument();
         //write comments
         writer.WriteComment("Commentss: XmlWriter Test Program");
         writer.Formatting = Formatting.Indented;
         writer.WriteStartElement("MessageList");
         writer.WriteStartElement("Exception");
         writer.WriteAttributeString("Layer", layer);
         //write some simple elements
         writer.WriteElementString("Message", msg);
         writer.WriteEndElement();
         writer.WriteEndElement();
         writer.WriteEndElement();
         writer.Close();
     }
     catch (Exception ex) { throw ex; }
 }
 /// <summary>
 /// Writes a GML feature into a generic <c>Stream</c>, such a <c>FileStream</c> or other streams.
 /// </summary>
 /// <param name="geometry"></param>
 /// <param name="stream"></param>
 public virtual void Write(IGeometry geometry, Stream stream)
 {
     XmlTextWriter writer = new XmlTextWriter(stream, null);
     writer.Formatting = Formatting.Indented;
     Write(geometry, writer);                                  
     writer.Close();
 }
Exemple #24
0
        public void CreateXml()
        {
            if ( ( m_SeasonList.Count > 0 ) )
            {
                const string fileName = "NFL.xml";
                XmlTextWriter writer = new
                    XmlTextWriter(string.Format("{0}{1}", Utility.OutputDirectory() + "xml\\", fileName), null);
                writer.Formatting = Formatting.Indented;

                writer.WriteStartDocument();
                writer.WriteComment( "Comments: NFL Season List" );
                writer.WriteStartElement( "nfl" );
                writer.WriteStartElement("season-list");

                foreach ( NflSeason s in m_SeasonList )
                {
                    WriteSeasonNode( writer, s );
                }
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
                RosterLib.Utility.Announce( fileName + " created" );
            }
        }
Exemple #25
0
		public void TransformingTest() 
		{
			XslTransform tx = new XslTransform();
			tx.Load(new XmlTextReader(
				Globals.GetResource(this.GetType().Namespace + ".test.xsl")));

			XmlReader xtr = new XmlTransformingReader(
				new XmlTextReader(
				Globals.GetResource(this.GetType().Namespace + ".input.xml")),
				tx);

			//That's it, now let's dump out XmlTransformingReader to see what it returns
			StringWriter sw = new StringWriter();
			XmlTextWriter w = new XmlTextWriter(sw);
			w.Formatting = Formatting.Indented;
			w.WriteNode(xtr, false);
			xtr.Close();
			w.Close();

			Assert.AreEqual(sw.ToString(), @"<parts>
  <item SKU=""1001"" name=""Lawnmower"" price=""299.99"" />
  <item SKU=""1001"" name=""Electric drill"" price=""99.99"" />
  <item SKU=""1001"" name=""Hairdrier"" price=""39.99"" />
</parts>");
		}
        public bool create(string xmlRoot, string fileName)
        {
            //create the root elements of the xml document if the dont alreasy exist
            try
            {
                if (!System.IO.File.Exists(fileName))
                {
                    XmlTextWriter xtw;
                    xtw = new XmlTextWriter(fileName, Encoding.UTF8);
                    xtw.WriteStartDocument();
                    xtw.WriteStartElement(xmlRoot);
                    xtw.WriteEndElement();
                    xtw.Close();

                    //if file exists return true
                    return true;
                }
                else { return false; }
            }
            catch (Exception err)
            {
                debugTerminal terminal = new debugTerminal();
                terminal.output(err.ToString());
                return false;
            }
        }
Exemple #27
0
        public void Create( string path )
        {
            XmlTextWriter xml;

            if( path == "" )
            {
                return;
            }

            m_fileName = path;

            if( File.Exists( m_fileName ) == false )
            {
                xml = new XmlTextWriter( m_fileName, System.Text.Encoding.UTF8 );

                xml.Formatting = System.Xml.Formatting.Indented;

                xml.WriteStartDocument();

                xml.WriteStartElement( "mdna" );
                xml.WriteEndElement();

                xml.WriteEndDocument();

                xml.Close();
            }
        }
Exemple #28
0
        public static String XMLPrint(this String xml){
            if (string.IsNullOrEmpty(xml))
                return xml;
            String result = "";

            var mStream = new MemoryStream();
            var writer = new XmlTextWriter(mStream, Encoding.Unicode);
            var document = new XmlDocument();

            try{
                document.LoadXml(xml);
                writer.Formatting = Formatting.Indented;
                document.WriteContentTo(writer);
                writer.Flush();
                mStream.Flush();
                mStream.Position = 0;
                var sReader = new StreamReader(mStream);
                String formattedXML = sReader.ReadToEnd();

                result = formattedXML;
            }
            catch (XmlException){
            }

            mStream.Close();
            writer.Close();

            return result;
        }
Exemple #29
0
        private void SavePluginListToXMLFile(string filename)
        {
            try
            {
                Console.WriteLine("Saving plugins entries to " + (string)MediaNET.Config["Interface/plugins.xml"]);
                XmlTextWriter writer = new System.Xml.XmlTextWriter((string)MediaNET.Config["Interface/plugins.xml"], null);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                writer.WriteStartElement("plugins");

                TreeModel model = pluginList.Model;
                TreeIter  iter;
                if (pluginStore.GetIterFirst(out iter))
                {
                    do
                    {
                        writer.WriteStartElement("plugin");
                        writer.WriteElementString("extension", (string)model.GetValue(iter, 0));
                        // Second field ignored -> found using reflection
                        writer.WriteElementString("player", (string)model.GetValue(iter, 2));
                        writer.WriteElementString("path", (string)model.GetValue(iter, 3));
                        writer.WriteEndElement();
                    }while (pluginStore.IterNext(ref iter));
                }
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
            catch (Exception e)
            {
                throw new Exception("Save settings failed: " + e.Message);
            }
        }
Exemple #30
0
        /// <summary>
        /// Serializes an object into an Xml Document
        /// </summary>
        /// <param name="o">The object to serialize</param>
        /// <returns>An Xml Document consisting of said object's data</returns>
        public static XmlDocument Serialize(object o)
        {
            XmlSerializer s = new XmlSerializer(o.GetType());

            MemoryStream ms = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(ms, new UTF8Encoding());
            writer.Formatting = Formatting.Indented;
            writer.IndentChar = ' ';
            writer.Indentation = 5;
            Exception caught = null;

            try
            {
                s.Serialize(writer, o);
                XmlDocument xml = new XmlDocument();
                string xmlString = ASCIIEncoding.UTF8.GetString(ms.ToArray());
                xml.LoadXml(xmlString);
                return xml;
            }
            catch (Exception e)
            {
                caught = e;
            }
            finally
            {
                writer.Close();
                ms.Close();

                if (caught != null)
                    throw caught;
            }
            return null;
        }
Exemple #31
0
        /// <summary>
        /// Sends the specified API request.
        /// </summary>
        /// <param name="apiRequest">The API request.</param>
        /// <returns></returns>
        public ANetApiResponse Send(ANetApiRequest apiRequest) {

            //Authenticate it
            AuthenticateRequest(apiRequest);

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_serviceUrl);
            webRequest.Method = "POST";
            webRequest.ContentType = "text/xml";
            webRequest.KeepAlive = true;

            // Serialize the request
            var type = apiRequest.GetType();
            var serializer = new XmlSerializer(type);
            XmlWriter writer = new XmlTextWriter(webRequest.GetRequestStream(), Encoding.UTF8);
            serializer.Serialize(writer, apiRequest);
            writer.Close();


            // Get the response
            WebResponse webResponse = webRequest.GetResponse();

            // Load the response from the API server into an XmlDocument.
            _xmlDoc = new XmlDocument();
            _xmlDoc.Load(XmlReader.Create(webResponse.GetResponseStream()));


            var response = DecideResponse(_xmlDoc);
            CheckForErrors(response);
            return response;
        }
        public override void Save(object value, string sectionName, string fileName)
        {
            XmlNode xmlNode = this.Serialize(value);
            XmlDocument document = new XmlDocument();
            document.AppendChild(document.ImportNode(xmlNode,true));

            // Encrypt xml
            EncryptXml enc = new EncryptXml(document);
            enc.AddKeyNameMapping("db", ReadServerEncryptionKey());

            XmlNodeList list = document.SelectNodes("//Password");

            foreach ( XmlNode n in list )
            {
                XmlElement el = (XmlElement)n;
                EncryptedData data = enc.Encrypt(el, "db");
                enc.ReplaceElement(el, data);
            }

            XmlTextWriter writer = new XmlTextWriter(fileName, null);
            writer.Formatting = Formatting.Indented;
            document.WriteTo(writer);
            writer.Flush();
            writer.Close();
        }
Exemple #33
0
        public static void WriteData()
        {
            if (!Directory.Exists(SR_Main.SavePath))
                Directory.CreateDirectory(SR_Main.SavePath);

            string filePath = Path.Combine(SR_Main.SavePath, SR_Main.FileName);

            using (StreamWriter op = new StreamWriter(filePath))
            {
                XmlTextWriter xml = new XmlTextWriter(op);

                xml.Formatting = Formatting.Indented;
                xml.IndentChar = '\t';
                xml.Indentation = 1;

                xml.WriteStartDocument(true);

                xml.WriteStartElement("StaffRunebook");

                xml.WriteAttributeString("Version", SR_Main.Version.ToString());

                for (int i = 0; i < SR_Main.Count; i++)
                    WriteAccountNode(SR_Main.Info[i], xml);

                xml.WriteEndElement();

                xml.Close();
            }
        }
Exemple #34
0
        public void SaveAndReadTest()
        {
            StringBuilder sb = new StringBuilder();
            XmlWriter writer = new XmlTextWriter(new StringWriter(sb));
            uint row = (uint)rng.Next();
            cell.Row = row;
            uint column = (uint)rng.Next();
            cell.Column = column;
            cell.InputValue = "input string";
            cell.NumericValue = "numeric value";
            cell.Value = "display value";
            cell.Save(writer);
            writer.Close();

            XmlDocument document = new XmlDocument();
            document.LoadXml(sb.ToString());

            ExtensionElementEventArgs e = new ExtensionElementEventArgs();
            e.ExtensionElement = document.FirstChild;

            entry.Parse(e, new AtomFeedParser());

            Assert.AreEqual(row, entry.Cell.Row, "Rows should be equal");
            Assert.AreEqual(column, entry.Cell.Column, "Columns should be equal");
            Assert.AreEqual("input string", entry.Cell.InputValue, "Input value should be equal");
            Assert.AreEqual("numeric value", entry.Cell.NumericValue, "Numeric value should be equal");
            Assert.AreEqual("display value", entry.Cell.Value, "Cell value should be equal");
        }
Exemple #35
0
        public void escribirXMl(string nombreF, List<Contacto> contactos)
        {
            FileStream fichero = new FileStream(nombreF, FileMode.Create, FileAccess.Write);
            //crearXml(nombreF);
            XmlTextWriter escritorXml = new XmlTextWriter(fichero, Encoding.Default);
            escritorXml.Formatting = Formatting.Indented;
            escritorXml.WriteStartDocument();
            escritorXml.WriteStartElement("Agenda");
            foreach (Contacto c in contactos)
            {
                escritorXml.WriteStartElement("Contacto");
                escritorXml.WriteStartElement("nombre", c.nombre);
                escritorXml.WriteEndElement();
                escritorXml.WriteStartElement("apellido", c.apellido);
                escritorXml.WriteEndElement();
                escritorXml.WriteStartElement("direccion", c.direccion);
                escritorXml.WriteEndElement();
                escritorXml.WriteStartElement("telefonos");
                escritorXml.WriteStartElement("telcasa", c.tlfCasa);
                escritorXml.WriteEndElement();
                escritorXml.WriteStartElement("telmovil", c.tlfMovil);
                escritorXml.WriteEndElement();
                escritorXml.WriteStartElement("teltrabajo", c.tlfTrabajo);
                escritorXml.WriteEndElement();
                escritorXml.WriteEndElement();
                escritorXml.WriteEndElement();
            }

            escritorXml.WriteEndElement();
            escritorXml.WriteEndDocument();
            escritorXml.Close();
        }
        /// <summary>
        ///   Converts the memory hash table to XML
        /// </summary>
        public void Dump2Xml()
        {
            if ( ( TheHT.Count > 0 ) && IsDirty )
            {
                XmlTextWriter writer = new
                          XmlTextWriter( string.Format( "{0}", Filename ), null );

                writer.WriteStartDocument();
                writer.WriteComment( "Comments: " + Name );
                writer.WriteStartElement( "media-list" );

                IDictionaryEnumerator myEnumerator = TheHT.GetEnumerator();
                while ( myEnumerator.MoveNext() )
                {
                    MediaItem m = (MediaItem) myEnumerator.Value;
                    WriteMediaNode( writer, m );
                }
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
                Utility.Announce( string.Format( "{0} created.",  Filename ) );
            }
            else
                Utility.Announce( string.Format( "No changes to {0}.", Filename ) );
        }
Exemple #37
0
        /// <summary>
        /// xml序列化成字符串
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>xml字符串</returns>
        public static string Serialize(object obj)
        {
            string returnStr = "";

            XmlSerializer serializer = new XmlSerializer(obj.GetType());

            MemoryStream ms = new MemoryStream();
            XmlTextWriter xtw = null;
            StreamReader sr = null;
            try
            {
                xtw = new System.Xml.XmlTextWriter(ms, Encoding.UTF8);
                xtw.Formatting = System.Xml.Formatting.Indented;
                serializer.Serialize(xtw, obj);
                ms.Seek(0, SeekOrigin.Begin);
                sr = new StreamReader(ms);
                returnStr = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (xtw != null)
                    xtw.Close();
                if (sr != null)
                    sr.Close();
                ms.Close();
            }
            return returnStr;
        }
        /// <summary>
        /// Saves the application settings to the specified file.
        /// </summary>
        /// <param name="filePath">
        /// The path of the file to which settings are to be saved.
        /// </param>
        private void Save(string filePath)
        {
            try
            {
                // Serialize the current object to a memory stream.
                System.IO.MemoryStream   plaintextStream = new System.IO.MemoryStream();
                System.Xml.XmlTextWriter plaintextWriter = new System.Xml.XmlTextWriter(plaintextStream, System.Text.Encoding.Unicode);
                XmlSerializer            serializer      = EncryptedSettings.Serializer;
                lock (serializer)
                {
                    plaintextWriter.Indentation = 0;
                    plaintextWriter.Formatting  = System.Xml.Formatting.None;
                    serializer.Serialize(plaintextWriter, this);
                }

                // Convert the plaintext memory stream to an array of bytes.
                byte[] plaintextBytes = plaintextStream.ToArray();

                // Encrypt the plaintext byte array.
                byte[] ciphertextBytes = ProtectedData.Protect(plaintextBytes, null, DataProtectionScope.LocalMachine);

                plaintextWriter.Close();
                plaintextWriter.Dispose();

                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath));

                // Write the encrypted byte array to the file.
                System.IO.FileStream ciphertextStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                ciphertextStream.Write(ciphertextBytes, 0, ciphertextBytes.Length);
                ciphertextStream.Close();
            }
            catch (System.InvalidOperationException)
            {
                throw;
            }

            /*
             * // This is the unencrypted version.
             * try
             * {
             *  System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath));
             *  System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(filePath, System.Text.Encoding.Unicode);
             *  XmlSerializer serializer = EncryptedSettings.Serializer;
             *  lock (serializer)
             *  {
             *      writer.Indentation = 1;
             *      writer.IndentChar = '\t';
             *      writer.Formatting = System.Xml.Formatting.Indented;
             *      serializer.Serialize(writer, this);
             *  }
             *  writer.Close();
             * }
             * catch (System.InvalidOperationException)
             * {
             *  throw;
             * }
             */
        }
Exemple #39
0
        private void SaveSetting()
        {
            //throw new System.NotImplementedException();

            #region zhucebiao
            //RegistryKey softwareKey = Registry.LocalMachine.OpenSubKey("SoftWare", true);
            //RegistryKey SQKey = softwareKey.CreateSubKey("SQPress");
            //RegistryKey selfWindowsKey = SQKey.CreateSubKey("selfWindowsKey");
            //selfWindowsKey.SetValue("BackColor", (object)BackColor.ToKnownColor());
            //selfWindowsKey.SetValue("Red", (object)(int)BackColor.R);
            //selfWindowsKey.SetValue("Green", (object)(int)BackColor.G);
            //selfWindowsKey.SetValue("Blue", (object)(int)BackColor.B);
            //selfWindowsKey.SetValue("Width", (object)Width);
            //selfWindowsKey.SetValue("Height", (object)Height);
            //selfWindowsKey.SetValue("X", (object)DesktopLocation.X);
            //selfWindowsKey.SetValue("Y", (object)DesktopLocation.Y);
            //selfWindowsKey.SetValue("WindowState", (object)WindowState.ToString());

            //softwareKey.Close();
            //SQKey.Close();
            //selfWindowsKey.Close();
            #endregion

            #region ISO
            IsolatedStorageFile iso         = IsolatedStorageFile.GetUserStoreForDomain();
            var isoStream                   = new IsolatedStorageFileStream("SelfPlace.xml", FileMode.Create, FileAccess.ReadWrite);
            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(isoStream, Encoding.Default);
            writer.Formatting = System.Xml.Formatting.Indented;


            writer.WriteStartDocument();
            writer.WriteStartElement("Settings");

            writer.WriteStartElement("Width");
            writer.WriteValue(this.Width);
            writer.WriteEndElement();

            writer.WriteStartElement("Height");
            writer.WriteValue(this.Height);
            writer.WriteEndElement();

            writer.WriteStartElement("X");
            writer.WriteValue(this.DesktopLocation.X);
            writer.WriteEndElement();

            writer.WriteStartElement("Y");
            writer.WriteValue(this.DesktopLocation.Y);
            writer.WriteEndElement();

            writer.WriteEndElement();

            writer.Flush();
            writer.Close();

            isoStream.Close();
            iso.Close();
            #endregion
        }
        public void SimpleSVGWriterConstructorTest()
        {
            string filename = IsotopeTestCommon.Helper.GetTestMethodOutputFilename("out1.svg");
            var    xw       = new System.Xml.XmlTextWriter(filename, System.Text.Encoding.UTF8);

            xw.Formatting = System.Xml.Formatting.Indented;

            var sw = new Isotope.Formats.SVG.SimpleSVGWriter(xw);

            sw.StartSVG(800, 800);

            sw.StartDefs();
            sw.StartFilter("gb1");
            sw.FilterGaussianBlur(3);
            sw.EndFilter();
            sw.EndDefs();

            var fmt1 = new Formatting();

            fmt1.Style = "fill:red;stroke:black;stroke-width:5;opacity:0.5";

            sw.Rect(0, 0, 100, 100, fmt1);
            sw.Rect(50, 50, 100, 100, fmt1);

            var fmt2 = new Formatting();

            fmt2.Fill        = "blue";
            fmt2.StrokeWidth = 3;
            fmt2.Stroke      = "black";
            fmt2.Opacity     = 0.3;

            sw.Circle(50, 50, 35, fmt2);
            sw.Ellipse(200, 100, 50, 20, fmt2);
            sw.Line(10, 10, 500, 100, fmt2);

            fmt2.Style = "filter:url(#gb1)";
            sw.Polygon(new int[] { 220, 100, 300, 210, 170, 250 }, fmt2);

            var fmt3 = new Formatting();

            fmt3.Fill        = "none";
            fmt3.StrokeWidth = 2;
            fmt3.Stroke      = "black";

            sw.Polyline(new int[] { 0, 0, 0, 20, 20, 20, 20, 40, 40, 40, 40, 60 }, fmt3);


            var fmt4 = new Formatting();

            fmt4.FontFamily = "Segoe UI";
            fmt4.FontSize   = 30;
            sw.Text(300, 100, "Hello World", fmt4);
            sw.EndSVG();


            xw.Close();
        }
Exemple #41
0
        /// <summary>
        /// Convierte un objeto en un string
        /// </summary>
        /// <param name="obj">el objeto a convertir</param>
        /// <returns>el string que representa al objeto</returns>
        public string serialize(Object obj)
        {
            StringWriter  sw     = new StringWriter();
            XmlTextWriter writer = new System.Xml.XmlTextWriter(sw);

            serializer.Serialize(writer, obj);
            writer.Flush();
            writer.Close();
            return(sw.ToString());
        }
Exemple #42
0
        private object GenerateXmlFromObject(string propName, object value)
        {
            object result = null;

            if (value is Type)
            {
                result = GenerateXmlFromTypeCore((Type)value);
            }

            //********************************
            if (value.GetType().ToString().EndsWith("[]"))
            {
                System.IO.MemoryStream   mem    = new MemoryStream();
                System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(mem, Encoding.UTF8);
                try
                {
                    System.Xml.Serialization.XmlSerializer serial =
                        new System.Xml.Serialization.XmlSerializer(value.GetType());
                    serial.Serialize(writer, value);
                    writer.Close();
                    result = Encoding.UTF8.GetString(mem.ToArray());
                    mem.Dispose();
                }
                catch (Exception)
                {
                }
                finally
                {
                    writer.Close();
                    mem.Dispose();
                }
            }
            //***************************************


            if (result == null)
            {
                result = value.ToString();
            }

            return(new XElement(propName, result));
        }
Exemple #43
0
        private void saveData()
        {
            dictionaryDataSet.AcceptChanges();

            // Write the XML schema and data to file with FileStream.
            System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(m_filename, System.Text.Encoding.Unicode);
            xmlWriter.Formatting  = Formatting.Indented;
            xmlWriter.Indentation = 4;
            dictionaryDataSet.WriteXml(xmlWriter);
            xmlWriter.Close();
        }
Exemple #44
0
        protected override void OnClosed(EventArgs e)
        {
            // write settings to file
            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(settingsPath, null)
            {
                Indentation = 1,
                IndentChar  = '\t',
                Formatting  = System.Xml.Formatting.Indented
            };

            writer.WriteStartElement("Settings");

            writer.WriteStartElement("Keys");

            writer.WriteStartElement("Up");
            writer.WriteValue(GameInputKeys.Up.ToString());
            writer.WriteEndElement();

            writer.WriteStartElement("Down");
            writer.WriteValue(GameInputKeys.Down.ToString());
            writer.WriteEndElement();

            writer.WriteStartElement("Left");
            writer.WriteValue(GameInputKeys.Left.ToString());
            writer.WriteEndElement();

            writer.WriteStartElement("Right");
            writer.WriteValue(GameInputKeys.Right.ToString());
            writer.WriteEndElement();

            writer.WriteStartElement("Jump");
            writer.WriteValue(GameInputKeys.Jump.ToString());
            writer.WriteEndElement();

            writer.WriteStartElement("Shoot");
            writer.WriteValue(GameInputKeys.Shoot.ToString());
            writer.WriteEndElement();

            writer.WriteStartElement("Start");
            writer.WriteValue(GameInputKeys.Start.ToString());
            writer.WriteEndElement();

            writer.WriteStartElement("Select");
            writer.WriteValue(GameInputKeys.Select.ToString());
            writer.WriteEndElement();

            writer.WriteEndElement();

            writer.WriteEndElement();
            writer.Close();
            base.OnClosed(e);
        }
Exemple #45
0
        public static void ModifyProjectFile(string filename)
        {
            if (!filename.ToLower().EndsWith("proj"))
            {
                throw new System.ArgumentException("Internal Error: ModifyProjectFile called with a file that is not a project");
            }

            Console.WriteLine("Modifying Project : {0}", filename);

            // Load the Project file
            XDocument doc      = null;
            Encoding  encoding = new UTF8Encoding(false);

            using (StreamReader reader = new StreamReader(filename, encoding))
            {
                doc      = System.Xml.Linq.XDocument.Load(reader);
                encoding = reader.CurrentEncoding;
            }

            // Modify the Source Control Elements
            RemoveSCCElementsAttributes(doc.Root);

            // Remove the read-only flag
            var original_attr = System.IO.File.GetAttributes(filename);

            System.IO.File.SetAttributes(filename, System.IO.FileAttributes.Normal);

            //if the original document doesn't include the encoding attribute
            //in the declaration then do not write it to the outpu file.
            if (String.IsNullOrEmpty(doc.Declaration.Encoding))
            {
                encoding = null;
            }

            //else if its not utf (i.e. utf-8, utf-16, utf32) format which use a BOM
            //then use the encoding identified in the XML file.
            else if (!doc.Declaration.Encoding.StartsWith("utf", StringComparison.OrdinalIgnoreCase))
            {
                encoding = Encoding.GetEncoding(doc.Declaration.Encoding);
            }

            // Write out the XML
            using (var writer = new System.Xml.XmlTextWriter(filename, encoding))
            {
                writer.Formatting = System.Xml.Formatting.Indented;
                doc.Save(writer);
                writer.Close();
            }

            // Restore the original file attributes
            System.IO.File.SetAttributes(filename, original_attr);
        }
Exemple #46
0
        /// <summary>
        /// 将对象序列化成xml字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string ToXmlStr <T>(this T t)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            MemoryStream  mem        = new MemoryStream();

            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(mem, Encoding.UTF8);
            XmlSerializerNamespaces  ns     = new XmlSerializerNamespaces();

            ns.Add("", "");
            serializer.Serialize(writer, t, ns);
            writer.Close();
            return(Encoding.UTF8.GetString(mem.ToArray(), 0, mem.ToArray().Length));
        }
Exemple #47
0
        public void AddAccount(Account account)
        {
            _accounts.Add(account);
            XElement element = new XElement("AccountType",
                                            new XAttribute("name", account.AccountName));

            _accountFile.Element("account").Element("accounts").Add(element);
            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(_fileName, null);
            writer.Formatting = System.Xml.Formatting.Indented;
            _accountFile.WriteTo(writer);
            _reloadAccounts = true;
            writer.Close();
        }
Exemple #48
0
        public static string GetChunkXml(Chunk chunk)
        {
            System.IO.StringWriter stringWriter = new
                                                  System.IO.StringWriter();
            Xml.XmlTextWriter writer = new Xml.XmlTextWriter(stringWriter);
            writer.Formatting = Xml.Formatting.Indented;

            WriteStep(writer, chunk);

            string content = stringWriter.ToString();

            writer.Close();
            return(content);
        }
Exemple #49
0
        public void AddBudget(Budget b)
        {
            _budgets.Add(b);
            XElement element = new XElement("budget",
                                            new XAttribute("name", b.BudgetName),
                                            new XAttribute("amount", b.Amount),
                                            new XAttribute("period", b.BudgetPeriod));

            _accountFile.Element("account").Element("budgets").Add(element);
            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(_fileName, null);
            writer.Formatting = System.Xml.Formatting.Indented;
            _accountFile.WriteTo(writer);
            _reloadBudgets = true;
            writer.Close();
        }
        private static string XmlToString(XmlDocument sLogData)
        {
            StringBuilder            strBuilder = new StringBuilder();
            StringWriterWithEncoding strWriter  = new StringWriterWithEncoding(strBuilder, System.Text.Encoding.UTF8);

            System.Xml.XmlTextWriter objXMLWriter = new System.Xml.XmlTextWriter(strWriter);
            objXMLWriter.Formatting  = Formatting.Indented;
            objXMLWriter.IndentChar  = (char)9;
            objXMLWriter.Indentation = 1;
            sLogData.Save(objXMLWriter);
            objXMLWriter.Flush();
            objXMLWriter.Close();
            objXMLWriter = null;
            return(strBuilder.ToString());
        }
Exemple #51
0
        /// <summary>
        /// 生成XML
        /// </summary>
        /// <param name="root">根结点</param>
        /// <returns></returns>
        public static String ToXml(XmlTreeNode root, Encoding encoding)
        {
            MemoryStream ms = new MemoryStream();
            XmlWriter    xw = new System.Xml.XmlTextWriter(ms, encoding);

            xw.WriteStartDocument();
            _WriteTreeNode(root, xw);
            xw.WriteEndDocument();

            xw.Flush();
            xw.Close();

            var xml = encoding.GetString(ms.ToArray());

            return(xml);
        }
Exemple #52
0
        public override void Write(System.IO.Stream stream)
        {
            if (this.RootChunk != null)
            {
                Xml.XmlTextWriter writer = new Xml.XmlTextWriter(stream, Encoding.UTF8);
                writer.Formatting = Xml.Formatting.Indented;

                writer.WriteStartDocument();

                WriteStep(writer, this.RootChunk);

                writer.WriteEndDocument();

                writer.Close();
            }
        }
Exemple #53
0
        public void WriteValue(string strSection, string strKey, string strValue)
        {
            //XmlNodeList mNode = mXml.GetElementsByTagName(strSection);
            XmlTextWriter mXmlWrite = new System.Xml.XmlTextWriter(this.strPathOfXml, System.Text.UTF8Encoding.UTF8);

            mXmlWrite.Formatting = Formatting.Indented;
            mXmlWrite.WriteStartDocument();
            mXmlWrite.WriteStartElement("property");
            mXmlWrite.WriteStartElement(strSection);
            mXmlWrite.WriteElementString(strKey, strValue);
            mXmlWrite.WriteEndElement();
            mXmlWrite.WriteEndElement();
            mXmlWrite.WriteEndDocument();
            mXmlWrite.Flush();
            mXmlWrite.Close();
        }
Exemple #54
0
        static int vipID; // = 0;

        static void SerializeVisual(Visual visual, double width, double height, String filename)
        {
            FileStream    stream = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite);
            XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8);

            writer.Formatting  = System.Xml.Formatting.Indented;
            writer.Indentation = 4;
            writer.WriteStartElement("FixedDocument");
            writer.WriteAttributeString("xmlns", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
            writer.WriteAttributeString("xmlns:x", "http://schemas.microsoft.com/winfx/2006/xaml");

            writer.WriteStartElement("PageContent");
            writer.WriteStartElement("FixedPage");
            writer.WriteAttributeString("Width", width.ToString(CultureInfo.InvariantCulture));
            writer.WriteAttributeString("Height", height.ToString(CultureInfo.InvariantCulture));
            writer.WriteAttributeString("Background", "White");
            writer.WriteStartElement("Canvas");

            System.IO.StringWriter resString = new StringWriter(CultureInfo.InvariantCulture);

            System.Xml.XmlTextWriter resWriter = new System.Xml.XmlTextWriter(resString);
            resWriter.Formatting  = System.Xml.Formatting.Indented;
            resWriter.Indentation = 4;

            System.IO.StringWriter bodyString = new StringWriter(CultureInfo.InvariantCulture);

            System.Xml.XmlTextWriter bodyWriter = new System.Xml.XmlTextWriter(bodyString);
            bodyWriter.Formatting  = System.Xml.Formatting.Indented;
            bodyWriter.Indentation = 4;

            VisualTreeFlattener.SaveAsXml(visual, resWriter, bodyWriter, filename);

            resWriter.Close();
            bodyWriter.Close();

            writer.Flush();
            writer.WriteRaw(resString.ToString());
            writer.WriteRaw(bodyString.ToString());

            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndElement();

            writer.WriteEndElement(); // FixedDocument
            writer.Close();
            stream.Close();
        }
Exemple #55
0
 public static void CreatXml(string XmlFileName)
 {
     try
     {
         System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(XmlFileName, System.Text.Encoding.GetEncoding("utf-8"));
         writer.Formatting = System.Xml.Formatting.Indented;
         writer.WriteRaw("<System Parameter Save>");
         writer.WriteStartElement("Config");
         //writer.WriteEndElement()
         writer.WriteFullEndElement();
         writer.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
     }
 }
Exemple #56
0
        private void WriteXmlToFile(DataSet thisDataSet, string _filename)
        {
            if (thisDataSet == null)
            {
                return;
            }
            string       filename = _filename;
            StreamWriter gc       = new StreamWriter(_filename, true, Encoding.Default);

            gc.WriteLine("<?xml version=\"1.0\" encoding=\"gb2312\" standalone=\"no\"?>");
            gc.Flush();
            gc.Close();
            System.IO.FileStream     stream    = new System.IO.FileStream(filename, System.IO.FileMode.Append);
            System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.Default);
            thisDataSet.WriteXml(xmlWriter);//XmlWriteMode.WriteSchema
            xmlWriter.Close();
        }
        private string Pretty(string Message)
        {
            System.Xml.XmlDocument   Doc       = new System.Xml.XmlDocument();
            System.IO.MemoryStream   MemStr    = new System.IO.MemoryStream();
            System.Xml.XmlTextWriter XmlWriter = new System.Xml.XmlTextWriter(MemStr, System.Text.Encoding.Unicode);
            XmlWriter.Formatting = System.Xml.Formatting.Indented;
            Doc.LoadXml(Message);
            Doc.WriteContentTo(XmlWriter);
            XmlWriter.Flush();
            MemStr.Flush();
            MemStr.Position = 0;
            string Ret = new System.IO.StreamReader(MemStr).ReadToEnd();

            MemStr.Close();
            XmlWriter.Close();
            return(Ret);
        }
        public static string GenerateEntityXml(string outputPath, EntityInfo entity)
        {
            string ret = String.Empty;

            if (entity == null || !Directory.Exists(outputPath))
            {
                return(ret);
            }

            Log4Helper.Write("GenerateEntityXml", String.Format("Process of entity {0} starts at {1}.", entity.ClassName, System.DateTime.Now.ToString("s")), LogSeverity.Info);

            using (System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(System.IO.Path.Combine(outputPath, String.Concat(entity.ClassName, ".xml")), System.Text.Encoding.UTF8))
            {
                xtw.Formatting = System.Xml.Formatting.Indented;
                xtw.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");

                //generate entity calss
                xtw.WriteStartElement("entity");
                xtw.WriteAttributeString("namespace", entity.NameSpace);
                xtw.WriteAttributeString("name", entity.ClassName);

                #region columns/properties
                //generate property node
                xtw.WriteStartElement("fields");
                foreach (FieldInfo field in entity.Fileds)
                {
                    xtw.WriteStartElement("property");
                    xtw.WriteAttributeString("type", field.Type);
                    xtw.WriteAttributeString("name", field.Name);
                    xtw.WriteAttributeString("privateFieldName", field.PrivateFieldName);
                    xtw.WriteAttributeString("paramName", field.ParamName);
                    xtw.WriteAttributeString("propetyName", field.PropertyName);
                    xtw.WriteAttributeString("csharpType", field.CSharpType);
                    xtw.WriteEndElement();
                }
                xtw.WriteEndElement();
                #endregion
                ret = xtw.ToString();
                xtw.WriteEndElement();
                xtw.Flush();
                xtw.Close();
            }

            Log4Helper.Write("GenerateEntityXmlFromTable", String.Format("Process of table {0} ends at {1}.", entity.ClassName, System.DateTime.Now.ToString("s")), LogSeverity.Info);
            return(ret);
        }
Exemple #59
0
        public string TransformXML(string xml, string xsl)
        {
            System.IO.StringReader          stringReader        = null;
            System.Xml.Xsl.XslTransform     xslTransform        = null;
            System.Xml.XmlTextReader        xmlTextReader       = null;
            System.IO.MemoryStream          xmlTextWriterStream = null;
            System.Xml.XmlTextWriter        xmlTextWriter       = null;
            System.Xml.XmlDocument          xmlDocument         = null;
            System.IO.StreamReader          streamReader        = null;
            System.Security.Policy.Evidence evidence            = null;
            try
            {
                stringReader        = new System.IO.StringReader(xsl);
                xslTransform        = new System.Xml.Xsl.XslTransform();
                xmlTextReader       = new System.Xml.XmlTextReader(stringReader);
                xmlTextWriterStream = new System.IO.MemoryStream();
                xmlTextWriter       = new System.Xml.XmlTextWriter(xmlTextWriterStream, System.Text.Encoding.Default);
                xmlDocument         = new System.Xml.XmlDocument();

                evidence = new System.Security.Policy.Evidence();
                evidence.AddAssembly(this);
                xmlDocument.LoadXml(xml);
                xslTransform.Load(xmlTextReader, null, evidence);
                xslTransform.Transform(xmlDocument, null, xmlTextWriter, null);
                xmlTextWriter.Flush();

                xmlTextWriterStream.Position = 0;
                streamReader = new System.IO.StreamReader(xmlTextWriterStream);
                return(streamReader.ReadToEnd());
            }
            catch (Exception exc)
            {
                LogEvent(exc.Source, "TransformXML()", exc.ToString(), 4);
                return("");
            }
            finally
            {
                streamReader.Close();
                xmlTextWriter.Close();
                xmlTextWriterStream.Close();
                xmlTextReader.Close();
                stringReader.Close();
                GC.Collect();
            }
        }
Exemple #60
0
    // <Snippet1>
    private void WriteSchemaWithXmlTextWriter(DataSet thisDataSet)
    {
        // Set the file path and name. Modify this for your purposes.
        string filename = "SchemaDoc.xml";

        // Create a FileStream object with the file path and name.
        System.IO.FileStream stream = new System.IO.FileStream
                                          (filename, System.IO.FileMode.Create);

        // Create a new XmlTextWriter object with the FileStream.
        System.Xml.XmlTextWriter writer =
            new System.Xml.XmlTextWriter(stream,
                                         System.Text.Encoding.Unicode);

        // Write the schema into the DataSet and close the reader.
        thisDataSet.WriteXmlSchema(writer);
        writer.Close();
    }