WriteWhitespace() public method

public WriteWhitespace ( string ws ) : void
ws string
return void
Esempio n. 1
0
        static void ExportXMLfile(string XMLfile)
        {
            string filename = XMLfile;

            try
            {
                File.Delete(XMLfile);
            }
            catch
            {
            //        Console.Write(".X2." + XMLfile + ".");
            }

            XmlTextWriter xml = null;

            xml = new XmlTextWriter(filename, null);

            xml.WriteStartDocument();
            xml.WriteStartElement("Features");
            xml.WriteWhitespace("\n");
            xml.WriteElementString("Score", GlobalVar.myScore.ToString());
            xml.WriteWhitespace("\n  ");

            xml.WriteEndElement();
            xml.WriteWhitespace("\n");

            xml.WriteEndDocument();

            //Write the XML to file and close the writer.
            xml.Flush();
            xml.Close();
        }
Esempio n. 2
0
        static void ImportXMLfile(int popMember)
        {
            string filename = "";

            filename = GlobalVar.jobName + GlobalVar.popIndex.ToString() + popMember.ToString();

            XmlTextWriter xml = null;

            xml = new XmlTextWriter(filename, null);

            xml.WriteStartDocument();
            xml.WriteStartElement("Features");
            xml.WriteWhitespace("\n");

            for (int i = 0; i < GlobalVar.featureCount; i++)
            {
                xml.WriteElementString("Index", i.ToString());
                xml.WriteElementString("Value", GlobalVar.features[i].ToString());
                xml.WriteWhitespace("\n  ");
            }

            xml.WriteEndElement();
            xml.WriteWhitespace("\n");

            xml.WriteEndDocument();

            //Write the XML to file and close the writer.
            xml.Flush();
            xml.Close();
        }
Esempio n. 3
0
		public static void Main (string[] args)
		{
			ArrayList problems;

			Validator v = new Validator ();
			Util.Verbosity = Util.DebugLevel.All;
			Util.Inform ("Loaded schema.");
			if (args.Length == 0) {
				Util.Inform ("Reading from standard input.");
				problems = v.ValidateString ("");
			} else {
				problems = v.Validate (args [0]);
			}

			if (XmlOutput) {
				XmlTextWriter w = new XmlTextWriter (Console.Out);
				w.WriteStartDocument ();
				w.WriteStartElement (null, "Problems", null);
				foreach (Problem p in problems)
				{
					w.WriteWhitespace ("\n");
					w.WriteStartElement (null, "Problem", null);

					w.WriteWhitespace ("\n");
					w.WriteStartElement (null, "Test", null);
					w.WriteString (p.Test);
					w.WriteEndElement ();

					w.WriteWhitespace ("\n");
					w.WriteStartElement (null, "Title", null);
					w.WriteString (p.Title);
					w.WriteEndElement ();

					w.WriteWhitespace ("\n");
					w.WriteStartElement (null, "Description", null);
					w.WriteString (p.Description);
					w.WriteEndElement ();

					w.WriteWhitespace ("\n");
					w.WriteStartElement (null, "Detail", null);
					w.WriteString (p.Detail);
					w.WriteEndElement ();

					w.WriteWhitespace ("\n");
					w.WriteEndElement ();
					w.WriteWhitespace ("\n");
				}
				w.WriteEndElement ();
				w.WriteWhitespace ("\n");
				w.WriteEndDocument ();

			} else {
				foreach (Problem p in problems)
				{
					Console.WriteLine (p.Title + " -- " + p.Description);
					Console.WriteLine (p.Detail);
				}
			}
		}
Esempio n. 4
0
        public static void Display()
        {
            // Display the disclaimer
            bool displayDisclaimer = true;

            // Does a settings.xml exist?
            if (File.Exists("settings.xml"))
            {
                try
                {
                    // Load settings.xml and see if we already displayed and the user
                    // agreed to the disclaimer already
                    XmlDocument xml = new XmlDocument();
                    xml.Load("settings.xml");
                    XmlNode node = xml.SelectSingleNode("/settings");
                    displayDisclaimer = (node["disclaimer"].InnerText != "1");
                }
                catch
                {
                }
            }

            // Should we still display the disclaimer?
            if (displayDisclaimer)
            {
                DialogResult result = MessageBox.Show("I will not use this program to cheat online.",
                    "Disclaimer", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

                // The user agreed to it. Now write a settings.xml file and remember that they agreed to it.
                if (result == DialogResult.OK)
                {
                    using (XmlTextWriter writer = new XmlTextWriter("settings.xml", Encoding.ASCII))
                    {
                        writer.WriteStartDocument();
                        writer.WriteWhitespace("\n");
                        writer.WriteStartElement("settings");
                        writer.WriteWhitespace("\n\t");
                        writer.WriteElementString("disclaimer", "1");
                        writer.WriteWhitespace("\n");
                        writer.WriteEndElement();
                        writer.WriteEndDocument();
                    }
                }
                else
                    Environment.Exit(0);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// 创建SiteMap文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="fileName">文件名</param>
        /// <param name="urlList">地址列表</param>
        public static void CreateSiteMap(string path, string fileName, IList<OurUrl> urlList)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            XmlTextWriter xmlWriter = new XmlTextWriter(path + @"/" + fileName, Encoding.UTF8);
            xmlWriter.WriteStartDocument();
            xmlWriter.WriteWhitespace("\n");
            xmlWriter.WriteStartElement("urlset");
            foreach (OurUrl url in urlList)
            {
                xmlWriter.WriteWhitespace("\n  ");
                xmlWriter.WriteStartElement("url");
                xmlWriter.WriteWhitespace("\n    ");

                xmlWriter.WriteStartElement("loc");
                xmlWriter.WriteValue(url.Loc);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteWhitespace("\n    ");

                xmlWriter.WriteStartElement("lastmod");
                xmlWriter.WriteValue(GetLastModString(url.LastMod));
                xmlWriter.WriteEndElement();
                xmlWriter.WriteWhitespace("\n    ");

                xmlWriter.WriteStartElement("changefreq");
                xmlWriter.WriteValue(url.ChangeFreq.ToString().ToLower());
                xmlWriter.WriteEndElement();
                xmlWriter.WriteWhitespace("\n    ");

                xmlWriter.WriteStartElement("priority");
                xmlWriter.WriteValue(url.Priority);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteWhitespace("\n  ");

                xmlWriter.WriteEndElement();
            }
            xmlWriter.WriteWhitespace("\n");
            xmlWriter.WriteEndElement();
            xmlWriter.WriteWhitespace("\n");
            xmlWriter.WriteEndDocument();
            xmlWriter.Flush();
            xmlWriter.Close();
        }
Esempio n. 6
0
        static void ExportXMLfile(string XMLfile)
        {
            string filename = XMLfile;

            try
            {
                File.Delete(XMLfile);
            }
            catch
            {
                Console.Write(".X7." + XMLfile + ".");
            }

            XmlTextWriter xml = null;

            xml = new XmlTextWriter(filename, null);

            xml.WriteStartDocument();
            xml.WriteStartElement("Features");
            xml.WriteWhitespace("\n");

            for (int i = 0; i < GlobalVar.featureCount; i++)
            {
                xml.WriteElementString("Index", i.ToString());
                xml.WriteWhitespace("\n  ");
                xml.WriteElementString("Value", GlobalVar.features[i].ToString());
                xml.WriteWhitespace("\n  ");
            }

            xml.WriteEndElement();
            xml.WriteWhitespace("\n");

            xml.WriteEndDocument();

            //Write the XML to file and close the writer.
            xml.Flush();
            xml.Close();
        }
Esempio n. 7
0
 public void Save(System.Xml.XmlTextWriter x)
 {
     x.WriteWhitespace("\t");
     x.WriteStartElement("Group");
     x.WriteAttributeString("name", Name);
     x.WriteWhitespace("\r\n");
     foreach (Timer timer in Timers)
     {
         x.WriteWhitespace("\t\t");
         x.WriteStartElement("timer");
         x.WriteAttributeString("name", timer.Name);
         x.WriteEndElement();
         x.WriteWhitespace("\r\n");
     }
     foreach (Rate rate in Rates)
     {
         x.WriteWhitespace("\t\t");
         x.WriteStartElement("rate");
         x.WriteAttributeString("value", rate.Value.ToString());
         x.WriteAttributeString("format", rate.Format);
         x.WriteEndElement();
         x.WriteWhitespace("\r\n");
     }
     foreach (Target target in Targets)
     {
         x.WriteWhitespace("\t\t");
         x.WriteStartElement("target");
         x.WriteAttributeString("value", target.Value.ToString());
         x.WriteAttributeString("period", target.Period);
         x.WriteAttributeString("exclude-weekends", target.ExcludeWeekend.ToString());
         x.WriteEndElement();
         x.WriteWhitespace("\r\n");
     }
     x.WriteWhitespace("\t");
     x.WriteEndElement();
     x.WriteWhitespace("\r\n");
 }
Esempio n. 8
0
        public void SaveV1PeakParameters(System.Xml.XmlTextWriter xwriter)
        {
            xwriter.WriteWhitespace("\n\t");
            xwriter.WriteStartElement("PeakParameters");
            xwriter.WriteWhitespace("\n\t\t");

            xwriter.WriteElementString("PeakBackgroundRatio", System.Convert.ToString(this.PeakBackgroundRatio));
            xwriter.WriteWhitespace("\n\t\t");
            xwriter.WriteElementString("SignalToNoiseThreshold", this.SignalToNoiseThreshold.ToString());
            xwriter.WriteWhitespace("\n\t\t");
            xwriter.WriteElementString("PeakFitType", this.PeakFitType.ToString());
            xwriter.WriteWhitespace("\n\t\t");
            xwriter.WriteElementString("WritePeaksToTextFile", this.WritePeaksToTextFile.ToString());

            xwriter.WriteWhitespace("\n\t");
            xwriter.WriteEndElement();
        }
Esempio n. 9
0
        /// <summary>
        /// 创建XML文件
        /// </summary>
        /// <param name="FileName"></param>
        public void CreateXmlFile(string FileName)
        {
            XmlDocument xmldoc = new XmlDocument();
            XmlNode node;
            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(FileName, null);

            node = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
            xmldoc.AppendChild(node);
            writer.WriteWhitespace(System.Environment.NewLine);
            XmlNode root = xmldoc.CreateElement("Data");
            xmldoc.AppendChild(root);
            CreateNode(xmldoc, root, "Address", "127.0.0.1");
            CreateNode(xmldoc, root, "Port", "8087");
            try
            {
                xmldoc.Save(FileName);
                writer.Close();
            }
            catch (Exception ex)
            {
               MessageBox.Show(ex.Message);
            }
        }
Esempio n. 10
0
 // Writes the current node into the provided XmlWriter.
 private void WriteNode(XmlTextWriter xtw, bool defattr) {
     int d = this.NodeType == XmlNodeType.None ? -1 : this.Depth;
     while (this.Read() && (d < this.Depth)) {
         switch (this.NodeType) {
             case XmlNodeType.Element:
                 xtw.WriteStartElement(this.Prefix, this.LocalName, this.NamespaceURI);
                 xtw.QuoteChar = this.QuoteChar;
                 xtw.WriteAttributes(this, defattr);
                 if (this.IsEmptyElement) {
                     xtw.WriteEndElement();
                 }
                 break;
             case XmlNodeType.Text:
                 xtw.WriteString(this.Value);
                 break;
             case XmlNodeType.Whitespace:
             case XmlNodeType.SignificantWhitespace:
                 xtw.WriteWhitespace(this.Value);
                 break;
             case XmlNodeType.CDATA:
                 xtw.WriteCData(this.Value);
                 break;
             case XmlNodeType.EntityReference:
                 xtw.WriteEntityRef(this.Name);
                 break;
             case XmlNodeType.XmlDeclaration:
             case XmlNodeType.ProcessingInstruction:
                 xtw.WriteProcessingInstruction(this.Name, this.Value);
                 break;
             case XmlNodeType.DocumentType:
                 xtw.WriteDocType(this.Name, this.GetAttribute("PUBLIC"), this.GetAttribute("SYSTEM"), this.Value);
                 break;
             case XmlNodeType.Comment:
                 xtw.WriteComment(this.Value);
                 break;
             case XmlNodeType.EndElement:
                 xtw.WriteFullEndElement();
                 break;
         }
     }
     if (d == this.Depth && this.NodeType == XmlNodeType.EndElement) {
         Read();
     }
 }
Esempio n. 11
0
 public void SaveRegions()
 {
     Console.WriteLine("Saving regions...");
     try
     {
         /*File.Delete(Application.StartupPath + "\\permissions.xml");
         File.Create(Application.StartupPath + "\\permissions.xml");*/
         using (var writer = new XmlTextWriter(Statics.SavePath + "\\regions.xml", Encoding.UTF8))
         {
             writer.WriteStartDocument();
             writer.WriteWhitespace("\r\n");
             writer.WriteStartElement("WorldGuard");
             writer.WriteWhitespace("\r\n\t");
             writer.WriteStartElement("Regions");
             foreach (Region region in Regions)
             {
                 writer.WriteWhitespace("\r\n\t\t");
                 writer.WriteStartElement("Region");
                 writer.WriteWhitespace("\r\n\t\t\t");
                 writer.WriteElementString("Name", region.Name);
                 writer.WriteWhitespace("\r\n\t\t\t");
                 writer.WriteElementString("Members", region.Members);
                 writer.WriteWhitespace("\r\n\t\t\t");
                 writer.WriteElementString("Pos1", (int)region.Pos1.X + " " + (int)region.Pos1.Y);
                 writer.WriteWhitespace("\r\n\t\t\t");
                 writer.WriteElementString("Pos2", (int)region.Pos2.X + " " + (int)region.Pos2.Y);
                 writer.WriteWhitespace("\r\n\t\t");
                 writer.WriteEndElement();
             }
             writer.WriteWhitespace("\r\n\t");
             writer.WriteEndElement();
             writer.WriteWhitespace("\r\n");
             writer.WriteEndElement();
             writer.Close();
         }
         Console.WriteLine("Regions saved!");
     }
     catch (Exception ex)
     {
         Console.WriteLine("ERRROR! " + ex.Message + ex.StackTrace);
         return;
     }
 }
        private static void SaveNewBaseLines()
        {
            lock (gate)
            {
                if (_newBaselines != null && !string.IsNullOrEmpty(_newBaseLinePath))
                {
                    using (var writer = new XmlTextWriter(_newBaseLinePath, Encoding.UTF8))
                    {
                        writer.Formatting = Formatting.Indented;
                        writer.Indentation = 2;
                        writer.WriteStartDocument();
                        writer.WriteStartElement("baselines");

                        foreach (var baseLineName in _newBaselines.Keys.OrderBy(x => x))
                        {
                            var baseLineText = _newBaselines[baseLineName];
                            writer.WriteStartElement("baseline");
                            writer.WriteAttributeString("key", baseLineName);
                            writer.WriteWhitespace("\r\n");
                            writer.WriteString(baseLineText);
                            writer.WriteEndElement();
                        }

                        writer.WriteEndDocument();
                    }
                }
            }
        }
 private void btnSave_Click(object sender, RoutedEventArgs e) {
     string path;
     using(SaveFileDialog sfd = new SaveFileDialog()) {
         sfd.Filter = QTUtility.TextResourcesDic["FileFilters"][1] + "|*.xml";
         sfd.RestoreDirectory = true;
         sfd.FileName = "Lng_QTTabBar_" + LangItems[1].Translated + ".xml";
         if(DialogResult.OK != sfd.ShowDialog()) return;
         path = sfd.FileName;
     }
     
     try {
         using(XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8)) {
             writer.WriteStartDocument();
             writer.WriteWhitespace(Environment.NewLine);
             writer.WriteStartElement("root");
             writer.WriteWhitespace(Environment.NewLine);
             for(int i = 0; i < 3; i++) {
                 LangEntry entry = LangItems[i];
                 if(entry.Translated == "") continue;
                 writer.WriteWhitespace(Environment.NewLine);
                 writer.WriteStartElement(entry.Key);
                 writer.WriteWhitespace(Environment.NewLine);
                 writer.WriteValue(entry.Translated);
                 writer.WriteWhitespace(Environment.NewLine);
                 writer.WriteEndElement();
                 writer.WriteWhitespace(Environment.NewLine);
             }
             writer.WriteWhitespace(Environment.NewLine);
             writer.WriteStartElement("Version_QTTabBar");
             writer.WriteWhitespace(Environment.NewLine);
             writer.WriteValue(QTUtility2.MakeVersionString());
             writer.WriteWhitespace(Environment.NewLine);
             writer.WriteEndElement();
             writer.WriteWhitespace(Environment.NewLine);
             writer.WriteWhitespace(Environment.NewLine);
             writer.WriteStartElement("DateModified");
             writer.WriteWhitespace(Environment.NewLine);
             writer.WriteValue(DateTime.Now.ToString("MM/dd/yyyy"));
             writer.WriteWhitespace(Environment.NewLine);
             writer.WriteEndElement();
             writer.WriteWhitespace(Environment.NewLine);
             writer.WriteWhitespace(Environment.NewLine);
             writer.WriteComment(" data start ");
             writer.WriteWhitespace(Environment.NewLine);
             RefInt r = new RefInt { i = 3 };
             while(r.i < LangItems.Count) {
                 string key = LangItems[r.i].Key;
                 string line = GetStrings(key, r).StringJoin(Environment.NewLine);
                 writer.WriteWhitespace(Environment.NewLine);
                 writer.WriteStartElement(key);
                 writer.WriteWhitespace(Environment.NewLine);
                 writer.WriteValue(line);
                 writer.WriteWhitespace(Environment.NewLine);
                 writer.WriteEndElement();
                 writer.WriteWhitespace(Environment.NewLine);                        
             }
             writer.WriteWhitespace(Environment.NewLine);
             writer.WriteComment(" data end ");
             writer.WriteWhitespace(Environment.NewLine);
             writer.WriteWhitespace(Environment.NewLine);
             writer.WriteEndElement();
             writer.WriteWhitespace(Environment.NewLine);
         }
     }
     catch(XmlException) {
         MessageBox.Show(QTUtility.TextResourcesDic["Options_Page13_Language"][10]);
     }
     catch(Exception exception2) {
         QTUtility2.MakeErrorLog(exception2);
     }
 }
Esempio n. 14
0
        /// <summary>
        /// 制作WCFMessage
        ///     实现
        /// ! 生成的2进制xml,序列化时,效果不太一样
        /// TODO 考虑合并到AWcfSrcUrl
        /// </summary>
        /// <param name="dictParam"></param>
        /// <returns></returns>
        public override string MakeWCFMsg(Dictionary<string, string> dictParam)
        {
            //名称
            string name = dictParam[""];

            Encoding utf8 = new UTF8Encoding(false);
            Stream ms = new MemoryStream();
            XmlTextWriter xw = new XmlTextWriter(ms, utf8);
            xw.Namespaces = true;

            xw.WriteStartElement("s:Envelope");
            xw.WriteAttributeString("xmlns:s", "http://www.w3.org/2003/05/soap-envelope");
            xw.WriteAttributeString("xmlns:a", "http://www.w3.org/2005/08/addressing");
            //Header
                xw.WriteStartElement("s:Header");
                    xw.WriteStartElement("a:Action");
                    xw.WriteAttributeString("s:mustUnderstand", "1");
                    xw.WriteString("urn:DataService/" + name);
                    xw.WriteEndElement();

                    xw.WriteStartElement("a:MessageID");
                    xw.WriteString("urn:uuid:eb38dd04-a5ad-424d-abaf-f46c984ee395");
                    xw.WriteEndElement();

                    xw.WriteStartElement("a:SequenceAcknowledgement");
                    xw.WriteStartElement("a:ReplyTo");
                    xw.WriteString("http://www.w3.org/2005/08/addressing/anonymous");
                    xw.WriteEndElement();
                    xw.WriteEndElement();

                    xw.WriteStartElement("a:To");
                    xw.WriteAttributeString("s:mustUnderstand", "1");
                    xw.WriteString("http://zx.bjmemc.com.cn/DataService.svc");
                    xw.WriteEndElement();
                xw.WriteEndElement();
            //body
                xw.WriteStartElement("s:Body");
                    xw.WriteStartElement(name);
                    xw.WriteWhitespace("");
                    xw.WriteEndElement();
                xw.WriteEndElement();
            xw.WriteEndElement();
            xw.Flush();

            byte[] bb = new byte[ms.Length];
            ms.Seek(0, SeekOrigin.Begin);
            ms.Read(bb, 0, (int)ms.Length);

            string strWCFMsg = utf8.GetString(bb);
            return strWCFMsg;
        }
Esempio n. 15
0
        static int ExportXMLfile(string XMLfile)
        {
            XmlTextWriter xml;
            string filename = XMLfile;

            if (File.Exists(XMLfile))
            {
                try
                {
                    File.Delete(XMLfile);
                }
                catch
                {
                    return (1);
                }
            }

             try
            {
                xml = new XmlTextWriter(filename, null);
             }
            catch
            {
                return(1);
            }

             try
             {
                 if (File.Exists(XMLfile))
                 {
                     xml.WriteStartDocument();
                     xml.WriteStartElement("Features");
                     xml.WriteWhitespace("\n");

                     xml.WriteElementString("Score", GlobalVar.myScore.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("Best", GlobalVar.bestScore.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("Pop", GlobalVar.popMember.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("Generation", GlobalVar.myGeneration.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("Active", GlobalVar.activeFeatures.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("LowFreq", GlobalVar.lowFreq.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("LowFreqW", GlobalVar.lowFreqW.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("HighFreq", GlobalVar.highFreq.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("HighFreqW", GlobalVar.highFreqW.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("LowAmp", GlobalVar.lowAmp.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("LowAmpW", GlobalVar.lowAmpW.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("HighAmp", GlobalVar.highAmp.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("HighAmpW", GlobalVar.highAmpW.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("HighNote", GlobalVar.highAmpNote.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("SuperHighs", GlobalVar.highCtr.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("ScoreAll", GlobalVar.scoreAll.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("ScoreCount", GlobalVar.scoreCount.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("samples", GlobalVar.samples.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("frames", GlobalVar.framesThisRun.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("features", GlobalVar.featureCount.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("worstscore", GlobalVar.worstScore.ToString());
                     xml.WriteWhitespace("\n  ");

                     xml.WriteElementString("worstndx", GlobalVar.worstNDX.ToString());
                     xml.WriteWhitespace("\n  ");

              //               xml.WriteElementString("Low Freq", GlobalVar.lowFreq.ToString());
              //               xml.WriteWhitespace("\n  ");
              //               xml.WriteElementString("High Freq", GlobalVar.highFreq.ToString());
              //               xml.WriteWhitespace("\n  ");
              //               xml.WriteElementString("Low Amp", GlobalVar.lowAmp.ToString());
              //               xml.WriteWhitespace("\n  ");
              //               xml.WriteElementString("High Amp", GlobalVar.highAmp.ToString());
              //               xml.WriteWhitespace("\n  ");

                     xml.WriteEndElement();
                     xml.WriteWhitespace("\n");

                     xml.WriteEndDocument();
                 }

            }
            catch
            {
                return(1);
            }

             try
             {
                 //Write the XML to file and close the writer.
                 if (File.Exists(XMLfile))
                 {
                     xml.Flush();
                     xml.Close();
                 }
             }
             catch
             {
                 return (1);
             }

            return (0);
        }
        private void RenderFeed()
        {
            if (siteSettings == null) { return; }
            Argotic.Syndication.RssFeed feed = new Argotic.Syndication.RssFeed();
            RssChannel channel = new RssChannel();
            channel.Generator = "mojoPortal CMS Recent Content Feed Geenrator";
            feed.Channel = channel;

            List<IndexItem> recentContent = GetData(); // gets the data and initilizes the channel params

            if (!shouldRender)
            {
                WebUtils.SetupRedirect(this, redirectUrl);
                return;
            }

            if (channelTitle.Length == 0) { channelTitle = "Recent Content"; } //empty string will cause an error
            channel.Title = channelTitle;
            channel.Link = new System.Uri(channelLink);
            if (channelDescription.Length == 0) { channelDescription = "Recent Content"; } //empty string will cause an error
            channel.Description = channelDescription;
            channel.Copyright = channelCopyright;
            channel.ManagingEditor = channelManagingEditor;
            channel.TimeToLive = channelTimeToLive;

            int itemsAdded = 0;

            if (recentContent != null)
            {
                foreach (IndexItem indexItem in recentContent)
                {
                    RssItem item = new RssItem();
                    string itemUrl = BuildUrl(indexItem);
                    item.Link = new Uri(itemUrl);
                    item.Guid = new RssGuid(itemUrl);
                    item.Title = FormatLinkText(indexItem);
                    item.PublicationDate = indexItem.LastModUtc;
                    item.Author = indexItem.Author;
                    item.Description = indexItem.ContentAbstract;
                    channel.AddItem(item);
                    itemsAdded += 1;

                }
            }

            if (itemsAdded == 0)
            {
                //channel must have at least one item
                RssItem item = new RssItem();
                item.Link = new Uri(siteRoot);
                item.Title = "Stay tuned for future updates. ";
                //item.Description =
                item.PublicationDate = DateTime.UtcNow;

                channel.AddItem(item);

            }

            // no cache locally
            if (Request.Url.AbsolutePath.Contains("localhost"))
            {
                Response.Cache.SetExpires(DateTime.Now.AddMinutes(-30));
                Response.Cache.SetCacheability(HttpCacheability.NoCache);

            }
            else
            {
                Response.Cache.SetExpires(DateTime.Now.AddMinutes(feedCacheTimeInMinutes));
                Response.Cache.SetCacheability(HttpCacheability.Public);
                Response.Cache.VaryByParams["f;gc;n;pageid;mid"] = true;
            }

            Response.ContentType = "application/xml";

            Encoding encoding = new UTF8Encoding();
            Response.ContentEncoding = encoding;

            using (XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding))
            {
                xmlTextWriter.Formatting = Formatting.Indented;

                //////////////////
                // style for RSS Feed viewed in browsers
                if (ConfigurationManager.AppSettings["RSSCSS"] != null)
                {
                    string rssCss = ConfigurationManager.AppSettings["RSSCSS"].ToString();
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/css\" href=\"" + cssBaseUrl + rssCss + "\" ?>");

                }

                if (ConfigurationManager.AppSettings["RSSXsl"] != null)
                {
                    string rssXsl = ConfigurationManager.AppSettings["RSSXsl"].ToString();
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + cssBaseUrl + rssXsl + "\" ?>");

                }
                ///////////////////////////

                feed.Save(xmlTextWriter);

            }
        }
Esempio n. 17
0
		/// <summary>
		/// Produces a formatted string.
		/// </summary>
		/// <param name="loggingEvent">The event being logged.</param>
		/// <param name="writer">The TextWriter to write the formatted event to</param>
		/// <remarks>
		/// <para>
		/// Format the <see cref="LoggingEvent"/> and write it to the <see cref="TextWriter"/>.
		/// </para>
		/// <para>
		/// This method creates an <see cref="XmlTextWriter"/> that writes to the
		/// <paramref name="writer"/>. The <see cref="XmlTextWriter"/> is passed 
		/// to the <see cref="FormatXml"/> method. Subclasses should override the
		/// <see cref="FormatXml"/> method rather than this method.
		/// </para>
		/// </remarks>
		override public void Format(TextWriter writer, LoggingEvent loggingEvent) 
		{
			if (loggingEvent == null)
			{
				throw new ArgumentNullException("loggingEvent");
			}

			// Attach the protected writer to the TextWriter passed in
			m_protectCloseTextWriter.Attach(writer);

			XmlTextWriter xmlWriter = new XmlTextWriter(m_protectCloseTextWriter);
			xmlWriter.Formatting = Formatting.None;
			xmlWriter.Namespaces = false;

			// Write the event to the writer
			FormatXml(xmlWriter, loggingEvent);

			xmlWriter.WriteWhitespace(SystemInfo.NewLine);

			// Close on xmlWriter will ensure xml is flushed
			// the protected writer will ignore the actual close
			xmlWriter.Close();

			// detach from the writer
			m_protectCloseTextWriter.Attach(null);
		}
Esempio n. 18
0
        public void WriteOutMapToXML(ref Classes.MapRecord _glycoMap, string filename, bool printall)
        {
            try
            {
                XmlTextWriter xwriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
                xwriter.Formatting = Formatting.None;
                xwriter.IndentChar = '\t';
                xwriter.Indentation = 1;
                xwriter.WriteStartDocument(true);

                xwriter.WriteWhitespace("\n");
                xwriter.WriteStartElement("GlycoMap");
                xwriter.WriteWhitespace("\n\t");

                int numdatasets = _glycoMap._AssociatedDatasetNames.Count;
                List<string> names = _glycoMap._AssociatedDatasetNames;
                List<string> types = _glycoMap._AssociatedDatasetTypes;

                SpectralUtilities _spectralUtils = new SpectralUtilities();

                _glycoMap._AllMLNRecords.ForEach(delegate(Classes.MultiAlignRecord m)
                 {
                     if ((m.BestMatchProteinName != "") || (!printall))
                     {
                         string gsequence = " ";
                         if ((m.BestMatchGlycanSequence !="") && (m.BestMatchGlycanSequence!= null))
                             gsequence = m.BestMatchGlycanSequence ;

                         xwriter.WriteStartElement("GlycoRecord");
                         xwriter.WriteWhitespace("\n\t\t");

                         //Main Part
                         xwriter.WriteElementString("ID", m.ID.ToString());
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("Mass", m.Mass.ToString());
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("NET", m.NET.ToString());
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("Protein", m.BestMatchProteinName);
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("Peptide", m.BestMatchPeptideSeq);
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("PeptideMass", m.BestMatchPeptideMass.ToString());
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("Site", m.BestMatchNGlycoSite);
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("Glycan", m.BestMatchGlycanComposition);
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("GlycanSequence", gsequence);
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("GlycanMass", m.BestMatchGlycanMass.ToString());
                         xwriter.WriteWhitespace("\n\t\t");
                         string true_false = "TRUE";
                         if (m.BestMatchFalseHit)
                             true_false = "FALSE";
                         xwriter.WriteElementString("TRUE_FALSE", true_false);
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("IDType", m.IDLabel.ToString());
                         xwriter.WriteWhitespace("\n\t\t");

                         // The spectra
                         string repCID = " ";
                         int repCIDLength = 0;
                         if (m._RepresentativeCIDPeaks != null)
                         {
                             repCID = _spectralUtils.EncodePeaks(ref m._RepresentativeCIDPeaks);
                             repCIDLength = m._RepresentativeCIDPeaks.Length;
                         }
                         xwriter.WriteElementString("RepresentativeCIDLength", repCIDLength.ToString());
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("RepresentativeCIDSpectra", repCID);
                         xwriter.WriteWhitespace("\n\t\t");
                         string repHCD = " ";
                         int repHCDLength = 0;
                         if (m._RepresentativeHCDPeaks != null)
                         {
                             repHCD = _spectralUtils.EncodePeaks(ref m._RepresentativeHCDPeaks);
                             repHCDLength = m._RepresentativeHCDPeaks.Length;
                         }
                         xwriter.WriteElementString("RepresentativeHCDLength", repHCDLength.ToString());
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("RepresentativeHCDSpectra", repHCD);
                         xwriter.WriteWhitespace("\n\t\t");
                         string repETD = " ";
                         int repETDLength = 0;
                         if (m._RepresentativeETDPeaks != null)
                         {
                             repETD = _spectralUtils.EncodePeaks(ref m._RepresentativeETDPeaks);
                             repETDLength = m._RepresentativeETDPeaks.Length;
                         }
                         xwriter.WriteElementString("RepresentativeETDLength", repETDLength.ToString());
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("RepresentativeETDSpectra", repETD);
                         xwriter.WriteWhitespace("\n\t\t");

                         // The scores
                         xwriter.WriteElementString("RepCIDScore", m.RepCIDScore.ToString());
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("RepHCDScore", m.RepHCDScore.ToString());
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("RepETDScore", m.RepETDScore.ToString());
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteElementString("RepCIDSequencing", m.RepCIDSequencingScore.ToString());
                         xwriter.WriteWhitespace("\n\t\t");

                         // Print out all datasets but in order of dataset id
                         m._AssociatedUMCRecords.Sort(delegate(Classes.UMCRecord u1, Classes.UMCRecord u2) { return u1.DatasetID.CompareTo(u2.DatasetID); });
                         int count_index = 0;
                         xwriter.WriteStartElement("DatasetInfo");

                         for (int i = 0; i < numdatasets; i++)
                         {
                             xwriter.WriteWhitespace("\n\t\t\t");
                             xwriter.WriteStartElement("DatasetRecord");
                             Classes.UMCRecord u = m._AssociatedUMCRecords[count_index];

                             if (u.DatasetID == i)
                             {
                                 // There is a UMC present, so write it out.
                                 int last_pos = names[i].LastIndexOf("\\");
                                 string dataset_name = names[i].Substring(last_pos + 1); //, names[i].Length);

                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("DatasetID", u.DatasetID.ToString());
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("DatasetName", dataset_name);
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("DatasetType", types[i]);
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("Abundance", u.Abundance.ToString());
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("PrecursorMz", u.UMCRepMz.ToString());
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("PrecursorMass", u.UMCRepMW.ToString());
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("PrecursorCS", u.UMCRepCS.ToString());
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("PrecursorRT", u.UMCElutionTime.ToString());
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("HCDScan", u.HCDScanRep.ToString());
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("HCDScore", u.UMCRepHCDScore.ToString());
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("CIDScan", u.CIDScanRep.ToString());
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("CIDScore", u.UMCRepCIDScore.ToString());
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("ETDScan", u.ETDScanRep.ToString());
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("ETDScore", u.UMCRepETDScore.ToString());
                                 count_index++;
                                 if (count_index >= m._AssociatedUMCRecords.Count)
                                     count_index--; // To keep it within index.
                             }
                             else
                             {
                                 int last_pos = names[i].LastIndexOf("\\");
                                 string dataset_name = names[i].Substring(last_pos + 1); //, names[i].Length);

                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("DatasetID", i.ToString());
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("DatasetName", dataset_name);
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("DatasetType", types[i]);
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("Abundance", Convert.ToString(0));
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("PrecursorMz", Convert.ToString(0));
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("PrecursorMass", Convert.ToString(0));
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("PrecursorCS", Convert.ToString(0));
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("PrecursorRT", Convert.ToString(0));
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("HCDScan", Convert.ToString(0));
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("HCDScore", Convert.ToString(1));
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("CIDScan", Convert.ToString(0));
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("CIDScore", Convert.ToString(0));
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("ETDScan", Convert.ToString(0));
                                 xwriter.WriteWhitespace("\n\t\t\t\t");
                                 xwriter.WriteElementString("ETDScore", Convert.ToString(0));
                             }
                             xwriter.WriteWhitespace("\n\t\t\t");
                             xwriter.WriteEndElement(); // Dataset record

                         }
                         xwriter.WriteWhitespace("\n\t\t");
                         xwriter.WriteEndElement(); //Datasetinfo
                         xwriter.WriteWhitespace("\n\t");
                         xwriter.WriteEndElement(); // glycorecord
                         xwriter.WriteWhitespace("\n\t");
                     }

                 });

                xwriter.WriteEndElement();
                xwriter.WriteEndDocument();
                xwriter.WriteWhitespace("\n");
                xwriter.Close();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Write all the parameters to a text file (xml format);
        /// used for storing settings
        /// </summary>
        /// <param name="filename">relative or absolute filename</param>
        /// <param name="AWithDebugInfo">should internal values be printed, only true for Testing
        /// </param>
        /// <returns>void</returns>
        public void Save(String filename, bool AWithDebugInfo = false)
        {
            XmlTextWriter textWriter;

            // create a file
            textWriter = new XmlTextWriter(filename, null);

            // Opens the document
            textWriter.WriteStartDocument();

            // Write first element
            textWriter.WriteWhitespace(new String((char)10, 1));
            textWriter.WriteStartElement("Parameters");
            textWriter.WriteWhitespace(new String((char)10, 1));

            foreach (TParameter element in Fparameters)
            {
                if (AWithDebugInfo
                    || ((element.paramType != ReportingConsts.CALCULATIONPARAMETERS) && (element.value.ToString() != "rptGrpValue")
                        && (element.value.ToString() != "calculation")))
                {
                    textWriter.WriteWhitespace("  ");
                    textWriter.WriteStartElement("Parameter", "");
                    textWriter.WriteStartAttribute("id", "");
                    textWriter.WriteString(element.name);
                    textWriter.WriteEndAttribute();

                    if (element.column != -1)
                    {
                        textWriter.WriteStartAttribute("column", "");
                        textWriter.WriteString(element.column.ToString());
                        textWriter.WriteEndAttribute();
                    }

                    if (element.level != -1)
                    {
                        textWriter.WriteStartAttribute("level", "");
                        textWriter.WriteString(element.level.ToString());
                        textWriter.WriteEndAttribute();
                    }

                    if (element.subreport != -1)
                    {
                        textWriter.WriteStartAttribute("subreport", "");
                        textWriter.WriteString(element.subreport.ToString());
                        textWriter.WriteEndAttribute();
                    }

                    textWriter.WriteAttributeString("value", element.value.EncodeToString());
                    textWriter.WriteEndElement();
                    textWriter.WriteWhitespace(new String((char)10, 1));
                }
            }

            // Ends the document.
            textWriter.WriteEndDocument();

            // close writer
            textWriter.Close();
        }
Esempio n. 20
0
        private void RenderRss()
        {
            Argotic.Syndication.RssFeed feed = new Argotic.Syndication.RssFeed();
            RssChannel channel = new RssChannel();
            channel.Generator = "mojoPortal Blog Module";

            channel.Language = SiteUtils.GetDefaultCulture();
            feed.Channel = channel;
            if (module.ModuleTitle.Length > 0)
            {
                channel.Title = module.ModuleTitle;
            }
            else
            {
                channel.Title = "Blog"; // it will cause an error if this is left blank so we must populate it if the module title is an emty string.
            }

            // this became broken when we combined query string params, since pageid is not one of the params this always returns the home page url
            // instead of the blog page url
            //string pu = WebUtils.ResolveServerUrl(SiteUtils.GetCurrentPageUrl());

            string pu = WebUtils.ResolveServerUrl(SiteUtils.GetPageUrl(pageSettings));

            channel.Link = new System.Uri(pu);
            channel.SelfLink = Request.Url;

            if (config.ChannelDescription.Length > 0) { channel.Description = config.ChannelDescription; }
            if (config.Copyright.Length > 0) { channel.Copyright = config.Copyright; }

            channel.ManagingEditor = config.ManagingEditorEmail;
            if (config.ManagingEditorName.Length > 0)
            {
                channel.ManagingEditor += " (" + config.ManagingEditorName + ")";
            }

            if (config.FeedTimeToLive > -1) { channel.TimeToLive = config.FeedTimeToLive; }

            //  Create and add iTunes information to feed channel
            ITunesSyndicationExtension channelExtension = new ITunesSyndicationExtension();
            channelExtension.Context.Subtitle = config.ChannelDescription;

            if (config.HasExplicitContent)
            {
                channelExtension.Context.ExplicitMaterial = ITunesExplicitMaterial.Yes;
            }
            else
            {
                channelExtension.Context.ExplicitMaterial = ITunesExplicitMaterial.No;
            }

            channelExtension.Context.Author = config.ManagingEditorEmail;
            if (config.ManagingEditorName.Length > 0)
            {
                channelExtension.Context.Author += " (" + config.ManagingEditorName + ")";
            }
            channelExtension.Context.Summary = config.ChannelDescription;
            channelExtension.Context.Owner = new ITunesOwner(config.ManagingEditorEmail, config.ManagingEditorName);

            if (config.FeedLogoUrl.Length > 0)
            {
                try
                {
                    channelExtension.Context.Image = new Uri(config.FeedLogoUrl);
                }
                catch (ArgumentNullException) { }
                catch (UriFormatException) { }
            }

            if (config.FeedMainCategory.Length > 0)
            {
                ITunesCategory mainCat = new ITunesCategory(config.FeedMainCategory);

                if (config.FeedSubCategory.Length > 0)
                {
                    mainCat.Categories.Add(new ITunesCategory(config.FeedSubCategory));
                }

                channelExtension.Context.Categories.Add(mainCat);
            }

            feed.Channel.AddExtension(channelExtension);

            DataSet dsBlogPosts = GetData();

            DataTable posts = dsBlogPosts.Tables["Posts"];

            foreach (DataRow dr in posts.Rows)
            {
                bool inFeed = Convert.ToBoolean(dr["IncludeInFeed"]);
                if (!inFeed) { continue; }

                RssItem item = new RssItem();

                int itemId = Convert.ToInt32(dr["ItemID"]);
                string blogItemUrl = FormatBlogUrl(dr["ItemUrl"].ToString(), itemId);
                item.Link = new Uri(Request.Url, blogItemUrl);
                item.Guid = new RssGuid(blogItemUrl);
                item.Title = dr["Heading"].ToString();
                item.PublicationDate = Convert.ToDateTime(dr["StartDate"]);

                bool showAuthor = Convert.ToBoolean(dr["ShowAuthorName"]);
                if (showAuthor)
                {

                    // techically this is supposed to be an email address
                    // but wouldn't that lead to a lot of spam?

                    string authorEmail = dr["Email"].ToString();
                    string authorName = dr["Name"].ToString();

                    if (BlogConfiguration.IncludeAuthorEmailInFeed)
                    {
                        item.Author = authorEmail + " (" + authorName + ")";
                    }
                    else
                    {

                        item.Author = authorName;
                    }
                }
                else if (config.ManagingEditorEmail.Length > 0)
                {
                    item.Author = config.ManagingEditorEmail;
                }

                item.Comments = new Uri(blogItemUrl);

                string signature = string.Empty;

                if (config.AddSignature)
                {
                    signature = "<br /><a href='" + blogItemUrl + "'>" + dr["Name"].ToString() + "</a>";
                }

                if ((config.AddCommentsLinkToFeed) && (config.AllowComments))
                {
                    signature += "&nbsp;&nbsp;" + "<a href='" + blogItemUrl + "'>...</a>";
                }

                if (config.AddTweetThisToFeed)
                {
                    signature += GenerateTweetThisLink(item.Title, blogItemUrl);

                }

                if (config.AddFacebookLikeToFeed)
                {
                    signature += GenerateFacebookLikeButton(blogItemUrl);

                }

                string blogPost = SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(navigationSiteRoot, imageSiteRoot, dr["Description"].ToString().RemoveCDataTags());

                string staticMapLink = BuildStaticMapMarkup(dr);

                if (staticMapLink.Length > 0)
                {
                    // add a google static map
                    blogPost += staticMapLink;

                }

                if ((!config.UseExcerptInFeed) || (blogPost.Length <= config.ExcerptLength))
                {
                    item.Description = blogPost + signature;
                }
                else
                {
                    string excerpt = SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(navigationSiteRoot, imageSiteRoot, dr["Abstract"].ToString().RemoveCDataTags());

                    if ((excerpt.Length > 0) && (excerpt != "<p>&#160;</p>"))
                    {
                        excerpt = excerpt
                            + config.ExcerptSuffix
                            + " <a href='"
                            + blogItemUrl + "'>" + config.MoreLinkText + "</a><div class='excerptspacer'>&nbsp;</div>";
                    }
                    else
                    {
                        excerpt = UIHelper.CreateExcerpt(dr["Description"].ToString(), config.ExcerptLength, config.ExcerptSuffix)
                            + " <a href='"
                            + blogItemUrl + "'>" + config.MoreLinkText + "</a><div class='excerptspacer'>&nbsp;</div>"; ;
                    }

                    item.Description = excerpt;

                }

                // how to add media enclosures for podcasting
                //http://www.podcast411.com/howto_1.html

                //http://argotic.codeplex.com/wikipage?title=Generating%20an%20extended%20RSS%20feed

                //http://techwhimsy.com/stream-mp3s-with-google-mp3-player

                //Uri url = new Uri("http://media.libsyn.com/media/podcast411/411_060325.mp3");
                //string type = "audio/mpeg";
                //long length = 11779397;

                string blogGuid = dr["BlogGuid"].ToString();
                string whereClause = string.Format("ItemGuid = '{0}'", blogGuid);

                if (!config.UseExcerptInFeed)
                {

                    DataView dv = new DataView(dsBlogPosts.Tables["Attachments"], whereClause, "", DataViewRowState.CurrentRows);

                    foreach (DataRowView rowView in dv)
                    {
                        DataRow row = rowView.Row;

                        Uri mediaUrl = new Uri(WebUtils.ResolveServerUrl(attachmentBaseUrl + row["ServerFileName"].ToString()));
                        long contentLength = Convert.ToInt64(row["ContentLength"]);
                        string contentType = row["ContentType"].ToString();

                        RssEnclosure enclosure = new RssEnclosure(contentLength, contentType, mediaUrl);
                        item.Enclosures.Add(enclosure);

                        //http://argotic.codeplex.com/wikipage?title=Generating%20an%20extended%20RSS%20feed

                        ITunesSyndicationExtension itemExtension = new ITunesSyndicationExtension();
                        itemExtension.Context.Author = dr["Name"].ToString();
                        itemExtension.Context.Subtitle = dr["SubTitle"].ToString();
                        //itemExtension.Context.Summary = "The iTunes syndication extension properties that are used vary based on whether extending the channel or an item";
                        //itemExtension.Context.Duration = new TimeSpan(1, 2, 13);
                        //itemExtension.Context.Keywords.Add("Podcast");
                        //itemExtension.Context.Keywords.Add("iTunes");

                        whereClause = string.Format("ItemID = '{0}'", itemId);
                        DataView dvCat = new DataView(dsBlogPosts.Tables["Categories"], whereClause, "", DataViewRowState.CurrentRows);

                        foreach (DataRowView rView in dvCat)
                        {
                            DataRow r = rView.Row;

                            item.Categories.Add(new RssCategory(r["Category"].ToString()));

                            itemExtension.Context.Keywords.Add(r["Category"].ToString());

                        }

                        item.AddExtension(itemExtension);
                    }

                }

                channel.AddItem(item);

            }

            if ((config.FeedburnerFeedUrl.Length > 0) || (Request.Url.AbsolutePath.Contains("localhost")))
            {
                Response.Cache.SetExpires(DateTime.Now.AddMinutes(-30));
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Cache.VaryByParams["r"] = true;
            }
            else
            {
                Response.Cache.SetExpires(DateTime.Now.AddMinutes(30));
                Response.Cache.SetCacheability(HttpCacheability.Public);
            }

            Response.ContentType = "application/xml";

            Encoding encoding = new UTF8Encoding();
            Response.ContentEncoding = encoding;

            using (XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding))
            {
                xmlTextWriter.Formatting = Formatting.Indented;

                //////////////////
                // style for RSS Feed viewed in browsers
                if (ConfigurationManager.AppSettings["RSSCSS"] != null)
                {
                    string rssCss = ConfigurationManager.AppSettings["RSSCSS"].ToString();
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/css\" href=\"" + cssBaseUrl + rssCss + "\" ?>");

                }

                if (ConfigurationManager.AppSettings["RSSXsl"] != null)
                {
                    string rssXsl = ConfigurationManager.AppSettings["RSSXsl"].ToString();
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + cssBaseUrl + rssXsl + "\" ?>");

                }
                ///////////////////////////

                feed.Save(xmlTextWriter);

            }
        }
Esempio n. 21
0
        void TempCode()
        {
            string glycanFile = @"C:\development\GlycoFragwork\GlycoFragworkDLL\DLLs\Default_Combination.csv";

            string mlnfile = @"D:\data\GlycoFragwork\Combined\Map\combinedmnl2_map.csv";
            string rawfile1 = @"D:\data\GlycoFragwork\Combined\Raw\combined_101111_111012161157.raw";
            string fastaFile = @"D:\data\Fasta\CombinedMixture.fasta";

            string ttest = @"C:\development\GlycoFragwork\Test\testCombined.xml";
            XmlTextWriter twriter = new XmlTextWriter(ttest, System.Text.Encoding.UTF8);
            twriter.Formatting = Formatting.None;
            twriter.IndentChar = '\t';
            twriter.Indentation = 1;
            twriter.WriteStartDocument(true);
            twriter.WriteWhitespace("\n");
            twriter.WriteStartElement("parameters");
            twriter.WriteWhitespace("\n\t");
            twriter.WriteElementString("version", "1.0");
            twriter.WriteWhitespace("\n\t");
            twriter.WriteStartElement("Input");
            twriter.WriteWhitespace("\n\t\t");
            twriter.WriteElementString("MAPFile", mlnfile);
            twriter.WriteWhitespace("\n\t\t");
            twriter.WriteElementString("GlycanFile", glycanFile);
            twriter.WriteWhitespace("\n\t\t");
            twriter.WriteElementString("FastaFile", fastaFile);
            twriter.WriteWhitespace("\n\t\t");
            twriter.WriteEndElement();
            twriter.WriteWhitespace("\n\t\t");

            twriter.WriteStartElement("RAW");
            twriter.WriteElementString("File", rawfile1);
            twriter.WriteWhitespace("\n\t\t");
            twriter.WriteEndElement();
            twriter.WriteWhitespace("\n\t\t");

            twriter.WriteStartElement("CIDFlags");
            twriter.WriteElementString("CID", true.ToString());
            twriter.WriteWhitespace("\n\t\t");
            twriter.WriteEndElement();
            twriter.WriteWhitespace("\n\t\t");

            twriter.WriteStartElement("HCDFlags");
            twriter.WriteElementString("HCD", true.ToString());
            twriter.WriteWhitespace("\n\t\t");
            twriter.WriteEndElement();
            twriter.WriteWhitespace("\n\t\t");

            twriter.WriteStartElement("ETDFlags");
            twriter.WriteElementString("ETD", true.ToString());
            twriter.WriteWhitespace("\n\t\t");
            twriter.WriteEndElement();
            twriter.WriteWhitespace("\n\t\t");

            twriter.WriteEndElement();
            twriter.WriteEndDocument();
            twriter.WriteWhitespace("\n");
            twriter.Close();
        }
Esempio n. 22
0
        private XmlTextReader PreprocessListItems(XmlTextReader xReader, PipelineContext context)
        {
            TextWriter sWriter = new StringWriter();
            XmlTextWriter xWriter = new XmlTextWriter(sWriter);
            string attrName = "metadataFieldValue";  // Must be same as extension config,  'selector="@metadataFieldValue"'
            string attrValue = "fieldValue";  // default here to confirm GUI DataExtender is working - will update value below

            xReader.MoveToContent();

            while (!xReader.EOF)
            {
                switch (xReader.NodeType)
                {
                    case XmlNodeType.Element:
                        xWriter.WriteStartElement(xReader.Prefix, xReader.LocalName, xReader.NamespaceURI);

                        // add all list attributes back  -- always START with this to NOT break the GUI
                        xWriter.WriteAttributes(xReader, false);

                        try
                        {
                            // add my custom attribute
                            if (IsValidItem(xReader))
                            {
                                string id = xReader.GetAttribute("ID");  // URI
                                TcmUri uri = new TcmUri(id);

                                if (uri.ItemType == ItemType.Component)
                                {
                                    // Do Work Here....
                                    attrValue = "your new value";
                                }

                                // add new metadata field attribute
                                xWriter.WriteAttributeString(attrName, attrValue);
                                xReader.MoveToElement();
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError("EXCEPTION " + ex.Message + ex.ToString() + ex.StackTrace);
                        }

                        if (xReader.IsEmptyElement)
                        {
                            xWriter.WriteEndElement();
                        }
                        break;

                    case XmlNodeType.EndElement:
                        xWriter.WriteEndElement();
                        break;
                    case XmlNodeType.CDATA:
                        // Copy CDATA node  <![CDATA[]]>
                        xWriter.WriteCData(xReader.Value);
                        break;
                    case XmlNodeType.Comment:
                        // Copy comment node <!-- -->
                        xWriter.WriteComment(xReader.Value);
                        break;
                    case XmlNodeType.DocumentType:
                        // Copy XML documenttype
                        xWriter.WriteDocType(xReader.Name, null, null, null);
                        break;
                    case XmlNodeType.EntityReference:
                        xWriter.WriteEntityRef(xReader.Name);
                        break;
                    case XmlNodeType.ProcessingInstruction:
                        xWriter.WriteProcessingInstruction(xReader.Name, xReader.Value);
                        break;
                    case XmlNodeType.SignificantWhitespace:
                        xWriter.WriteWhitespace(xReader.Value);
                        break;
                    case XmlNodeType.Text:
                        xWriter.WriteString(xReader.Value);
                        break;
                    case XmlNodeType.Whitespace:
                        xWriter.WriteWhitespace(xReader.Value);
                        break;
                }
                xReader.Read();
            };

            xWriter.Flush();

            xReader = new XmlTextReader(new StringReader(sWriter.ToString()));
            xReader.MoveToContent();

            //-> Write XML of tcm:Item out...
            //   This is where the attribute in the config file is matched -> selector="@metadataFieldValue"
            // Trace.Write(sWriter.ToString() + Environment.NewLine);
            return xReader;
        }
        /// <summary>
        /// Idea here is to re-create the XmlTextReader Node and this accounts for 50% of the code.
        /// Original code borrowed from http://www.sdltridionworld.com/community/2011_extensions/parentchangenotifier.aspx
        /// Thanks for the work from Serguei Martchenko - would not be possible without his example!
        /// </summary>
        /// <param name="xReader"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private XmlTextReader PreprocessListItems(XmlTextReader xReader, PipelineContext context)
        {
            TextWriter sWriter = new StringWriter();
            XmlTextWriter xWriter = new XmlTextWriter(sWriter);
            string attrName = "metadataFieldValue";
            string attrValue = "";  // set this to 'fieldValue', for example, to debug and prove it is working

            xReader.MoveToContent();

            using(var tdse = new TDSEWrapper())
            {
                while (!xReader.EOF)
                {
                    switch (xReader.NodeType)
                    {
                        case XmlNodeType.Element:
                            xWriter.WriteStartElement(xReader.Prefix, xReader.LocalName, xReader.NamespaceURI);

                            // add all attributes back  -- always START with this to NOT break the GUI
                            xWriter.WriteAttributes(xReader, false);

                            try
                            {
                                // add my custom attribute
                                if (IsValidItem(xReader))
                                {
                                    string id = xReader.GetAttribute("ID");  // URI
                                    TcmUri uri = new TcmUri(id);

                                    if (uri.ItemType == ItemType.Component)
                                    {
                                        // Get Metadata Value
                                        // 0 seconds with no processing
                                        // 12 seconds for 250 Components with TOM API, Component.MetadataFields...
                                        // 12 seconds for 250 Components with Core Service
                                        // 2 seconds for 250 Components with TOM API and GetXML  (FASTEST!)

                                        // Core Service
                                        //attrValue = GetMetadataValue(fieldName, id);

                                        // TDSE...Fastest with GetXML
                                        Component comp = tdse.TDSE.GetObject(id, Tridion.ContentManager.Interop.TDSDefines.EnumOpenMode.OpenModeView) as Component;
                                        attrValue = GetMetadataValue(comp, "article_number");
                                    }

                                    // add new metadata field attribute
                                    xWriter.WriteAttributeString(attrName, attrValue);
                                    xReader.MoveToElement();
                                }
                            }
                            catch (Exception ex)
                            {
                                Trace.TraceError("EXCEPTION " + ex.Message + ex.ToString() + ex.StackTrace);
                            }

                            if (xReader.IsEmptyElement)
                            {
                                xWriter.WriteEndElement();
                            }
                            break;

                        case XmlNodeType.EndElement:
                            xWriter.WriteEndElement();
                            break;
                        case XmlNodeType.CDATA:
                            // Copy CDATA node  <![CDATA[]]>
                            xWriter.WriteCData(xReader.Value);
                            break;
                        case XmlNodeType.Comment:
                            // Copy comment node <!-- -->
                            xWriter.WriteComment(xReader.Value);
                            break;
                        case XmlNodeType.DocumentType:
                            // Copy XML documenttype
                            xWriter.WriteDocType(xReader.Name, null, null, null);
                            break;
                        case XmlNodeType.EntityReference:
                            xWriter.WriteEntityRef(xReader.Name);
                            break;
                        case XmlNodeType.ProcessingInstruction:
                            xWriter.WriteProcessingInstruction(xReader.Name, xReader.Value);
                            break;
                        case XmlNodeType.SignificantWhitespace:
                            xWriter.WriteWhitespace(xReader.Value);
                            break;
                        case XmlNodeType.Text:
                            xWriter.WriteString(xReader.Value);
                            break;
                        case XmlNodeType.Whitespace:
                            xWriter.WriteWhitespace(xReader.Value);
                            break;
                    }
                    xReader.Read();
                };
            }
            xWriter.Flush();

            xReader = new XmlTextReader(new StringReader(sWriter.ToString()));
            xReader.MoveToContent();
            //-> Write XML of tcm:Item out...
            //   This is where the attribute in the config file is matched.
            // Trace.Write(sWriter.ToString() + Environment.NewLine);
            return xReader;
        }
Esempio n. 24
0
		private static void CreateXmlKeyFile(string strFile, byte[] pbKeyData)
		{
			Debug.Assert(strFile != null);
			if(strFile == null) throw new ArgumentNullException("strFile");
			Debug.Assert(pbKeyData != null);
			if(pbKeyData == null) throw new ArgumentNullException("pbKeyData");

			XmlTextWriter xtw = new XmlTextWriter(strFile, new UTF8Encoding(false));

			xtw.WriteStartDocument();
			xtw.WriteWhitespace("\r\n");
			xtw.WriteStartElement(RootElementName); // KeyFile
			xtw.WriteWhitespace("\r\n\t");

			xtw.WriteStartElement(MetaElementName); // Meta
			xtw.WriteWhitespace("\r\n\t\t");
			xtw.WriteStartElement(VersionElementName); // Version
			xtw.WriteString("1.00");
			xtw.WriteEndElement(); // End Version
			xtw.WriteWhitespace("\r\n\t");
			xtw.WriteEndElement(); // End Meta
			xtw.WriteWhitespace("\r\n\t");

			xtw.WriteStartElement(KeyElementName); // Key
			xtw.WriteWhitespace("\r\n\t\t");

			xtw.WriteStartElement(KeyDataElementName); // Data
			xtw.WriteString(Convert.ToBase64String(pbKeyData));
			xtw.WriteEndElement(); // End Data
			xtw.WriteWhitespace("\r\n\t");

			xtw.WriteEndElement(); // End Key
			xtw.WriteWhitespace("\r\n");

			xtw.WriteEndElement(); // RootElementName
			xtw.WriteWhitespace("\r\n");
			xtw.WriteEndDocument(); // End KeyFile
			xtw.Close();
		}
 public void Save( IEnumerable<OnlineTransaction> transactions )
 {
     StreamWriter writer = File.CreateText( filename );
     try
     {
         XmlTextWriter xmlWriter = new XmlTextWriter( writer );
         try
         {
             xmlWriter.WriteStartDocument();
             xmlWriter.WriteWhitespace( Environment.NewLine );
             xmlWriter.WriteStartElement( "Online" );
             xmlWriter.WriteWhitespace( Environment.NewLine );
             foreach( OnlineTransaction otrans in transactions )
             {
                 SerializeTransaction( xmlWriter, otrans );
                 xmlWriter.WriteWhitespace( Environment.NewLine );
             }
             xmlWriter.WriteEndElement(); // </Online>
             xmlWriter.WriteWhitespace( Environment.NewLine );
             xmlWriter.WriteEndDocument();
         }
         finally
         {
             xmlWriter.Close();
         }
     }
     finally
     {
         writer.Close();
     }
 }
Esempio n. 26
0
        public void OpenXmlReportFile(string sReportFile, string sFontFile)
        {

            Stream stream;

            try
            {
                stream = new FileStream(sReportFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            }
            catch (IOException)
            {
                // This error needs to abort for the command line
                // driver, since we are not viewing afterwards.
                Console.WriteLine("Could not open the report file. Not outputting report");
                stream = new MemoryStream(); //Just dumping into memory, later this is thrown away
            }

            m_xmlWriter = new XmlTextWriter(stream, 
                                                System.Text.Encoding.UTF8);
            m_xmlWriter.WriteStartDocument();
            m_xmlWriter.WriteWhitespace("\r\n");
            string type = "type=\"text/xsl\" href=\"fval.xsl\"";
            m_xmlWriter.WriteProcessingInstruction("xml-stylesheet", type );
            m_xmlWriter.WriteWhitespace("\r\n");
            m_xmlWriter.WriteStartElement("FontValidatorReport");
            string dateAndTime = System.DateTime.Now.ToString("f", null);
            m_xmlWriter.WriteAttributeString("RunDateTime", dateAndTime );
            m_xmlWriter.WriteAttributeString("MachineName", 
                                             SystemInformation.ComputerName);
            m_xmlWriter.WriteWhitespace("\r\n");

            FileInfo fi = new FileInfo(sFontFile);

            m_xmlWriter.WriteStartElement("FontFile");
            m_xmlWriter.WriteAttributeString("FileName", fi.Name);
            m_xmlWriter.WriteAttributeString("FileNameAndPath", sFontFile);
            m_xmlWriter.WriteWhitespace("\r\n");
        }
Esempio n. 27
0
File: doc.cs Progetto: royleban/mono
		//
		// Outputs XML documentation comment from tokenized comments.
		//
		public bool OutputDocComment (string asmfilename, string xmlFileName)
		{
			XmlTextWriter w = null;
			try {
				w = new XmlTextWriter (xmlFileName, null);
				w.Indentation = 4;
				w.Formatting = Formatting.Indented;
				w.WriteStartDocument ();
				w.WriteStartElement ("doc");
				w.WriteStartElement ("assembly");
				w.WriteStartElement ("name");
				w.WriteString (Path.GetFileNameWithoutExtension (asmfilename));
				w.WriteEndElement (); // name
				w.WriteEndElement (); // assembly
				w.WriteStartElement ("members");
				XmlCommentOutput = w;
				module.GenerateDocComment (this);
				w.WriteFullEndElement (); // members
				w.WriteEndElement ();
				w.WriteWhitespace (Environment.NewLine);
				w.WriteEndDocument ();
				return true;
			} catch (Exception ex) {
				Report.Error (1569, "Error generating XML documentation file `{0}' (`{1}')", xmlFileName, ex.Message);
				return false;
			} finally {
				if (w != null)
					w.Close ();
			}
		}
 public string WriteThemeXmlFile()
 {
     string a = "";
     using (StringWriter str = new StringWriter())
     {
         using (XmlTextWriter xml = new XmlTextWriter(str))
         {
             xml.WriteStartDocument();
             xml.WriteWhitespace("\r\n");
             xml.WriteStartElement("RibbonColorTheme");
             xml.WriteWhitespace("\r\n\t");
             xml.WriteStartElement("Properties");
             xml.WriteWhitespace("\r\n\t\t");
             xml.WriteElementString("ThemeName", ThemeName);
             xml.WriteWhitespace("\r\n\t\t");
             xml.WriteElementString("Author", ThemeAuthor);
             xml.WriteWhitespace("\r\n\t\t");
             xml.WriteElementString("AuthorEmail", ThemeAuthorEmail);
             xml.WriteWhitespace("\r\n\t\t");
             xml.WriteElementString("AuthorWebsite", ThemeAuthorWebsite);
             xml.WriteWhitespace("\r\n\t\t");
             xml.WriteElementString("DateCreated", ThemeDateCreated);
             xml.WriteWhitespace("\r\n\t");
             xml.WriteEndElement();
             xml.WriteWhitespace("\r\n\t");
             xml.WriteStartElement("ColorTable");
             int count = Enum.GetNames(typeof(RibbonColorPart)).Length;
             for (int i = 0; i < count; i++)
             {
                 xml.WriteWhitespace("\r\n\t\t");
                 xml.WriteElementString(((RibbonColorPart)i).ToString(), GetColorHexStr((RibbonColorPart)i));
             }
             xml.WriteWhitespace("\r\n\t");
             xml.WriteEndElement(); xml.WriteWhitespace("\r\n");
             xml.WriteEndElement(); xml.WriteWhitespace("\r\n");
             xml.WriteEndDocument();
         }
         a = str.ToString();
     }
     return a;
 }
Esempio n. 29
0
 public static void SavePermissions()
 {
     try
     {
         /*File.Delete(Application.StartupPath + "\\permissions.xml");
         File.Create(Application.StartupPath + "\\permissions.xml");*/
         using (var writer = new XmlTextWriter(Statics.SavePath + "\\permissions.xml", Encoding.UTF8))
         {
             writer.WriteStartDocument();
             writer.WriteWhitespace("\r\n");
             writer.WriteStartElement("Permissions");
             writer.WriteWhitespace("\r\n\t");
             writer.WriteStartElement("Groups");
             foreach (GroupPermissions group in Groups)
             {
                 writer.WriteWhitespace("\r\n\t\t");
                 writer.WriteStartElement("Group");
                 writer.WriteWhitespace("\r\n\t\t\t");
                 writer.WriteElementString("Name", group.Name);
                 writer.WriteWhitespace("\r\n\t\t\t");
                 writer.WriteElementString("Color", group.ColorR + " " + group.ColorG + " " + group.ColorB);
                 writer.WriteWhitespace("\r\n\t\t\t");
                 writer.WriteElementString("Prefix", group.Prefix);
                 foreach (string nodes in group.Nodes)
                 {
                     writer.WriteWhitespace("\r\n\t\t\t");
                     writer.WriteElementString("Node", nodes);
                 }
                 writer.WriteWhitespace("\r\n\t\t");
                 writer.WriteEndElement();
             }
             writer.WriteWhitespace("\r\n\t");
             writer.WriteEndElement();
             writer.WriteWhitespace("\r\n\t");
             writer.WriteStartElement("Players");
             foreach (PlayerPermissions ply in Players)
             {
                 writer.WriteWhitespace("\r\n\t\t");
                 writer.WriteStartElement("Player");
                 writer.WriteWhitespace("\r\n\t\t\t");
                 writer.WriteElementString("Name", ply.Name);
                 writer.WriteWhitespace("\r\n\t\t\t");
                 writer.WriteElementString("Group", ply.Group);
                 foreach (string node in ply.Nodes)
                 {
                     writer.WriteWhitespace("\r\n\t\t\t");
                     writer.WriteElementString("Node", node);
                 }
                 writer.WriteWhitespace("\r\n\t\t");
                 writer.WriteEndElement();
             }
             writer.WriteWhitespace("\r\n\t");
             writer.WriteEndElement();
             writer.WriteWhitespace("\r\n");
             writer.WriteEndElement();
             writer.Close();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("ERROR! " + ex.Message + ex.StackTrace);
         /*Console.Out("Press any key to exit...");
         System.Console.ReadKey(true);
         Environment.Exit(0);*/
     }
 }
Esempio n. 30
0
        private static void CreateXmlKeyFile(string strFile, byte[] pbKeyData)
        {
            Debug.Assert(strFile != null);
            if(strFile == null) throw new ArgumentNullException("strFile");
            Debug.Assert(pbKeyData != null);
            if(pbKeyData == null) throw new ArgumentNullException("pbKeyData");

            IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile);
            Stream sOut = IOConnection.OpenWrite(ioc);

            #if KeePassUAP
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.Encoding = StrUtil.Utf8;
            xws.Indent = false;

            XmlWriter xtw = XmlWriter.Create(sOut, xws);
            #else
            XmlTextWriter xtw = new XmlTextWriter(sOut, StrUtil.Utf8);
            #endif

            xtw.WriteStartDocument();
            xtw.WriteWhitespace("\r\n");
            xtw.WriteStartElement(RootElementName); // KeyFile
            xtw.WriteWhitespace("\r\n\t");

            xtw.WriteStartElement(MetaElementName); // Meta
            xtw.WriteWhitespace("\r\n\t\t");
            xtw.WriteStartElement(VersionElementName); // Version
            xtw.WriteString("1.00");
            xtw.WriteEndElement(); // End Version
            xtw.WriteWhitespace("\r\n\t");
            xtw.WriteEndElement(); // End Meta
            xtw.WriteWhitespace("\r\n\t");

            xtw.WriteStartElement(KeyElementName); // Key
            xtw.WriteWhitespace("\r\n\t\t");

            xtw.WriteStartElement(KeyDataElementName); // Data
            xtw.WriteString(Convert.ToBase64String(pbKeyData));
            xtw.WriteEndElement(); // End Data
            xtw.WriteWhitespace("\r\n\t");

            xtw.WriteEndElement(); // End Key
            xtw.WriteWhitespace("\r\n");

            xtw.WriteEndElement(); // RootElementName
            xtw.WriteWhitespace("\r\n");
            xtw.WriteEndDocument(); // End KeyFile
            xtw.Close();

            sOut.Close();
        }
Esempio n. 31
0
        public bool Append(params HistoryItem[] historyItems)
        {
            if (!string.IsNullOrEmpty(FilePath))
            {
                lock (thisLock)
                {
                    Helpers.CreateDirectoryFromFilePath(FilePath);

                    using (FileStream fs = File.Open(FilePath, FileMode.Append, FileAccess.Write, FileShare.Read))
                    using (XmlTextWriter writer = new XmlTextWriter(fs, Encoding.UTF8))
                    {
                        writer.Formatting = Formatting.Indented;
                        writer.Indentation = 4;

                        foreach (HistoryItem historyItem in historyItems)
                        {
                            writer.WriteStartElement("HistoryItem");
                            writer.WriteElementIfNotEmpty("Filename", historyItem.Filename);
                            writer.WriteElementIfNotEmpty("Filepath", historyItem.Filepath);
                            writer.WriteElementIfNotEmpty("DateTimeUtc", historyItem.DateTime.ToString("o"));
                            writer.WriteElementIfNotEmpty("Type", historyItem.Type);
                            writer.WriteElementIfNotEmpty("Host", historyItem.Host);
                            writer.WriteElementIfNotEmpty("URL", historyItem.URL);
                            writer.WriteElementIfNotEmpty("ThumbnailURL", historyItem.ThumbnailURL);
                            writer.WriteElementIfNotEmpty("DeletionURL", historyItem.DeletionURL);
                            writer.WriteElementIfNotEmpty("ShortenedURL", historyItem.ShortenedURL);
                            writer.WriteEndElement();
                        }

                        writer.WriteWhitespace(Environment.NewLine);
                    }
                }

                return true;
            }

            return false;
        }
Esempio n. 32
0
		private static bool SaveFile(string strFile)
		{
			if(strFile == null) return false;

			XmlTextWriter xtw;
			try { xtw = new XmlTextWriter(strFile, Encoding.UTF8); }
			catch(Exception) { return false; }
			Debug.Assert(xtw != null); if(xtw == null) return false;

			xtw.WriteStartDocument();
			xtw.WriteWhitespace("\r\n");
			xtw.WriteStartElement(RootElementName);
			xtw.WriteWhitespace("\r\n");

			Debug.Assert(m_cfgCurrent != null);
			foreach(KeyValuePair<string, string> kvp in m_cfgCurrent)
			{
				xtw.WriteWhitespace("\t");
				xtw.WriteStartElement(ConfigItemElement);
				xtw.WriteAttributeString(ConfigItemName, kvp.Key);

				// xtw.WriteAttributeString(ConfigItemValue, kvp.Value);
				xtw.WriteString(kvp.Value);
				
				xtw.WriteEndElement();
				xtw.WriteWhitespace("\r\n");
			}

			xtw.WriteEndElement();
			xtw.WriteWhitespace("\r\n");
			xtw.WriteEndDocument();
			xtw.Close();

			return true;
		}