예제 #1
0
        /// <summary>
        /// Método para criação do Arquivo XML com Configurações do usuário.
        /// </summary>
        public static void CriarArquivoXML()
        {
            try
            {
                System.Xml.XmlTextWriter xtrPrefs = new System.Xml.XmlTextWriter(Directories.UserPrefsDirectory + 
                    @"\UserPrefs.config", System.Text.Encoding.UTF8);

                // Inicia o documento XML.
                xtrPrefs.WriteStartDocument();

                // Escreve elemento raiz.
                xtrPrefs.WriteStartElement("Directories");
                // Escreve sub-Elementos.
                xtrPrefs.WriteElementString("Starbound", Directories.StarboundDirectory);
                xtrPrefs.WriteElementString("Mods", Directories.ModsDirectory);
                // Encerra o elemento raiz.
                xtrPrefs.WriteEndElement();
                // Escreve o XML para o arquivo e fecha o objeto escritor.
                xtrPrefs.Close();
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);

            }
        }
예제 #2
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
            var doc = System.Xml.Linq.XDocument.Load(filename);

            // 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);

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

            // Restore the original file attributes
            System.IO.File.SetAttributes(filename, original_attr);
        }
예제 #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();

                writer.WriteStartElement("Project");
                writer.WriteStartElement("Items");

                Dictionary<int, sProject> projectList;
                DB.LoadProject(out projectList);

                foreach (KeyValuePair<int, sProject> item in projectList)
                {
                    writer.WriteStartElement("Item");
                    writer.WriteAttributeString("uid", item.Key.ToString());
                    writer.WriteAttributeString("name", item.Value.name);
                    writer.WriteEndElement();
                }

                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
예제 #4
0
파일: Program.cs 프로젝트: saveenr/saveenr
        static void Main(string[] args)
        {


            var items = typeof(string).Assembly.GetTypes().Take(100);
            var items2 = items.Select(i => new { i.Name, i.IsClass, i.IsEnum, i.IsValueType });


            var datatable = Isotope.Data.DataUtil.DataTableFromEnumerable(items2);

            string out_filename = "out.xaml";
            var encoding = System.Text.Encoding.UTF8;

            var x = new System.Xml.XmlTextWriter(out_filename, encoding);

            var repdef = new Isotope.Reporting.ReportDefinition();


            repdef.ReportHeaderDefinition.ReportTitle.TextStyle.FontSize = 18.0;
            repdef.ReportHeaderDefinition.ReportTitle.TextStyle.FontWeight = Isotope.Reporting.FontWeight.Bold;
            repdef.ReportHeaderDefinition.HeaderText.TextStyle.FontSize = 8.0;

            var colstyle1 = new Isotope.Reporting.TableColumnStyle();
            colstyle1.DetailTextStyle.FontWeight = Isotope.Reporting.FontWeight.Bold;
            colstyle1.HorzontalAlignment = Isotope.Reporting.HorzontalAlignment.Right;
            colstyle1.Width = 150;

            repdef.Table.ColumnStyles.Add(colstyle1);

            repdef.Table.TableStyle.CellSpacing = 10;
            repdef.WriteXML(x,datatable);
            x.Close();

        }
예제 #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int callstack_uid;

            if (int.TryParse(Request.QueryString["callstack_uid"], out callstack_uid) == false)
                callstack_uid = 1;

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Callstack");

                DB.LoadCallstack(callstack_uid,
                    delegate(int depth, string funcname, string fileline)
                    {
                        writer.WriteStartElement("Singlestep");
                        writer.WriteAttributeString("depth", depth.ToString());
                        this.WriteCData(writer, "Funcname", funcname);
                        this.WriteCData(writer, "Fileline", fileline);
                        writer.WriteEndElement();
                    }
                );

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
예제 #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int report_uid;
            int new_state;

            if (int.TryParse(Request.QueryString["report_uid"], out report_uid) == false)
            {
                return;
            }

            if (int.TryParse(Request.QueryString["state"], out new_state) == false)
                new_state = 1;

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Outputs");

                DB.UpdateReportState(report_uid, new_state);

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
예제 #7
0
        public static void IsolatedStorage_Read_and_Write_Sample()
        {
            string fileName = @"SelfWindow.xml";

            IsolatedStorageFile storFile = IsolatedStorageFile.GetUserStoreForDomain();
            IsolatedStorageFileStream storStream = new IsolatedStorageFileStream(fileName, FileMode.Create, FileAccess.Write);
            System.Xml.XmlWriter writer = new System.Xml.XmlTextWriter(storStream, Encoding.UTF8);
            writer.WriteStartDocument();

            writer.WriteStartElement("Settings");

            writer.WriteStartElement("UserID");
            writer.WriteValue(42);
            writer.WriteEndElement();
            writer.WriteStartElement("UserName");
            writer.WriteValue("kingwl");
            writer.WriteEndElement();

            writer.WriteEndElement();

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

            string[] userFiles = storFile.GetFileNames();

            foreach(var userFile in userFiles)
            {
                if(userFile == fileName)
                {
                    var storFileStreamnew =  new IsolatedStorageFileStream(fileName,FileMode.Open,FileAccess.Read);
                    StreamReader storReader = new StreamReader(storFileStreamnew);
                    System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(storReader);

                    int UserID = 0;
                    string UserName = null;

                    while(reader.Read())
                    {
                        switch(reader.Name)
                        {
                            case "UserID":
                                UserID = int.Parse(reader.ReadString());
                                break;
                            case "UserName":
                                UserName = reader.ReadString();
                                break;
                            default:
                                break;
                        }
                    }

                    Console.WriteLine("{0} {1}", UserID, UserName);

                    storFileStreamnew.Close();
                }
            }
            storFile.Close();
        }
예제 #8
0
        public string ToXml()
        {
            StringWriter xmlStream = null;

            System.Xml.XmlTextWriter xmlWriter = null;
            try
            {
                xmlStream = new StringWriter();
                xmlWriter = new System.Xml.XmlTextWriter(xmlStream);

                // Start Document Element
                xmlWriter.WriteStartElement("ServiceParameters");

                if (this.PublicKey != null)
                {
                    xmlWriter.WriteStartElement("Item");
                    xmlWriter.WriteAttributeString("key", "PublicKey");
                    xmlWriter.WriteString(this.PublicKey);
                    xmlWriter.WriteEndElement();
                }

                Enumerator enumerator = this.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        xmlWriter.WriteStartElement("Item");
                        xmlWriter.WriteAttributeString("key", enumerator.Current.Key);
                        xmlWriter.WriteCData(enumerator.Current.Value);
                        xmlWriter.WriteEndElement();
                    }
                }
                finally
                {
                    enumerator.Dispose();
                }

                // End Document Element
                xmlWriter.WriteEndElement();
                xmlWriter.Flush();

                return(xmlStream.ToString());
            }
            catch (Exception)
            {
                return(string.Empty);
            }
            finally
            {
                xmlWriter?.Close();
                xmlStream?.Close();
            }
        }
예제 #9
0
 // Lecture de la configuration
 public static void WriteConfig()
 {
     string config_file = "config.xml";
     var newconf = new System.Xml.XmlTextWriter(config_file, null);
     newconf.WriteStartDocument();
     newconf.WriteStartElement("config");
     newconf.WriteElementString("last_update", LastUpdate.ToShortDateString());
     newconf.WriteElementString("auth_token", AuthToken);
     newconf.WriteEndElement();
     newconf.WriteEndDocument();
     newconf.Close();
 }
예제 #10
0
        // Lecture de la configuration
        static void ReadConfig()
        {
            string config_file = "config.xml";
            if (!System.IO.File.Exists(config_file))
            {
                var newconf = new System.Xml.XmlTextWriter(config_file, null);
                newconf.WriteStartDocument();
                newconf.WriteStartElement("config");
                newconf.WriteElementString("last_update", "0");
                newconf.WriteElementString("auth_token", "");
                newconf.WriteEndElement();
                newconf.WriteEndDocument();
                newconf.Close();
            }

            var conf = new System.Xml.XmlTextReader(config_file);
            string CurrentElement = "";
            while (conf.Read())
            {
                switch(conf.NodeType) {
                    case System.Xml.XmlNodeType.Element:
                        CurrentElement = conf.Name;
                        break;
                    case System.Xml.XmlNodeType.Text:
                    if (CurrentElement == "last_update")
                        LastUpdate = DateTime.Parse(conf.Value);
                    if (CurrentElement == "auth_token")
                        AuthToken = conf.Value;
                        break;
                }
            }
            conf.Close();

            // On vérifie que le token est encore valide
            if (AuthToken.Length > 0)
            {
                var flickr = new Flickr(Program.ApiKey, Program.SharedSecret);
                try
                {
                    Auth auth = flickr.AuthCheckToken(AuthToken);
                    Username = auth.User.UserName;
                }
                catch (FlickrApiException ex)
                {
                    //MessageBox.Show(ex.Message, "Authentification requise",
                    //    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    AuthToken = "";
                }
            }
        }
예제 #11
0
        private void saveButton_Click(object sender, EventArgs e)
        {
            string settingsFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\DichMusicHelperPathSettings.xml";

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(settingsFile, System.Text.Encoding.Unicode))
            {
                writer.WriteStartElement("PathSettings");
                writer.WriteAttributeString("Path", pathTextBox.Text);
                writer.WriteAttributeString("CreateFolder", createFolderBox.Checked.ToString());
                writer.WriteEndElement();
                writer.Close();
            }

            this.Close();
        }
예제 #12
0
파일: XmlCOM.cs 프로젝트: WZDotCMS/WZDotCMS
 /// <summary>
 /// 保存Config参数
 /// </summary>
 public static void UpdateConfig(string name, string nKey, string nValue)
 {
     if (ReadConfig(name, nKey) != "")
     {
         System.Xml.XmlDocument XmlDoc = new System.Xml.XmlDocument();
         XmlDoc.Load(HttpContext.Current.Server.MapPath(name + ".config"));
         System.Xml.XmlNodeList elemList = XmlDoc.GetElementsByTagName(nKey);
         System.Xml.XmlNode mNode = elemList[0];
         mNode.InnerText = nValue;
         System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(new System.IO.StreamWriter(HttpContext.Current.Server.MapPath(name + ".config")));
         xw.Formatting = System.Xml.Formatting.Indented;
         XmlDoc.WriteTo(xw);
         xw.Close();
     }
 }
예제 #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int project_uid;

            if (int.TryParse(Request.QueryString["project"], out project_uid) == false)
                project_uid = 1;

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();

                writer.WriteStartElement("Report");
                writer.WriteAttributeString("project", project_uid.ToString());

                writer.WriteStartElement("Items");

                DB.LoadReportDeleted(project_uid,
                    delegate(int report_uid, string login_id, string ipaddr, DateTime reported_time, string relative_time, int callstack_uid, string funcname, string version, string filename, string assigned, string uservoice, int num_comments)
                    {
                        writer.WriteStartElement("Item");

                        writer.WriteAttributeString("report_uid", report_uid.ToString());
                        writer.WriteAttributeString("login_id", login_id);
                        writer.WriteAttributeString("ipaddr", ipaddr);
                        writer.WriteAttributeString("reported_time", reported_time.ToString());
                        writer.WriteAttributeString("relative_time", relative_time);
                        writer.WriteAttributeString("callstack_uid", callstack_uid.ToString());
                        writer.WriteAttributeString("assigned", assigned);
                        writer.WriteAttributeString("num_comments", num_comments.ToString());
                        this.WriteCData(writer, "Funcname", funcname);
                        this.WriteCData(writer, "Version", version);
                        this.WriteCData(writer, "Filename", filename);
                        this.WriteCData(writer, "Uservoice", uservoice);

                        writer.WriteEndElement();
                    }
                );
                writer.WriteEndElement(); // Items
                writer.WriteEndElement(); // Report
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
예제 #14
0
 /// <summary>
 /// 序列化成xml字符串
 /// </summary>
 /// <param name="obj"></param>
 /// <returns>序列化后的字符串</returns>
 public static string Serialize(object obj)
 {
     XmlSerializer xs = new XmlSerializer(obj.GetType());
     using (MemoryStream ms = new MemoryStream())
     {
         System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(ms, System.Text.Encoding.UTF8);
         xtw.Formatting = System.Xml.Formatting.Indented;
         xs.Serialize(xtw, obj);
         ms.Seek(0, SeekOrigin.Begin);
         using (StreamReader sr = new StreamReader(ms))
         {
             string str = sr.ReadToEnd();
             xtw.Close();
             ms.Close();
             return str;
         }
     }
 }
예제 #15
0
 public static void saveDataTable(DataTable data, string filePath)
 {
     // Create the FileStream to write with.
     System.IO.FileStream myFileStream = new System.IO.FileStream
        (filePath, System.IO.FileMode.Create);
     // Create an XmlTextWriter with the fileStream.
     System.Xml.XmlTextWriter myXmlWriter =
        new System.Xml.XmlTextWriter(myFileStream, System.Text.Encoding.Unicode);
     // Write to the file with the WriteXml method.
     try
     {
         data.WriteXml(myXmlWriter);
     }
     finally
     {
         myXmlWriter.Close();
     }
 }
예제 #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            string settingsFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\DichMusicHelperProxySettings.xml";

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(settingsFile, System.Text.Encoding.Unicode))
            {
                writer.WriteStartElement("ProxySettings");
                writer.WriteAttributeString("Server", serverBox.Text);
                writer.WriteAttributeString("Port", portBox.Text);
                writer.WriteAttributeString("Login", loginBox.Text);
                writer.WriteAttributeString("Password", passwordBox.Text);
                writer.WriteAttributeString("UseProxy", useProxyBox.Checked.ToString());
                writer.WriteEndElement();
                writer.Close();
            }

            this.Close();
        }
예제 #17
0
파일: Helper.cs 프로젝트: uvbs/FullSource
        public static bool DataTableExportAsXml(DataTable dt, string FileFullPath)
        {
            if (!System.IO.Directory.Exists(Path.GetDirectoryName(FileFullPath)))
            {
                CreatePath(FileFullPath);
            }

            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(FileFullPath, Encoding.UTF8);
            writer.Formatting = System.Xml.Formatting.Indented;
            writer.WriteStartDocument();
            string str = string.Format("type=\"text/xsl\" href=\"{0}.xslt\"", Path.GetFileNameWithoutExtension(FileFullPath));

            writer.WriteProcessingInstruction("xml-stylesheet", str);


            dt.DataSet.WriteXml(writer);
            writer.Close();

            return(true);
        }
예제 #18
0
        public static void SaveDocument(System.Xml.XmlDocument origDoc, System.IO.Stream strm, bool bDoReplace)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

            if (bDoReplace)
                doc.LoadXml(origDoc.OuterXml.Replace("xmlns=\"\"", ""));

            using (System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(strm, System.Text.Encoding.UTF8))
            {
                xtw.Formatting = System.Xml.Formatting.Indented; // if you want it indented
                xtw.Indentation = 4;
                xtw.IndentChar = ' ';

                doc.Save(xtw);
                xtw.Flush();
                xtw.Close();
            } // End Using xtw

            doc = null;
        }
예제 #19
0
        public static string WriteXsd()
        {
            if (File.Exists("Gwen.xml"))
            {
                m_comments = XDocument.Load("Gwen.xml");
            }
            XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-8", null));

            XNamespace xs     = "http://www.w3.org/2001/XMLSchema";
            XElement   schema = new XElement(xs + "schema",
                                             new XAttribute(XNamespace.Xmlns + "xs", "http://www.w3.org/2001/XMLSchema"));

            doc.Add(schema);

            schema.Add(new XElement(xs + "simpleType", new XAttribute("name", "text"),
                                    new XElement(xs + "restriction", new XAttribute("base", "xs:string"))
                                    ));

            XElement cgroup = new XElement(xs + "group");

            cgroup.SetAttributeValue("name", "controls");
            XElement choice = new XElement(xs + "choice");

            cgroup.Add(choice);
            schema.Add(cgroup);
            foreach (KeyValuePair <string, ElementDef> element in m_ElementHandlers)
            {
                XElement ele = new XElement(xs + "element");
                ele.SetAttributeValue("name", element.Key);
                ele.SetAttributeValue("ref", element.Key);
                choice.Add(ele);
                schema.Add(CreateXElementForType(element.Value));
            }

            System.Xml.XmlTextWriter xwriter = new System.Xml.XmlTextWriter("Gwen.xsd", Encoding.UTF8);
            xwriter.Formatting = System.Xml.Formatting.Indented;
            doc.WriteTo(xwriter);
            xwriter.Flush();
            xwriter.Close();
            return(File.ReadAllText("Gwen.xsd"));
        }
예제 #20
0
        public void WritePictureXMLFile(List <FileSystemEventArgs> listPictureChanged, bool init = false)
        {
            GlobalDataStore.Logger.Debug("Updating Pictures.xml ...");

            if (init)
            {
                items = new List <LabelX.Toolbox.LabelXItem>();
            }

            //if (listPictureChanged.Count == 0)
            //    items = new List<LabelX.Toolbox.LabelXItem>();

            DirectoryInfo PicturesRootFolderDirectoryInfo = new DirectoryInfo(PicturesRootFolder);

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

            //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();

            GlobalDataStore.Logger.Debug("Updating Pictures.xml. Done.");
        }
예제 #21
0
 /// <summary>
 /// Html To XMl  返回格式化好的XML文件
 /// </summary>
 /// <param name="html">传入要格式化的HTML文件</param>
 /// <returns>返回格式化好的XML文件</returns>
 public static string HTMLConvert(string html)
 {
     if (string.IsNullOrEmpty(html.Trim()))
     {
         return(string.Empty);
     }
     //solve ]]>
     //处理节点
     html = System.Text.RegularExpressions.Regex.Replace(html, @"<!\s{0,}\[\s{0,}CDATA\s{0,}\[\s{0,}|\s{0,}\]\s{0,}\]\s{0,}>", "");
     using (Sgml.SgmlReader reader = new Sgml.SgmlReader())
     {
         reader.DocType     = "HTML";
         reader.InputStream = new System.IO.StringReader(html);
         using (System.IO.StringWriter stringWriter = new System.IO.StringWriter())
         {
             //实例化对象
             using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stringWriter))
             {
                 reader.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
                 writer.Formatting         = System.Xml.Formatting.Indented;
                 System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                 doc.Load(reader);
                 if (doc.DocumentElement == null)
                 {
                     return("Html to XML Error this programe can not Convert");
                 }
                 else
                 {
                     doc.DocumentElement.WriteContentTo(writer);
                 }
                 writer.Close();
                 string xhtml = stringWriter.ToString();
                 if (xhtml == null)
                 {
                     return(stringWriter.ToString());
                 }
                 return(xhtml);
             }
         }
     }
 }
예제 #22
0
        void CreateHandler_Click(object sender, EventArgs args)
        {
            try
            {
                System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter("1.xml", UTF8Encoding.UTF8);
                w.WriteRaw("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                ModelNode model = (ModelNode)this.Reslove(typeof(ModelNode), null);
                w.WriteRaw(model.DataInfo.DomNode.OuterXml);
                w.Flush();
                w.Close();

                GenHandler    gen     = new GenHandler(@"Xsl/ListOperationHandler.xslt", "1.xml");
                StringBuilder builder = new StringBuilder();
                gen.Generate(builder);
                this.OnGenerate(this, builder);
            }
            catch (Exception ex)
            {
                MessageBox.Show("生成失败:" + ex.Message);
            }
        }
예제 #23
0
        public static void Serialize <T>(string path, T value)
        {
            System.Xml.XmlTextWriter writer = null;

            try
            {
                writer = new System.Xml.XmlTextWriter(path, Encoding.UTF8);

                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

                serializer.Serialize(writer, value);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                writer.Close();
            }
        }
예제 #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType     = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int callstack_uid;

            if (int.TryParse(Request.QueryString["callstack_uid"], out callstack_uid) == false)
            {
                callstack_uid = 1;
            }

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Comment");

                writer.WriteAttributeString("callstack_uid", callstack_uid.ToString());

                DB.ForEachCallstackComment CommentWriter = delegate(string author, string comment, DateTime created)
                {
                    writer.WriteStartElement("Item");

                    writer.WriteAttributeString("author", author);
                    writer.WriteAttributeString("created", created.ToString());

                    writer.WriteCData(comment);

                    writer.WriteEndElement();
                };

                DB.LoadCallstackComment(callstack_uid, CommentWriter);

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
예제 #25
0
        public void TestResultBasicInfo_WriteXml()
        {
            XmlNode testNode = testResult.ToXml(true);

            string expected = GenerateExpectedXml(testResult);

            StringBuilder actual = new StringBuilder();
            StringWriter  sw     = new StringWriter(actual);

#if CLR_2_0 || CLR_4_0
            System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
            settings.CloseOutput      = true;
            settings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment;
            System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sw, settings);
#else
            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw);
#endif
            testNode.WriteTo(writer);
            writer.Close();

            Assert.That(actual.ToString(), Is.EqualTo(expected));
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int project_uid;
            int report_uid;
            string version;

            if (int.TryParse(Request.QueryString["project"], out project_uid) == false)
                project_uid = 1;

            if (int.TryParse(Request.QueryString["report_uid"], out report_uid) == false)
            {
                return;
            }

            version = Request.QueryString["version"];
            if (version != null)
            {
                version.Trim();
                if (version.Length == 0)
                    version = null;
            }

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Outputs");

                DB.ReserveReparse(project_uid, report_uid, version);

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
예제 #27
0
        private void tbnOK_Click(object sender, EventArgs e)
        {
            object select = combxDataBases.SelectedValue;
            if (select == null)
            {
                return;
            }
            ChoosedDBName = combxDataBases.SelectedValue.ToString();
            string oldDefault = ds.Tables["root"].Rows[0][0].ToString();
            if (oldDefault != ChoosedDBName && chkSetDefault.Checked)
            {
                ds.Tables["root"].Rows[0][0] = ChoosedDBName;
                System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(dbXmlFile, Encoding.UTF8);
                writer.Formatting = System.Xml.Formatting.Indented;
                writer.WriteStartDocument();

                ds.WriteXml(writer);
                writer.Close();
            }
            
            this.DialogResult = DialogResult.OK;
        }
 private void btnExportar_Click(object sender, EventArgs e)
 {
     if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
     {
         System.Xml.XmlTextWriter xml = new System.Xml.XmlTextWriter(this.saveFileDialog1.FileName, null);
         xml.WriteStartDocument();
         xml.WriteStartElement("datagridview");
         foreach (DataGridViewRow row in this.dgv.Rows)
         {
             xml.WriteStartElement("row");
             for (int i = 0; i < this.dgv.ColumnCount; i++)
             {
                 xml.WriteStartElement("column");
                 xml.WriteElementString("value", row.Cells[i].Value.ToString());
                 xml.WriteEndElement();
             }
             xml.WriteEndElement();
         }
         xml.WriteEndElement();
         xml.Close();
     }
 }
예제 #29
0
        } // End Function XmlUnescape

        public static void SaveDocument(System.Xml.XmlDocument origDoc, System.IO.Stream strm, bool bDoReplace)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

            if (bDoReplace)
            {
                doc.LoadXml(origDoc.OuterXml.Replace("xmlns=\"\"", ""));
            }

            using (System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(strm, System.Text.Encoding.UTF8))
            {
                xtw.Formatting  = System.Xml.Formatting.Indented; // if you want it indented
                xtw.Indentation = 4;
                xtw.IndentChar  = ' ';

                doc.Save(xtw);
                xtw.Flush();
                xtw.Close();
            } // End Using xtw

            doc = null;
        } // End Sub SaveDocument
예제 #30
0
        /// <summary>
        /// 写配置文件
        /// </summary>
        private void WriteInfo()
        {
            if (ClassPaths.Count == 0)
            {
                try
                {
                    FileInfo fi = new FileInfo("配置.xml");
                    fi.Delete();
                    return;
                }
                catch
                {
                    return;
                }
            }
            FileStream FS = new FileStream("配置.xml", FileMode.Create);

            System.Xml.XmlTextWriter myXml = new System.Xml.XmlTextWriter(FS, System.Text.Encoding.Default);
            myXml.Formatting = System.Xml.Formatting.Indented;
            myXml.WriteStartDocument(true);
            myXml.WriteStartElement("ClassInfo");
            Int32 id = 0;

            foreach (String[] cp in ClassPaths)
            {
                myXml.WriteStartElement("Class");
                myXml.WriteAttributeString("ID", id.ToString());
                myXml.WriteElementString("ClassName", cp[0]);
                myXml.WriteElementString("FilePath", cp[1]);
                myXml.WriteElementString("Direction", cp[2]);
                myXml.WriteEndElement();
                id++;
            }

            myXml.WriteEndElement();
            myXml.WriteEndDocument();
            myXml.Close();
            FS.Close();
        }
예제 #31
0
        /// <summary>
        /// Returns the configuration as XML string</summary>
        protected virtual string ReturnConfiguration()
        {
            //- example -
            //<?xml version="1.0" encoding="UTF-16"?>
            //<ndd>
            //  <Command Type="Configuration">
            //    <Parameter Name="CloseAfterTest">True</Parameter>
            //    <Parameter Name="SkipPatientSelectionConfirmation">True</Parameter>
            //    <Parameter Name="IncludeCurveData">False</Parameter>
            //    <Parameter Name="IncludeTrialValues">False</Parameter>
            //    <Parameter Name="FileExchangeFolder">C:\temp\EMR</Parameter>
            //    <Parameter Name="AttachReport">True</Parameter>
            //    <Parameter Name="AttachmentFileName">%PatientID%</Parameter>
            //    <Parameter Name="AttachmentFormat">PDF</Parameter>
            //</Command>
            //</ndd>

            StringBuilder sb = new System.Text.StringBuilder();

            using (System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(new System.IO.StringWriter(sb, CultureInfo.InvariantCulture)))
            {
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("ndd");
                xmlWriter.WriteStartElement("Command");
                xmlWriter.WriteAttributeString("Type", Commands.Configuration.Command);

                //write configuration values (they could be fix)
                WriteConfigurationValues(xmlWriter);

                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndDocument();

                xmlWriter.Flush();
                xmlWriter.Close();
                return(sb.ToString());
            }
        }
예제 #32
0
        public void writeGPX(string filename)
        {
            System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".gpx", Encoding.ASCII);

            xw.WriteStartElement("gpx");

            xw.WriteStartElement("trk");

            xw.WriteStartElement("trkseg");

            DateTime start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);

            foreach (Data mod in flightdata)
            {
                xw.WriteStartElement("trkpt");
                xw.WriteAttributeString("lat", mod.model.Location.latitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteAttributeString("lon", mod.model.Location.longitude.ToString(new System.Globalization.CultureInfo("en-US")));

                xw.WriteElementString("ele", mod.model.Location.altitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("time", mod.datetime.ToString("yyyy-MM-ddTHH:mm:sszzzzzz"));
                xw.WriteElementString("course", (mod.model.Orientation.heading).ToString(new System.Globalization.CultureInfo("en-US")));

                xw.WriteElementString("roll", mod.model.Orientation.roll.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("pitch", mod.model.Orientation.tilt.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("mode", mod.mode);

                //xw.WriteElementString("speed", mod.model.Orientation.);
                //xw.WriteElementString("fix", mod.model.Location.altitude);

                xw.WriteEndElement();
            }

            xw.WriteEndElement();
            xw.WriteEndElement();
            xw.WriteEndElement();

            xw.Close();
        }
예제 #33
0
        private static CodeDefinition AddComment(DeprecatableObject obj, CodeDefinition cd)
        {
            var comment = new CodeDefinition {
                Indent = "/// "
            };

            cd.Children.Add(comment);
            if (obj.Description != null)
            {
                comment.Children.Add("<summary>");
                var sw     = new StringWriter();
                var writer = new System.Xml.XmlTextWriter(sw);
                writer.WriteString(obj.Description);
                writer.Close();
                foreach (var str in sw.ToString().Split('\n'))
                {
                    comment.Children.Add(str.Replace("\r", ""));
                }
                comment.Children.Add("</summary>");
            }
            if (obj.IsDeprecated)
            {
                if (!string.IsNullOrEmpty(obj.DeprecationReason))
                {
                    cd.Children.Add(string.Format("[System.Obsolete(\"{0}\")]",
                                                  obj.DeprecationReason
                                                  .Replace("\\", "\\\\")
                                                  .Replace("\n", "\\n")
                                                  .Replace("\"", "\\\"")));
                }
                else
                {
                    cd.Children.Add("[System.Obsolete]");
                }
            }

            return(comment);
        }
예제 #34
0
        static void UpdateAppConfig()
        {
            Dictionary <string, string> dic = new Dictionary <string, string>();

            dic["AccountName"] = "mediavaletdevasia12";

            string appConfigFile = @"C:\webjob\MediaValet.WebJobs.EntityChangeListener.exe.config";

            System.Xml.Linq.XElement xelement = System.Xml.Linq.XElement.Load(appConfigFile);

            IEnumerable <System.Xml.Linq.XElement> elements = xelement.Elements().ToList();

            // Read the entire XML
            foreach (var element in elements)
            {
                if (element.Name.LocalName == "appSettings")
                {
                    var eles = element.Elements().ToList();

                    foreach (var ele in eles)
                    {
                        if (dic.ContainsKey(ele.Attribute("key").Value))
                        {
                            ele.Attribute("value").Value = dic[ele.Attribute("key").Value];
                        }
                    }
                }
            }

            var ww = new System.Xml.XmlTextWriter(appConfigFile, System.Text.Encoding.UTF8);

            ww.Formatting = System.Xml.Formatting.Indented;
            ww.WriteStartDocument();

            xelement.WriteTo(ww);
            ww.Flush();
            ww.Close();
        }
예제 #35
0
        internal static bool SerializeRegisteredServers(RegisteredServers regServers, string fileName)
        {
            if (fileName == null || fileName.Length == 0)
            {
                log.LogWarning("Unable to serialize registered servers. The destination fileName is null or empty");
                return(false);
            }

            if (regServers == null)
            {
                log.LogWarning($"Unable to serialize registered servers to {fileName}. \"RegisteredServers\" object is null");
                return(false);
            }
            try
            {
                System.Xml.XmlTextWriter tw = null;
                try
                {
                    XmlSerializer xmlS = new XmlSerializer(typeof(RegisteredServers));
                    tw            = new System.Xml.XmlTextWriter(fileName, Encoding.UTF8);
                    tw.Formatting = System.Xml.Formatting.Indented;
                    xmlS.Serialize(tw, regServers);
                }
                finally
                {
                    if (tw != null)
                    {
                        tw.Close();
                    }
                }
                return(true);
            }
            catch (System.UnauthorizedAccessException exe)
            {
                log.LogError(exe, $"Unable to serialze file to {fileName}");
                return(false);
            }
        }
예제 #36
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int callstack_uid;

            if (int.TryParse(Request.QueryString["callstack_uid"], out callstack_uid) == false)
                callstack_uid = 1;

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Comment");

                writer.WriteAttributeString("callstack_uid", callstack_uid.ToString());

                DB.ForEachCallstackComment CommentWriter = delegate(string author, string comment, DateTime created)
                {
                    writer.WriteStartElement("Item");

                    writer.WriteAttributeString("author", author);
                    writer.WriteAttributeString("created", created.ToString());

                    writer.WriteCData(comment);

                    writer.WriteEndElement();
                };

                DB.LoadCallstackComment(callstack_uid, CommentWriter);

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
예제 #37
0
        protected virtual string ReturnConfiguration()
        {
            StringBuilder sb = new System.Text.StringBuilder();

            using (System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(new System.IO.StringWriter(sb, CultureInfo.InvariantCulture)))
            {
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("ndd");
                xmlWriter.WriteStartElement("Command");
                xmlWriter.WriteAttributeString("Type", Commands.Configuration.Command);

                //write configuration values (they could be fix)
                WriteConfiguration(xmlWriter);

                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndDocument();

                xmlWriter.Flush();
                xmlWriter.Close();
                return(sb.ToString());
            }
        }
예제 #38
0
        /// <summary>
        /// 备份全部的数据表到 XML 文件。
        /// </summary>
        /// <param name="Connection">已经打开的数据库连接。</param>
        /// <param name="XMLFile">XML 文件名。</param>
        /// <param name="Description">文档备注。</param>
        public void BackupAllTables(System.Data.SqlClient.SqlConnection Connection, string XMLFile, string Description)
        {
            System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(XMLFile, System.Text.Encoding.UTF8);
            try
            {
                xtw.Formatting = System.Xml.Formatting.Indented;
                xtw.WriteStartDocument();
                xtw.WriteStartElement("Root");
                this.WriteVersion(xtw, Version, Description, Generator);

                string[] tables = this.GetTables(Connection);
                foreach (string tmp in tables)
                {
                    this.BackupTable(Connection, xtw, tmp);
                }
                xtw.WriteEndElement();
                xtw.WriteEndDocument();
            }
            finally
            {
                xtw.Close();
            }
        }
예제 #39
0
        private void datagridviewExportAsXml(DataGridView dgv, string FileFullPath)
        {
            string strExamPath = FileFullPath.Substring(0, FileFullPath.LastIndexOf('\\'));

            if (!System.IO.Directory.Exists(strExamPath))
            {
                MessageBox.Show(FileFullPath, "目录错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            DataSet ds4Xml = new DataSet();

            datagridviewToDataSet(dgv, ds4Xml);

            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(FileFullPath, Encoding.UTF8);
            writer.Formatting = System.Xml.Formatting.Indented;
            writer.WriteStartDocument();
            string str = string.Format("type=\"text/xsl\" href=\"{0}.xslt\"", System.IO.Path.GetFileNameWithoutExtension(FileFullPath));

            writer.WriteProcessingInstruction("xml-stylesheet", str);

            ds4Xml.WriteXml(writer);
            writer.Close();
            MessageBox.Show("文件成功保存到了" + FileFullPath, "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
예제 #40
0
        public ActionResult RSS()
        {
            //...XmlTextWriter RSSFeed = new XmlTextWriter(MapPath("./" + "RSS.rss"), System.Text.Encoding.UTF8);
            System.Xml.XmlTextWriter RSSFeed = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8);
            // Write the rss tags like title, version,
            // Channel, title, link description copyright etc. 
            RSSFeed.WriteStartDocument();
            RSSFeed.WriteStartElement("rss");
            RSSFeed.WriteAttributeString("version", "2.0");
            RSSFeed.WriteStartElement("channel");
            RSSFeed.WriteElementString("title", "Mehdi Naseri RSS");
            RSSFeed.WriteElementString("description", "This Website has been made by: Mehdi Naseri");
            RSSFeed.WriteElementString("link", "http://Naseri.Net");
            RSSFeed.WriteElementString("pubDate", DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss +0000"));
            RSSFeed.WriteElementString("copyright", "Copyright Mehdi Naseri 2013");
            //Items of RSS
            for (int i = 0; i < 3; i++)
            {
                RSSFeed.WriteStartElement("item");
                RSSFeed.WriteElementString("title", string.Format("Title " + (i + 1).ToString()));
                RSSFeed.WriteElementString("description", string.Format("Description " + (i + 1).ToString()));
                RSSFeed.WriteElementString("link", "http://Naseri.Net/RSS");
                //RSSFeed.WriteElementString("pubDate", "Mon, 06 Sep 2009 16:45:00 +0000");
                RSSFeed.WriteElementString("pubDate", DateTime.Now.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss +0000"));
                RSSFeed.WriteEndElement();
            }
            RSSFeed.WriteEndElement();
            RSSFeed.WriteEndElement();
            RSSFeed.WriteEndDocument();
            RSSFeed.Flush();
            RSSFeed.Close();
            Response.End();

            return Content(RSSFeed.ToString(), "text/xml", System.Text.Encoding.UTF8);
            //return View();
        }
예제 #41
0
        private bool saveToFile()
        {
            string outPath = this.config.OutSavePath;

            if (outPath != null)
            {
                Logger.Trace("Saving work file to: " + outPath);

                System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(outPath, null);
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("root");
                extendedSimMatrix.WriteXml(xmlWriter);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndDocument();
                xmlWriter.Flush();

                xmlWriter.Close();
            }
            else
            {
                Logger.Trace("File not saved as no file path has been provided.");
            }
            return(true);
        }
예제 #42
0
        private void tbnOK_Click(object sender, EventArgs e)
        {
            object select = combxDataBases.SelectedValue;

            if (select == null)
            {
                return;
            }
            ChoosedDBName = combxDataBases.SelectedValue.ToString();
            string oldDefault = ds.Tables["root"].Rows[0][0].ToString();

            if (oldDefault != ChoosedDBName && chkSetDefault.Checked)
            {
                ds.Tables["root"].Rows[0][0] = ChoosedDBName;
                System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(dbXmlFile, Encoding.UTF8);
                writer.Formatting = System.Xml.Formatting.Indented;
                writer.WriteStartDocument();

                ds.WriteXml(writer);
                writer.Close();
            }

            this.DialogResult = DialogResult.OK;
        }
예제 #43
0
 public bool SaveConfiguration(string fileName)
 {
     System.Xml.XmlTextWriter tw = null;
     try
     {
         XmlSerializer xmlS = new XmlSerializer(typeof(SprocTest.Configuration.Database));
         tw             = new System.Xml.XmlTextWriter(fileName, Encoding.UTF8);
         tw.Formatting  = System.Xml.Formatting.Indented;
         tw.Indentation = 3;
         xmlS.Serialize(tw, this);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
     finally
     {
         if (tw != null)
         {
             tw.Close();
         }
     }
 }
예제 #44
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();

            System.Xml.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);
        }
예제 #45
0
        /// <summary>
        /// This method writes an error message to the log file specified by the _logfile FileInfo object
        /// </summary>
        public void WriteEventToFile(string Message, EventLogEntryType EntryType)
        {
            //todo: perhaps add more structure layout to this?
            if (_logFile != null)
            {
                //using (StreamWriter sw = _logFile.AppendText())
                using (System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(_logFile.Open(FileMode.Append, FileAccess.Write), System.Text.Encoding.ASCII))
                {
                    try
                    {
                        //sw.WriteLine(EntryType.ToString() + ": " + Message);
                        //xw.WriteLine("{0} {1}: {2}", DateTime.Now, EntryType.ToString(), Message);

                        //xw.WriteElementString("Date", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString());
                        //xw.WriteElementString("EntryType", EntryType.ToString());
                        //xw.WriteElementString("Message", Message);

                        xw.WriteStartElement("Event");

                        xw.WriteAttributeString("Date", DateTime.Now.ToShortDateString());
                        xw.WriteAttributeString("Time", DateTime.Now.ToShortTimeString());
                        xw.WriteAttributeString("EntryType", EntryType.ToString());
                        xw.WriteString(Message);

                        xw.WriteEndElement();
                        xw.WriteString("\n");

                        xw.Close();
                    }
                    catch (Exception ex)
                    {
                        EventLogHelper.WriteApplicationEvent("Could not write to log file.\nMessage:  " + Message + "\nException:" + ex.Message, EventLogEntryType.Error, "Application");
                    }
                }
            }
        }
예제 #46
0
    public static void ExportExcelXMLFromDataSet(DataSet ds)
    {
        DataSet objDataset = ds;


        //Create   the   FileStream   to   write   with.
        System.IO.FileStream fs = new System.IO.FileStream(
            "C:\\test.xml", System.IO.FileMode.Create);

        //Create   an   XmlTextWriter   for   the   FileStream.
        System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(
            fs, System.Text.Encoding.Unicode);

        //Add   processing   instructions   to   the   beginning   of   the   XML   file,   one
        //of   which   indicates   a   style   sheet.
        xtw.WriteProcessingInstruction("xml", "version='1.0'");
        //xtw.WriteProcessingInstruction("xml-stylesheet",
        //   "type='text/xsl'   href='customers.xsl'");

        //Write   the   XML   from   the   dataset   to   the   file.
        objDataset.WriteXml(xtw);
        xtw.Close();
        Common.DownLoadFile("c:\\test.xml");
    }
예제 #47
0
        private void writeGPX(string filename)
        {
            System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".gpx",Encoding.ASCII);

            xw.WriteStartElement("gpx");

            xw.WriteStartElement("trk");

            xw.WriteStartElement("trkseg");

            DateTime start = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,0,0,0);

            foreach (Data mod in flightdata)
            {
                xw.WriteStartElement("trkpt");
                xw.WriteAttributeString("lat", mod.model.Location.latitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteAttributeString("lon", mod.model.Location.longitude.ToString(new System.Globalization.CultureInfo("en-US")));

                xw.WriteElementString("ele", mod.model.Location.altitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("time", start.AddMilliseconds(mod.datetime).ToString("yyyy-MM-ddTHH:mm:sszzzzzz"));
                xw.WriteElementString("course", (mod.model.Orientation.heading).ToString(new System.Globalization.CultureInfo("en-US")));

                xw.WriteElementString("roll", mod.model.Orientation.roll.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("pitch", mod.model.Orientation.tilt.ToString(new System.Globalization.CultureInfo("en-US")));
                //xw.WriteElementString("speed", mod.model.Orientation.);
                //xw.WriteElementString("fix", mod.model.Location.altitude);

                xw.WriteEndElement();
            }

            xw.WriteEndElement();
            xw.WriteEndElement();
            xw.WriteEndElement();

            xw.Close();
        }
예제 #48
0
        private void onXMLSent(string xml, long socketId)
        {
            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(xml);

                System.IO.StringWriter sw = new System.IO.StringWriter();
                System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter(sw);
                w.Formatting = System.Xml.Formatting.Indented;
                w.Indentation = 4;

                doc.Save(w);
                w.Flush();
                w.Close();

                string s = sw.ToString();
                int lineEnd = s.IndexOf("<", 2);
                s = s.Substring(lineEnd);

                string t = String.Format("{2}Sent at {0}: {2}{1}{2}", DateTime.Now.ToShortTimeString(), s, "\r\n");
                AppendTextThreadSafe(t);
            }
            catch(Exception)
            {
            }
        }
예제 #49
0
        void CreateHandler_Click(object sender, EventArgs args)
        {
            try
            {
                System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter("1.xml", UTF8Encoding.UTF8);
                w.WriteRaw("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                ModelNode model = (ModelNode)this.Reslove(typeof(ModelNode), null);
                w.WriteRaw(model.DataInfo.DomNode.OuterXml);
                w.Flush();
                w.Close();

                GenHandler gen = new GenHandler(@"Xsl/ListOperationHandler.xslt", "1.xml");
                StringBuilder builder = new StringBuilder();
                gen.Generate(builder);
                this.OnGenerate(this, builder);
            }
            catch (Exception ex)
            {
                MessageBox.Show("生成失败:" + ex.Message);
            }
        }
예제 #50
0
 /// <summary>
 /// Save (merely a shortcut to the serializer
 /// </summary>
 /// <param name="filename"></param>
 public override void Save(string filename = "bla.xml")
 {
     System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(filename, Encoding.Unicode);
     XmlSerializer serializer = new XmlSerializer(typeof(WallTiles));
     serializer.Serialize(writer, this);
     writer.Close();
 }
예제 #51
0
        public void Run()
        {
            geneticfx.Environment env = new geneticfx.Environment( );
            env.StartGeneration += new geneticfx.Environment.EventHandlerDelegate(this.StartGenerationHandler);
            env.EndGeneration   += new geneticfx.Environment.EventHandlerDelegate(this.EndGenerationHandler);

            geneticfx.Population initial_population = new geneticfx.Population(50);

            System.Collections.ArrayList rects = new System.Collections.ArrayList();

            rects.Add(new RECT(0, 0, 100, 100));
            rects.Add(new RECT(0, 0, 100, 200));

            rects.Add(new RECT(0, 0, 200, 100));
            rects.Add(new RECT(0, 0, 200, 200));

            rects.Add(new RECT(0, 0, 200, 100));
            rects.Add(new RECT(0, 0, 200, 200));

            rects.Add(new RECT(0, 0, 100, 100));
            rects.Add(new RECT(0, 0, 100, 200));

            rects.Add(new RECT(0, 0, 100, 100));
            rects.Add(new RECT(0, 0, 100, 200));
            rects.Add(new RECT(0, 0, 100, 100));
            rects.Add(new RECT(0, 0, 100, 200));

            for (int i = 0; i < initial_population.Capacity; i++)
            {
                MyChromosome cs = new MyChromosome(rects);
                cs.RandomizeGenes();
                geneticfx.Organism o = new geneticfx.Organism(cs, 0.0F);
                initial_population.AddOrganism(o);
            }

            env.MutationRate = 0.10F;
            int num_generations = 10;

            env.SetupForEvolution(initial_population, geneticfx.FitnessDirection.Minimize);

            string fname = "out.svg";

            fname = System.IO.Path.GetFullPath(fname);

            System.Xml.XmlWriter xw = new System.Xml.XmlTextWriter(fname, System.Text.Encoding.UTF8);
            xw.WriteStartElement("svg");

            int cur_y = 100;

            for (int i = 0; i < num_generations; i++)
            {
                env.EvolveNextGeneration();

                geneticfx.Generation generation = env.CurrentGeneration;

                int cur_x = 100;
                for (int generation_index = 0; generation_index < generation.population.Size; generation_index++)
                {
                    geneticfx.Organism o   = generation.population[generation_index];
                    MyChromosome       mcr = (MyChromosome)o.Genes;

                    RECT bb = RECTTOOLS.get_bounding_box(mcr.layout_rects);
                    xw.WriteStartElement("g");
                    xw.WriteAttributeString("transform", string.Format("translate({0},{1})", cur_x, cur_y));
                    for (int icr = 0; icr < mcr.Length; icr++)
                    {
                        RECT r = mcr.layout_rects [icr];
                        xw.WriteStartElement("rect");
                        xw.WriteAttributeString("x", r.x0.ToString());
                        xw.WriteAttributeString("y", r.y0.ToString());
                        xw.WriteAttributeString("width", r.w.ToString());
                        xw.WriteAttributeString("height", r.h.ToString());
                        xw.WriteAttributeString("opacity", "0.1");
                        xw.WriteEndElement();

                        xw.WriteStartElement("text");
                        xw.WriteAttributeString("x", "0");
                        xw.WriteAttributeString("y", "0");
                        string s = string.Format("Gen{0} / Org{1} / Fit={2}", generation_index, o.ID, o.Fitness);
                        xw.WriteString(s);
                        xw.WriteEndElement();
                    }
                    xw.WriteEndElement();


                    cur_x += (int)(1000 + 100);
                }
                cur_y += (int)(1000 + 100);


                xw.Flush();
            }
            xw.WriteEndElement();
            xw.Flush();
            xw.Close();
        }
예제 #52
0
        /// <summary>
        /// Save the whole diagram to a xml file.
        /// </summary>
        /// <param name="fileName">File name into which the whole diagram is saved.</param>
        public void SaveDiagramToFile( string fileName)
        {
            System.Xml.XmlTextWriter writer;
            writer = new System.Xml.XmlTextWriter(fileName, System.Text.Encoding.UTF8);

            SaveDiagramToXml(writer);
            writer.Close();
            m_currentFileName = fileName;
        }
예제 #53
0
        private void writeGPX(string filename)
        {
            using (System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".gpx", Encoding.ASCII))
            {

                xw.WriteStartElement("gpx");

                xw.WriteStartElement("trk");

                xw.WriteStartElement("trkseg");

                List<string> items = new List<string>();

                foreach (string photo in photocoords.Keys)
                {
                    items.Add(photo);
                }

                items.Sort();

                foreach (string photo in items)
                {

                    xw.WriteStartElement("trkpt");
                    xw.WriteAttributeString("lat", ((double[])photocoords[photo])[0].ToString(new System.Globalization.CultureInfo("en-US")));
                    xw.WriteAttributeString("lon", ((double[])photocoords[photo])[1].ToString(new System.Globalization.CultureInfo("en-US")));

                    // must stay as above

                    xw.WriteElementString("time", ((DateTime)filedatecache[photo]).ToString("yyyy-MM-ddTHH:mm:ssZ"));

                    xw.WriteElementString("ele", ((double[])photocoords[photo])[2].ToString(new System.Globalization.CultureInfo("en-US")));
                    xw.WriteElementString("course", ((double[])photocoords[photo])[3].ToString(new System.Globalization.CultureInfo("en-US")));

                    xw.WriteElementString("compass", ((double[])photocoords[photo])[3].ToString(new System.Globalization.CultureInfo("en-US")));

                    xw.WriteEndElement();
                }

                xw.WriteEndElement();
                xw.WriteEndElement();
                xw.WriteEndElement();

                xw.Close();
            }
        }
예제 #54
0
        /// <summary>
        /// Saves movie goofs to an xml file 
        /// </summary>
        /// <param name="movie">IIMDbMovie object</param>
        /// <param name="xmlPath">path to save xml file to</param>
        /// <param name="overwrite">set to true to overwrite existing xml file</param>
        public void SaveGoofs(
            IIMDbMovie movie,
            string xmlPath,
            bool overwrite)
        {
            System.Xml.XmlTextWriter xmlWr;

            try
            {
                if (System.IO.File.Exists(xmlPath) == false
                    || overwrite)
                    if (movie.Goofs.Count > 0)
                    {
                        xmlWr = new System.Xml.XmlTextWriter(xmlPath, Encoding.Default);
                        xmlWr.Formatting = System.Xml.Formatting.Indented;
                        xmlWr.WriteStartDocument();
                        xmlWr.WriteStartElement("Goofs");
                        foreach (IIMDbGoof goof in movie.Goofs)
                        {
                            xmlWr.WriteStartElement("Goof");
                            xmlWr.WriteElementString("Category", goof.Category);
                            xmlWr.WriteElementString("Description", goof.Description);
                            xmlWr.WriteEndElement();
                        }
                        xmlWr.WriteEndElement();
                        xmlWr.WriteEndDocument();
                        xmlWr.Flush();
                        xmlWr.Close();
                        xmlWr = null;
                    }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #55
0
 // Generates content of customXmlPart1.
 private void GenerateCustomXmlPart1Content(CustomXmlPart customXmlPart1)
 {
     System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(customXmlPart1.GetStream(System.IO.FileMode.Create), System.Text.Encoding.UTF8);
     writer.WriteRaw("<b:Sources SelectedStyle=\"\\APASixthEditionOfficeOnline.xsl\" StyleName=\"APA\" Version=\"6\" xmlns:b=\"http://schemas.openxmlformats.org/officeDocument/2006/bibliography\" xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/bibliography\"></b:Sources>\r\n");
     writer.Flush();
     writer.Close();
 }
예제 #56
0
        List <Result> handleXML(string text)
        {
            try {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(text);
                string fmt = null, zip = null;
                {
                    StringWriter sw = new System.IO.StringWriter();
                    using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw)) {
                        writer.Indentation = 4;  // the Indentation
                        writer.Formatting  = System.Xml.Formatting.Indented;
                        doc.WriteContentTo(writer);
                        writer.Close();
                    }
                    fmt = sw.ToString();
                }

                {
                    StringWriter sw = new StringWriter();
                    using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw)) {
                        doc.WriteContentTo(writer);
                        writer.Close();
                    }
                    zip = sw.ToString();
                }

                Result fmtItem = new Result()
                {
                    Title    = "复制格式化后的XML文本",
                    SubTitle = abbr(fmt),
                    IcoPath  = "Images\\format.png",
                    Action   = e => {
                        Clipboard.SetDataObject(fmt);
                        return(true);
                    }
                };

                Result zipItem = new Result()
                {
                    Title    = "复制压缩后的XML文本",
                    SubTitle = abbr(zip),
                    IcoPath  = "Images\\zip.png",
                    Action   = e => {
                        Clipboard.SetDataObject(zip);
                        return(true);
                    }
                };

                Result viewItem = new Result()
                {
                    Title   = "在浏览器中查看XML结构",
                    IcoPath = "Images\\browser.png",
                    Action  = e => {
                        File.WriteAllText(Path.Combine(pluginDir, XMLJsFile), "var xmlData=`" + tobs64(fmt) + "`");
                        Process.Start(Path.Combine(pluginDir, XMLHtmlFile));
                        return(true);
                    }
                };
                return(new List <Result> {
                    fmtItem, zipItem, viewItem
                });
            } catch {
                return(null);
            }
        }
예제 #57
0
        private void datagridviewExportAsXml(DataGridView dgv, string FileFullPath)
        {
            string strExamPath = FileFullPath.Substring(0, FileFullPath.LastIndexOf('\\'));
            if (!System.IO.Directory.Exists(strExamPath))
            {
                MessageBox.Show(FileFullPath, "目录错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            DataSet ds4Xml = new DataSet();

            datagridviewToDataSet(dgv, ds4Xml);

            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(FileFullPath, Encoding.UTF8);
            writer.Formatting = System.Xml.Formatting.Indented;
            writer.WriteStartDocument();
            string str = string.Format("type=\"text/xsl\" href=\"{0}.xslt\"", System.IO.Path.GetFileNameWithoutExtension(FileFullPath));
            writer.WriteProcessingInstruction("xml-stylesheet", str);

            ds4Xml.WriteXml(writer);
            writer.Close();
            MessageBox.Show("文件成功保存到了" + FileFullPath, "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
예제 #58
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType     = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int project_uid;
            int pageNo;
            int pageSize;

            int    filterType;
            string filterValue;

            int hideResolved = 0;

            if (int.TryParse(Request.QueryString["project"], out project_uid) == false)
            {
                project_uid = 1;
            }

            if (int.TryParse(Request.QueryString["pageNo"], out pageNo) == false)
            {
                pageNo = 1;
            }

            if (int.TryParse(Request.QueryString["pageSize"], out pageSize) == false)
            {
                pageSize = 30;
            }

            if (int.TryParse(Request.QueryString["filterType"], out filterType) == false)
            {
                filterType = 0;
            }

            filterValue = Request.QueryString["filterValue"];
            if (filterValue == null)
            {
                filterValue = "";
            }

            string  temp1  = Request.QueryString["hideResolved"];
            string  temp2  = Request.QueryString["hideExamination"];
            Boolean check1 = false;
            Boolean check2 = false;

            if (temp1 != null)
            {
                check1 = Boolean.Parse(temp1);
            }
            if (temp2 != null)
            {
                check2 = Boolean.Parse(temp2);
            }
            if (check1 && check2)
            {
                hideResolved = 3;
            }
            else if (check1)
            {
                hideResolved = 1;
            }
            else if (check2)
            {
                hideResolved = 2;
            }

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();

                writer.WriteStartElement("Report");
                writer.WriteAttributeString("project", project_uid.ToString());
                writer.WriteAttributeString("pageNo", pageNo.ToString());
                writer.WriteAttributeString("pageSize", pageSize.ToString());

                writer.WriteStartElement("Items");

                int totalPageSize = 0;
                DB.LoadReport(project_uid, pageNo, pageSize,
                              delegate(int report_uid, string login_id, string ipaddr, DateTime reported_time, string relative_time, int callstack_uid, string funcname, string version, string filename, string assigned, string uservoice, int num_comments)
                {
                    writer.WriteStartElement("Item");

                    writer.WriteAttributeString("report_uid", report_uid.ToString());
                    writer.WriteAttributeString("login_id", login_id);
                    writer.WriteAttributeString("ipaddr", ipaddr);
                    writer.WriteAttributeString("reported_time", reported_time.ToString());
                    writer.WriteAttributeString("relative_time", relative_time);
                    writer.WriteAttributeString("callstack_uid", callstack_uid.ToString());
                    writer.WriteAttributeString("assigned", assigned);
                    writer.WriteAttributeString("num_comments", num_comments.ToString());
                    this.WriteCData(writer, "Funcname", funcname);
                    this.WriteCData(writer, "Version", version);
                    this.WriteCData(writer, "Filename", filename);
                    this.WriteCData(writer, "Uservoice", uservoice);

                    writer.WriteEndElement();
                },
                              out totalPageSize,
                              (DB.ReportWhereFilter)filterType,
                              filterValue,
                              hideResolved
                              );
                writer.WriteEndElement(); // Items

                writer.WriteStartElement("Outputs");
                this.WriteCData(writer, "TotalPageSize", totalPageSize.ToString());
                writer.WriteEndElement(); // Outputs

                writer.WriteEndElement(); // Report
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
예제 #59
0
        /// <summary>
        /// Saves movie trivia to an xml file 
        /// </summary>
        /// <param name="movie">IIMDbMovie object</param>
        /// <param name="xmlPath">path to save xml file to</param>
        /// <param name="overwrite">set to true to overwrite existing xml file</param>
        public void SaveTrivia(
            IIMDbMovie movie,
            string xmlPath,
            bool overwrite)
        {
            System.Xml.XmlTextWriter xmlWr;

            try
            {
                if (System.IO.File.Exists(xmlPath) == false
                    || overwrite)
                    if (movie.Trivia.Count > 0)
                    {
                        xmlWr = new System.Xml.XmlTextWriter(xmlPath, Encoding.Default);
                        xmlWr.Formatting = System.Xml.Formatting.Indented;
                        xmlWr.WriteStartDocument();
                        xmlWr.WriteStartElement("Trivias");
                        foreach (string trivia in movie.Trivia)
                        {
                            xmlWr.WriteElementString("Trivia", trivia);
                        }
                        xmlWr.WriteEndElement();
                        xmlWr.WriteEndDocument();
                        xmlWr.Flush();
                        xmlWr.Close();
                        xmlWr = null;
                    }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #60
0
        /// <summary>
        /// Saves movie quotes to an xml file 
        /// </summary>
        /// <param name="movie">IIMDbMovie object</param>
        /// <param name="xmlPath">path to save xml file to</param>
        /// <param name="overwrite">set to true to overwrite existing xml file</param>
        public void SaveQuotes(
            IIMDbMovie movie,
            string xmlPath,
            bool overwrite)
        {
            System.Xml.XmlTextWriter xmlWr;

            try
            {
                if (System.IO.File.Exists(xmlPath) == false
                    || overwrite)
                    if (movie.Quotes.Count > 0)
                    {
                        xmlWr = new System.Xml.XmlTextWriter(xmlPath, Encoding.Default);
                        xmlWr.Formatting = System.Xml.Formatting.Indented;
                        xmlWr.WriteStartDocument();
                        xmlWr.WriteStartElement("Quotes");
                        foreach (IList<IIMDbQuote> quoteBlock in movie.Quotes)
                        {
                            xmlWr.WriteStartElement("QuoteBlock");
                            foreach (IIMDbQuote quote in quoteBlock)
                            {
                                xmlWr.WriteStartElement("Quote");
                                xmlWr.WriteElementString("Character", quote.Character);
                                xmlWr.WriteElementString("QuoteText", quote.Text);
                                xmlWr.WriteEndElement();
                            }
                            xmlWr.WriteEndElement();
                        }
                        xmlWr.WriteEndElement();
                        xmlWr.WriteEndDocument();
                        xmlWr.Flush();
                        xmlWr.Close();
                        xmlWr = null;
                    }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }