Beispiel #1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        DateTime now = DateTime.Now;
        Organization org = Organization.FromIdentity(Int32.Parse(Request.QueryString["OrganizationId"]));

        ExternalActivities activities = ExternalActivities.ForOrganization(org);
        activities.Sort(ExternalActivities.SortOrder.DateDescending);

        Response.ContentType = "text/xml";

        XmlWriter xml = new XmlTextWriter(Response.Output);
        RssWriter rss = new RssWriter(xml);

        rss.WriteHeader("Aktivism - " + org.Name, "http://www.piratpartiet.se", "Aktivism för Piratpartiet", null);

        foreach (ExternalActivity activism in activities)
        {
            string title = "Aktivism i " + activism.Geography.Name;
            if (title.Length > 60)
            {
                title = title.Substring(0, 57) + "...";
            }

            rss.WriteItem(title, "<img src=\"http://data.piratpartiet.se/Handlers/DisplayActivism.aspx?Id=" + activism.Identity.ToString() + "\" />", new Uri("http://data.piratpartiet.se/Handlers/DisplayActivism.aspx?Id=" + activism.Identity), activism.CreatedDateTime);
        }

        rss.Close();
        xml.Close();
    }
Beispiel #2
0
 static int Main(string[] args)
 {
     int result = 0;
       if (args.Length == 0)
       {
        Console.WriteLine("USAGE: GenerateWsdl.exe [Assembly] [Type] [URL] [File]");
        result = -1;;
       }
       else
       {
        try
        {
     Assembly assembly = Assembly.LoadFrom(args[0]);
     Type type = assembly.GetType(args[1]);
     ServiceDescriptionReflector reflector = new ServiceDescriptionReflector();
     reflector.Reflect(type, args[2]);
     XmlTextWriter writer = new XmlTextWriter(args[3], Encoding.ASCII);
     writer.Formatting = Formatting.Indented;
     reflector.ServiceDescriptions[0].Write(writer);
     writer.Close();
        }
        catch(Exception ex)
        {
     Console.Error.WriteLine(ex);
     result = -1;
        }
       }
       return result;
 }
    public void Action() {   
        string xml = "<?xml version=\"1.0\"?>\n<a><b c=\"d\">e</b></a>";
        string xsl = "<?xml version=\"1.0\"?>\n" +
            "<xsl:stylesheet version=\"1.0\" " +
                    "xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" " +
                    "xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\" " +
                    "xmlns:js=\"urn:js\" " +
                ">" +
                "<msxsl:script language=\"jsCrIpt\" implements-prefix=\"js\">" +
                    "function SimpleTest() { return \"JScript test\"; }" +        
                "</msxsl:script>" +                
                "<xsl:template match=\"a\"><foo><xsl:apply-templates/></foo></xsl:template>" +
                "<xsl:template match=\"b\"><xsl:element name=\"bar\">" +
        	        "<xsl:attribute name=\"simpleTest\"><xsl:value-of select=\"js:SimpleTest()\"/></xsl:attribute>" +
                "</xsl:element></xsl:template>" +
                "<xsl:template match=\"/\"><xsl:apply-templates/></xsl:template>" +
            "</xsl:stylesheet>";            
    
        XPathDocument myXPathDocument = new XPathDocument(new XmlTextReader(new StringReader(xml)));

        XslTransform myXslTransform = new XslTransform();
        myXslTransform.Load(new XmlTextReader(new StringReader(xsl)));
        
        StringWriter myStringWriter = new StringWriter();
        XmlTextWriter myXmlWriter = new XmlTextWriter(myStringWriter);
        myXmlWriter.Formatting = Formatting.Indented;
        
        myXslTransform.Transform(myXPathDocument, null, myXmlWriter);
        myXmlWriter.Close();        
        
        Console.WriteLine(myStringWriter.ToString());
    }
Beispiel #4
0
	public void DumpArrayToXml ()
	{
		string metadata_filename = dir + Path.DirectorySeparatorChar + "album-data.xml";

		XmlTextWriter writer = new XmlTextWriter (metadata_filename, Encoding.UTF8);

		writer.WriteStartDocument (true);
		writer.WriteStartElement ("album", "www.ximian.com");
		writer.WriteAttributeString ("name", album_name);
	        writer.WriteAttributeString ("count", picture_count.ToString ());

		for (int i = 0; i < picture_count; ++i) {
			writer.WriteStartElement ("picture", "www.ximian.com");

			writer.WriteElementString ("location", "www.ximian.com", picture_data [i].Location);
			writer.WriteElementString ("title", "www.ximian.com", picture_data [i].Title);
			writer.WriteElementString ("date", "www.ximian.com", picture_data [i].Date);
			writer.WriteElementString ("keywords", "www.ximian.com", picture_data [i].Keywords);
			writer.WriteElementString ("comments", "www.ximian.com", picture_data [i].Comments);
			writer.WriteElementString ("index", "www.ximian.com", picture_data [i].Index.ToString ());
			
			writer.WriteEndElement ();
		}

		writer.WriteEndElement ();
		writer.WriteEndDocument ();
		writer.Close ();
	}
    protected void Page_Load(object sender, EventArgs e)
    {
        DateTime now = DateTime.Now;

        MediaEntries entries = (MediaEntries) Cache.Get(cacheKey);

        if (entries == null)
        {
            entries = MediaEntries.FromBlogKeyword("Piratpartiet", now.AddDays(-7));
            Cache.Insert(cacheKey, entries, null, DateTime.UtcNow.AddMinutes (5) , System.Web.Caching.Cache.NoSlidingExpiration); // five minute cache is plenty to prevent db F5 attacks
        }
      
        Response.ContentType = "text/xml";

        XmlWriter xml = new XmlTextWriter(Response.Output);
        RssWriter rss = new RssWriter(xml);

        rss.WriteHeader("Bloggat om Piratpartiet", "http://www.piratpartiet.se", "Bloggposter som nämner Piratpartiet", null);

        foreach (MediaEntry entry in entries)
        {
            string title = entry.Title;
            if (title.Length > 30)
            {
                title = title.Substring(0, 27) + "...";
            }

            rss.WriteItem(title, string.Empty, new Uri (entry.Url), entry.DateTime);
        }

        rss.Close();
        xml.Close();
    }
Beispiel #6
0
        public static void createErrorLogger()
        {
            XmlTextWriter xmlTextWriter = (XmlTextWriter)null;

            try
            {
                if (!Directory.Exists(ErrorLogger.xmlFolder))
                {
                    Directory.CreateDirectory(ErrorLogger.xmlFolder);
                }
                if (File.Exists(ErrorLogger.xmlFilePath))
                {
                    return;
                }
                xmlTextWriter            = new XmlTextWriter(ErrorLogger.xmlFilePath, (Encoding)null);
                xmlTextWriter.Formatting = Formatting.Indented;
                xmlTextWriter.WriteStartDocument(false);
                xmlTextWriter.WriteComment("Scoreboardregie application error logger");
                xmlTextWriter.WriteStartElement(nameof(ErrorLogger));
                xmlTextWriter.WriteEndElement();
                xmlTextWriter.Flush();
                xmlTextWriter.Close();
            }
            catch (Exception ex)
            {
                ErrorLogger.displayErrorMessage(ex);
            }
            finally
            {
                xmlTextWriter?.Close();
            }
        }
    protected void btnLahetaPalaute_Click(object sender, EventArgs e)
    {
        string filename = MapPath("~/App_Data/Palautteet.xml");

        XmlDocument doc = new XmlDocument();

        doc.Load(filename);

        XmlElement newElem = doc.CreateElement("palaute");

        newElem.InnerXml = "<pvm>" + this.tbxPvm.Text + "</pvm>" +
            "<tekija>" + this.tbxNimi.Text + "</tekija>" +
            "<opittu>" + this.tbxOlenOppinut.Text + "</opittu>" +
            "<haluanoppia>" + this.tbxHaluanOppia.Text + "</haluanoppia>" +
            "<hyvaa>" + this.tbxHyvaa.Text + "</hyvaa>" +
            "<parannettavaa>" + this.tbxHuonoa.Text + "</parannettavaa>" +
            "<muuta>" + this.tbxMuuta.Text + "</muuta>";

        doc.DocumentElement.SelectNodes("/palautteet")[0].AppendChild(newElem);

        XmlWriter w = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
        doc.WriteTo(w);
        w.Close();

        this.tbxPvm.Text = "";
        this.tbxNimi.Text = "";
        this.tbxOlenOppinut.Text = "";
        this.tbxHaluanOppia.Text = "";
        this.tbxHyvaa.Text = "";
        this.tbxHuonoa.Text = "";
        this.tbxMuuta.Text = "";
    }
Beispiel #8
0
        /// <summary>
        /// Creates a new writer for markup languages with specified stream.
        /// </summary>
        /// <param name="stream">input stream.</param>
        private void CreateWriter(Stream stream)
        {
            XmlTextWriter tempWriter = null;

            try
            {
                tempWriter = new XmlTextWriter(stream, Encoding.UTF8);

                YesNo indented;
                var   behaviors             = Provider.Input.Model.Table.Exporter.Behaviors;
                var   transformFileBehavior = behaviors.Get <TransformFileBehaviorModel>();
                if (transformFileBehavior == null)
                {
                    var transformBehavior = new TransformFileBehaviorModel();
                    indented = transformBehavior.Indented;
                }
                else
                {
                    indented = transformFileBehavior.Indented;
                }

                if (indented == YesNo.Yes)
                {
                    tempWriter.Formatting = Formatting.Indented;
                }

                Writer     = tempWriter;
                tempWriter = null;
            }
            finally
            {
                tempWriter?.Close();
            }
        }
Beispiel #9
0
        public static string Serialize <T>(T obj) where T : new()
        {
            if (obj == null)
            {
                obj = new T();
            }
            string        result        = "";
            XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
            MemoryStream  memoryStream  = new MemoryStream();
            XmlTextWriter xmlTextWriter = null;
            StreamReader  streamReader  = null;

            try
            {
                xmlTextWriter            = new XmlTextWriter(memoryStream, Encoding.UTF8);
                xmlTextWriter.Formatting = Formatting.Indented;
                xmlSerializer.Serialize(xmlTextWriter, obj);
                memoryStream.Seek(0L, SeekOrigin.Begin);
                streamReader = new StreamReader(memoryStream);
                result       = streamReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                xmlTextWriter?.Close();
                streamReader?.Close();
                memoryStream.Close();
            }
            return(result);
        }
Beispiel #10
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();
        Response.ContentType = "text/xml";
        XmlTextWriter objX = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
        objX.WriteStartDocument();
        objX.WriteStartElement("rss");
        objX.WriteAttributeString("version", "2.0");
        objX.WriteStartElement("channel");
        objX.WriteElementString("title", drvvv.Plugins.GetTextToSite("Anglodeals", "francodeals", "zebradeals"));
        objX.WriteElementString("link", "http://anglodeals.co.il/rss.aspx");
        objX.WriteElementString("description", "At  Deals we compile the best coupons from both English and Hebrew anf franch websites daily, translate what is needed and put them up on one user-friendly website.");
        objX.WriteElementString("copyright", "(c) 2012, anglodeals. All rights reserved.");
        //objX.WriteElementString("ttl", "5");

        foreach (var x in drvvv.drvvvSettings.GetDataContextInstance().Coupons.Where(x => x.Active && x.EndDate >= DateTime.Now && x.TitleEn != null).OrderByDescending(x => x.ID).Take(30))
        {
            objX.WriteStartElement("item");
            objX.WriteElementString("guid", x.ID.ToString());
            objX.WriteElementString("title", drvvv.Plugins.GetTextToSite(x.TitleEn, x.TitleFr, x.TitleDefault));
            objX.WriteElementString("image", (drvvv.Plugins.ReturnImgAddress(x.ImgName)).Replace("~/", drvvv.Plugins.GetTextToSite("http://anglodeals.co.il/", "http://francodeals.co.il/", "http://zebradeals.co.il/")));
            objX.WriteElementString("description", drvvv.Plugins.GetTextToSite(x.SubjectEn, x.SubjectFr, x.SubjectDefault));
            objX.WriteElementString("link", string.Format("http://{2}/CouponAddress.aspx?couponID={0}&SiteID={1}", x.ID, 6, drvvv.Plugins.GetTextToSite("anglodeals.co.il", "francodeals.co.il", "zebradeals.co.il")));
            objX.WriteElementString("pubDate", string.Format("{0:R}", x.EndDate));
            objX.WriteEndElement();
        }

        objX.WriteEndElement();
        objX.WriteEndElement();
        objX.WriteEndDocument();
        objX.Flush();
        objX.Close();
        Response.End();

    }
Beispiel #11
0
        public T cadastrar <T>(Objeto objeto, Uri uriBase)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(
                new Uri(uriBase, "xml"));

            httpWebRequest.ContentType = "application/xml";
            httpWebRequest.Method      = "POST";

            XmlSerializer serializador = new XmlSerializer(typeof(T));

            StringWriter  escritorString = new StringWriter();
            XmlTextWriter escritorXml    = new XmlTextWriter(escritorString);

            serializador.Serialize(escritorXml, objeto);

            escritorString.Close();
            escritorXml?.Close();

            string resposta = Requisicao.realizarComConteudo(
                escritorString.ToString(), httpWebRequest);

            StringReader  leitorString = new StringReader(resposta);
            XmlTextReader leitorXml    = new XmlTextReader(leitorString);

            return((T)serializador.Deserialize(leitorXml));
        }
Beispiel #12
0
    protected void WriteRSSFile()
    {
        try
        {
            string fileName = links.RssFeedLink.Replace(@"~\", ""); ;
            string filePath = HttpRuntime.AppDomainAppPath + fileName;

            XmlWriter xml = new XmlTextWriter(new StreamWriter(filePath));
            RssWriter rss = new RssWriter(xml);

            List<Item> itemList = engine.LoadItemDB(ProcessingEngine.Sort.Hot);

            rss.WriteHeader("getputs.com", "http://www.getputs.com", "All Your News Belong To Us!", null);

            foreach (Item item in itemList)
            {
                rss.WriteItem(item);
            }

            rss.Close();
            xml.Close();

        }
        catch (Exception ex)
        {
            if (log.isLoggingOn && log.isAppLoggingOn)
            {
                log.Log("Error in RssPage.aspx");
                log.Log(ex);
            }
        }
    }
Beispiel #13
0
 void Create()
 {
     XmlTextWriter writer = new XmlTextWriter ("todo.xml", System.Text.Encoding.UTF8);
     writer.WriteStartDocument ();
     writer.WriteStartElement ("tasks");
     writer.WriteEndElement ();
     writer.Close ();
 }
Beispiel #14
0
 public static void Write()
 {
     XmlTextWriter writer = new XmlTextWriter(Console.Out);
     writer.WriteStartDocument();
     writer.WriteElementString("Hello", "Xml");
     writer.WriteEndDocument();
     writer.Close();
 }
Beispiel #15
0
    private void dumpDataSetToXmlFile(DataSet ds)
    {
        XmlTextWriter xtw = new XmlTextWriter(txtDumpToFile.Text, null);
        ds.WriteXml(xtw, XmlWriteMode.WriteSchema);
        xtw.Close();

        lblErrorMessage.Text = "Done!";
    }
Beispiel #16
0
    /// <summary>
    /// This method is used for creating a new employee information in XML file
    /// </summary>
    /// <param name="employee">employee object</param>
    /// <returns>True - Success, False - Failure</returns>
    public bool Create(BLAutot auto)
    {
        try
        {
            // Checking if the file exist
            if (!File.Exists(strFileName))
            {
                // If file does not exist in the database path, create and store an empty Autot node
                XmlTextWriter textWritter = new XmlTextWriter(strFileName, null);
                textWritter.WriteStartDocument();
                textWritter.WriteStartElement("Wanhatautot");
                textWritter.WriteEndElement();
                textWritter.Close();
            }

            // Create the XML document by loading the file
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(strFileName);

            // Creating Auto node
            XmlElement subNode = xmlDoc.CreateElement("Auto");

            // Getting the maximum Id based on the XML data already stored
            string strId = CommonMethods.GetMaxValue(xmlDoc, "Wanhatautot" + "/" + "Auto" + "/" + "aid").ToString();

            // Adding Id column. Auto generated column
            subNode.AppendChild(CommonMethods.CreateXMLElement(xmlDoc, "aid", strId));
            xmlDoc.DocumentElement.AppendChild(subNode);

            subNode.AppendChild(CommonMethods.CreateXMLElement(xmlDoc, "rekkari", auto.rekkari));
            xmlDoc.DocumentElement.AppendChild(subNode);

            subNode.AppendChild(CommonMethods.CreateXMLElement(xmlDoc, "merkki", auto.merkki));
            xmlDoc.DocumentElement.AppendChild(subNode);

            subNode.AppendChild(CommonMethods.CreateXMLElement(xmlDoc, "malli", auto.malli));
            xmlDoc.DocumentElement.AppendChild(subNode);

            subNode.AppendChild(CommonMethods.CreateXMLElement(xmlDoc, "vm", auto.vm.ToString()));
            xmlDoc.DocumentElement.AppendChild(subNode);

            subNode.AppendChild(CommonMethods.CreateXMLElement(xmlDoc, "myyntiHinta", auto.myyntiHinta.ToString()));
            xmlDoc.DocumentElement.AppendChild(subNode);

            subNode.AppendChild(CommonMethods.CreateXMLElement(xmlDoc, "sisaanOstoHinta", auto.sisaanOstoHinta.ToString()));
            xmlDoc.DocumentElement.AppendChild(subNode);

            // Saving the file after adding the new auto node
            xmlDoc.Save(strFileName);

            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
        public string ConsumerScore(string xdsUrl, string cherwellUrl, string cmsUsrName, string cmsUsrPwd,
                                    string xdsUsrName, string xdsUsrPw, string reason, string idNo, string dob, string passportNumber,
                                    string reference, string ticket, string firstName, string lastname,
                                    string productionId, bool attachXml, bool attachPdf, string recId)
        {
            _webService.Url = XdsUrl;
            var myMatch = _webService.ConnectConsumerMatch(ticket, reason, int.Parse(productionId), idNo,
                                                           passportNumber,
                                                           firstName, lastname, dob, reference, string.Empty);

            _enquiryId       = int.Parse(XmlReaders.FindXmlValue(myMatch, "EnquiryID"));
            _enquiryResultId = int.Parse(XmlReaders.FindXmlValue(myMatch, "EnquiryResultID"));

            var xdsResult = _webService.ConnectGetResult(ticket, _enquiryId, _enquiryResultId, int.Parse(productionId),
                                                         string.Empty);

            var attachments = new Attachements();

            if (attachXml)
            {
                attachments.AttachXml(CherwellUrl, cmsUsrName, cmsUsrPwd, recId, xdsResult);
            }

            if (attachPdf)
            {
                attachments.AttachPdf(CherwellUrl, cmsUsrName, cmsUsrPwd, recId, ticket, productionId, _enquiryId, _enquiryResultId);
            }

            var results = new Results
            {
                Score           = XmlReaders.FindXmlValue(xdsResult, "FinalScore"),
                EnquiryID       = _enquiryId.ToString(),
                EnquiryResultID = _enquiryResultId.ToString(),
                Judgements      = XmlReaders.FindJudgements(xdsResult, "JudgmentsCount").ToString()
            };
            var           sw = new StringWriter();
            XmlTextWriter tw = null;

            try
            {
                var serializer = new XmlSerializer(results.GetType());
                tw = new XmlTextWriter(sw);
                serializer.Serialize(tw, results);
            }
            catch (Exception)
            {
                //Handle Exception Code
            }
            finally
            {
                sw.Close();
                tw?.Close();
            }

            return(sw.ToString());
        }
Beispiel #18
0
 public static void CreateXmlFile(string fileName, string rootElementName)
 {
     XmlTextWriter writer = new XmlTextWriter(fileName, System.Text.Encoding.UTF8);
     writer.WriteStartDocument();
     writer.Formatting = Formatting.Indented;
     writer.Indentation = 2;
     writer.WriteStartElement(rootElementName);
     writer.WriteEndElement();
     writer.WriteEndDocument();
     writer.Close();
 }
Beispiel #19
0
        public void Dispose()
        {
            _xmlTextWriter?.Close();
            _shadowFileStream?.Close();
            _shadowFileStream?.Dispose();

            if (_shadowFile != null)
            {
                DeleteFile(_shadowFile);
            }
        }
Beispiel #20
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Cache.SetNoStore();
        Response.ContentType = "application/xml";
        DataTable dt = CreateBll.GetInfo(TABLE_NAME, 1, 100);

        MemoryStream ms = new MemoryStream();
        XmlTextWriter xmlTW = new XmlTextWriter(ms, Encoding.UTF8);
        xmlTW.Formatting = Formatting.Indented;
        xmlTW.WriteStartDocument();
        xmlTW.WriteStartElement("urlset");
        xmlTW.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
        xmlTW.WriteAttributeString("xmlns:news", "http://www.google.com/schemas/sitemap-news/0.9");

        foreach (DataRow dr in dt.Rows)
        {
            xmlTW.WriteStartElement("url");
            string infoUrl = CreateBll.GetInfoUrl(dr,1).ToLower();
            if(!infoUrl.StartsWith("http://")&&!infoUrl.StartsWith("https://")&&!infoUrl.StartsWith("ftp://"))
            {
                if(Param.ApplicationRootPath==string.Empty)
                {
                    infoUrl = CreateBll.SiteModel.Domain+infoUrl;
                }
                else
                {
                    infoUrl = infoUrl.Replace(Param.ApplicationRootPath.ToLower(),string.Empty);
                    infoUrl = CreateBll.SiteModel.Domain+infoUrl;
                }
            }
            xmlTW.WriteElementString("loc", infoUrl);

            xmlTW.WriteStartElement("news:news");
            xmlTW.WriteElementString("news:publication_date", dr["addtime"].ToString());
             string keywords = dr["tagnamestr"].ToString();
            if (keywords.StartsWith("|") && keywords.EndsWith("|"))
            {
                keywords = keywords.Substring(0, keywords.Length - 1);
                keywords = keywords.Substring(1, keywords.Length - 1);
                keywords = keywords.Replace("|",",");
            }
            xmlTW.WriteElementString("news:keywords", keywords);
            xmlTW.WriteEndElement();
            xmlTW.WriteEndElement();
        }
        xmlTW.WriteEndDocument();
        xmlTW.Flush();
        byte[] buffer = ms.ToArray();
        Response.Write(Encoding.UTF8.GetString(buffer));
        Response.End();
        xmlTW.Close();
        ms.Close();
        ms.Dispose();
    }
Beispiel #21
0
    /// <summary>
    /// The entry point for the application.
    /// </summary>
    /// <param name="args"> A list of command line arguments</param>
    public static int Main(String[] args)
    {
        // TODO: Add code to start application here
        XmlTextWriter writer = new XmlTextWriter(Console.Out);
        writer.WriteStartDocument();
        writer.WriteElementString("Hello", "XML");
        writer.WriteEndDocument();
        writer.Close();

        return 0;
    }
        /// <summary>
        /// Serializes an object instance to a file.
        /// </summary>
        /// <param name="instance">the object instance to serialize</param>
        /// <param name="fileName"></param>
        /// <param name="binarySerialization">determines whether XML serialization or binary serialization is used</param>
        /// <returns></returns>
        public static bool SerializeObject(object instance, string fileName, bool binarySerialization)
        {
            bool retVal = true;

            if (!binarySerialization)
            {
                XmlTextWriter writer = null;
                try
                {
                    var serializer = new XmlSerializer(instance.GetType());

                    // Create an XmlTextWriter using a FileStream.
                    Stream fs = new FileStream(fileName, FileMode.Create);
                    writer = new XmlTextWriter(fs, new UTF8Encoding())
                    {
                        Formatting  = Formatting.Indented,
                        IndentChar  = ' ',
                        Indentation = 3
                    };

                    // Serialize using the XmlTextWriter.
                    serializer.Serialize(writer, instance);
                }
                catch (Exception ex)
                {
                    Debug.Write("SerializeObject failed with : " + ex.Message, "West Wind");
                    retVal = false;
                }
                finally
                {
                    writer?.Close();
                }
            }
            else
            {
                Stream fs = null;
                try
                {
                    var serializer = new BinaryFormatter();
                    fs = new FileStream(fileName, FileMode.Create);
                    serializer.Serialize(fs, instance);
                }
                catch
                {
                    retVal = false;
                }
                finally
                {
                    fs?.Close();
                }
            }

            return(retVal);
        }
Beispiel #23
0
    //===============================================================
    // Function: Page_Load
    //===============================================================
    protected void Page_Load(object sender, EventArgs e)
    {
        XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
        writer.WriteStartDocument();
        writer.WriteStartElement("data");

        CreateXMLContent(writer);

        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Close();
    }
 public static void SaveAgentsToFile(string path, AgentDependency m)
 {
     XmlTextWriter	writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);
     writer.Indentation = 4;
     writer.Formatting = Formatting.Indented;
     writer.Settings.NewLineHandling = NewLineHandling.Entitize;
     writer.Settings.NewLineOnAttributes = true;
     writer.WriteStartDocument();
     writer.WriteComment("This file is generated by Agents Plugin Editor (created by Peyman Abdi peyman[at]nemo-games[dot]com).");
     m.Write(writer);
     writer.Close();
     AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
 }
Beispiel #25
0
 //导出重点怀疑对象
 protected void btnExportKey_Click(object sender, EventArgs e)
 {
     string xmlPath = Server.MapPath("~/src/temp/") + "MacIpUser" + Page.User.Identity.Name + ".xml";
     DataSet dsKey = DB.getMacIpUsers();
     StreamWriter sw = new StreamWriter(xmlPath);
     XmlTextWriter xmlWriter = new XmlTextWriter(sw);
     xmlWriter.Formatting = Formatting.Indented;
     xmlWriter.Indentation = 10;
     dsKey.WriteXml(xmlWriter);
     xmlWriter.Close();
     Message.Show(this.Page, "重点怀疑对象导出成功!");
     SendToClient(xmlPath);
 }
    /// <summary>
    /// This method is used for creating a new employee information in XML file
    /// </summary>
    /// <param name="employee">employee object</param>
    /// <returns>True - Success, False - Failure</returns>
    public bool Create(BLTunnit tunti)
    {
        try
        {
            // Checking if the file exist
            if (!File.Exists(strFileName))
            {
                // If file does not exist in the database path, create and store an empty tuntit node
                XmlTextWriter textWritter = new XmlTextWriter(strFileName, null);
                textWritter.WriteStartDocument();
                textWritter.WriteStartElement("Tunnit");
                textWritter.WriteEndElement();
                textWritter.Close();
            }

            // Create the XML document by loading the file
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(strFileName);

            // Creating tunti node
            XmlElement subNode = xmlDoc.CreateElement("Tunti");

            // Getting the maximum Id based on the XML data already stored
            string strId = CommonMethods.GetMaxValue(xmlDoc, "Tunnit" + "/" + "Tunti" + "/" + "id").ToString();

            // Adding Id column. tunti generated column
            subNode.AppendChild(CommonMethods.CreateXMLElement(xmlDoc, "id", strId));
            xmlDoc.DocumentElement.AppendChild(subNode);

            subNode.AppendChild(CommonMethods.CreateXMLElement(xmlDoc, "koodaaja", tunti.koodaaja));
            xmlDoc.DocumentElement.AppendChild(subNode);

            subNode.AppendChild(CommonMethods.CreateXMLElement(xmlDoc, "paivamaara", tunti.paivamaara));
            xmlDoc.DocumentElement.AppendChild(subNode);

            subNode.AppendChild(CommonMethods.CreateXMLElement(xmlDoc, "tuntimaara", tunti.tuntimaara));
            xmlDoc.DocumentElement.AppendChild(subNode);

            subNode.AppendChild(CommonMethods.CreateXMLElement(xmlDoc, "minuutit", tunti.minuutit));
            xmlDoc.DocumentElement.AppendChild(subNode);

            // Saving the file after adding the new tunti node
            xmlDoc.Save(strFileName);

            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Beispiel #27
0
 protected void btnAdd_Click(object sender, EventArgs e)
 {
     XmlTextWriter xr = new XmlTextWriter(Server.MapPath("my.xml"), null);
     xr.WriteStartDocument();
     xr.WriteStartElement("Information");
     xr.WriteStartElement("infos");
     xr.WriteElementString("info", Editor1.Content);
     xr.WriteEndElement();
     xr.WriteEndElement();
     xr.WriteEndDocument();
     xr.Close();
     Fillinfos();
     Editor1.Content = "";
 }
Beispiel #28
0
    //===============================================================
    // Function: Page_Load
    //===============================================================
    protected void Page_Load(object sender, EventArgs e)
    {
        int userID = int.Parse(Request.QueryString["UID"].ToString());

        XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
        writer.WriteStartDocument();
        writer.WriteStartElement("data");

        CreateXMLContent(writer, userID);

        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Close();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //Instantiate Action Stored Procedure object
        Blogic FetchData = new Blogic();

        int i = 0;

        //Note: You need to change the domain name "myasp-net.com and ex-designz.net" to your site domain
        Response.Clear();
        Response.ContentType = "text/xml";
        XmlTextWriter objX = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
        objX.WriteStartDocument();
        objX.WriteStartElement("rss");
        objX.WriteAttributeString("version", "2.0");
        objX.WriteStartElement("channel");
        objX.WriteElementString("title", "Ex-designz.net Most Popular Recipe RSS Feed");
        objX.WriteElementString("link", "http://www.myasp-net.com");
        objX.WriteElementString("description", "Recipe database from around the world");
        objX.WriteElementString("copyright", "(c) 2005, Myasp-net.com and Ex-designz.net. All rights reserved.");
        objX.WriteElementString("ttl", "10");

        //Get datatable
        IDataReader dr = FetchData.GetRSSMostPopularRecipe;

        //loop through all record, and write XML for each item.
        for (i = 0; i <= 20 - 1; i++)
        {
            dr.Read();
            objX.WriteStartElement("item");
            objX.WriteElementString("title", dr["Name"].ToString());
            objX.WriteElementString("link", "http://www.ex-designz.net/recipedisplay.asp?rid=" + (int)dr["ID"]);
            objX.WriteElementString("pubDate", Convert.ToDateTime(dr["Date"]).ToShortDateString());
            objX.WriteEndElement();
        }

        dr.Close();

        //End of XML file
        objX.WriteEndElement();
        objX.WriteEndElement();
        objX.WriteEndDocument();

        //Close the XmlTextWriter object
        objX.Flush();
        objX.Close();
        Response.End();

        FetchData = null;
    }
 public static void SaveManifestToFile(string path, Manifest m)
 {
     if (!System.IO.Directory.Exists(Manifest.ManifestFolder))
         System.IO.Directory.CreateDirectory(Manifest.ManifestFolder);
     XmlTextWriter	writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);
     writer.Indentation = 4;
     writer.Formatting = Formatting.Indented;
     writer.Settings.NewLineHandling = NewLineHandling.Entitize;
     writer.Settings.NewLineOnAttributes = true;
     writer.WriteStartDocument();
     writer.WriteComment("This file is generated by Android Manifest Editor (created by Peyman Abdi peyman[at]nemo-games[dot]com).");
     m.Write(writer);
     writer.Close();
     AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
 }
Beispiel #31
0
        /// <summary>
        /// 返回格式化XmlDocument字符串
        /// </summary>
        /// <param name="doc">XmlDocument</param>
        /// <returns></returns>
        public static string FormatXml(XmlDocument doc)
        {
            StringBuilder sb  = new StringBuilder();
            StringWriter  sw  = new StringWriter(sb);
            XmlTextWriter xtw = null;

            try{
                xtw             = new XmlTextWriter(sw);
                xtw.Formatting  = Formatting.Indented;
                xtw.Indentation = 1;
                xtw.IndentChar  = '\t';
                doc.WriteTo(xtw);
            }finally{
                xtw?.Close();
            }
            return(sb.ToString());
        }
  } //Main()

  /// <summary>
  /// Demonstrates the XslTransform class using two different overloads.
  /// One returns an XmlReader containing the transform.
  /// The other stores the transform in an XmlTextWriter.
  /// </summary>
  /// <param name="document"></param>
  /// <param name="stylesheet"></param>
  public static void ReadTransformWrite(string document, string stylesheet)
  {
    StreamReader stream = null;

    try
    {
      string outputFile = Path.GetFileNameWithoutExtension(document) + "_transform.xml";
      // XPathDocument stores the target XML in an efficient way for transformation.
      XPathDocument myXPathDocument = new XPathDocument(document);
      XslTransform myXslTransform = new XslTransform();
      myXslTransform.Load(stylesheet);

      // Get back the transform results in an XMLReader and output them to the console.
      XmlReader reader = myXslTransform.Transform(myXPathDocument, null);

      Console.WriteLine("Input XML file: {0} \nXSL stylesheet: {1}" + nl, document, stylesheet);
      Console.WriteLine(nl + "Layout of transformed XML content from XML reader:" + nl);
      OutputXml(reader);

      // Create an output file to hold the tranform.
      // Using an intermediate XmlTextWriter instead of the overload of the Transform method
      // that writes directly to a file allows more control of the formatting.
      XmlTextWriter writer = new XmlTextWriter(outputFile, null);
      writer.Formatting = Formatting.Indented;
      writer.Indentation = 2;
      myXslTransform.Transform(myXPathDocument, null, writer);
      writer.Close();

      //Output the contents of the tranformed file to the console.
      Console.WriteLine(nl + "Transformed XML content from file:" + nl);
      stream = new StreamReader (outputFile);
      Console.Write(stream.ReadToEnd());
    } //try

    catch (Exception e)
    {
      Console.WriteLine ("Exception: {0}", e.ToString());
    } //catch

    finally
    {
      if (stream != null)
        stream.Close();
    } //finally
  } //ReadTransformWrite()
Beispiel #33
0
 //This will transform xml document using xslt and produce result xml document
 //and display it
 public static void Main(string[] args)
 {
     try
     {
         XPathDocument myXPathDocument = new XPathDocument("C:/Users/user/Desktop/Assignment 4/schema.xml");
         XslTransform myXslTransform = new XslTransform();
         XmlTextWriter writer = new XmlTextWriter("C:/Users/user/Desktop/Assignment 4/output.html", null);
         myXslTransform.Load("http://www.public.asu.edu/~sprakas3/dsod/Hotels.xsl");
         myXslTransform.Transform(myXPathDocument, null, writer);
         writer.Close();
         StreamReader stream = new StreamReader("C:/Users/user/Desktop/Assignment 4/output.html");
         Console.Write("**This is result document**\n\n");
         Console.Write(stream.ReadToEnd());
     }
     catch (Exception e)
     {
     }
 }
Beispiel #34
0
    //===============================================================
    // Function: Page_Load
    //===============================================================
    protected void Page_Load(object sender, EventArgs e)
    {
        string searchText = "";
        if (Request.QueryString["Search"] != null)
        {
            searchText = (string)Request.QueryString["Search"];
        }

        XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
        writer.WriteStartDocument();
        writer.WriteStartElement("data");

        CreateXMLContent(writer, searchText);

        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Close();
    }
Beispiel #35
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int i = 0;

        //Note: You need to change the domain name "myasp-net.com and ex-designz.net" to your site domain
        Response.Clear();
        Response.ContentType = "text/xml";
        XmlTextWriter objX = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
        objX.WriteStartDocument();
        objX.WriteStartElement("rss");
        objX.WriteAttributeString("version", "2.0");
        objX.WriteStartElement("channel");
        objX.WriteElementString("title", "VGuitar.net những bài hát yêu thích nhất RRS");
        objX.WriteElementString("link", "http://thlb.biz");
        objX.WriteElementString("description", "Lyric database from around the world");
        objX.WriteElementString("copyright", "(c) 2009, thlb.biz");
        objX.WriteElementString("ttl", "10");

        //Get datatable
        IDataReader dr = Blogic.ActionProcedureDataProvider.GetRSSMostPopularLyric;

        //loop through all record, and write XML for each item.
        for (i = 0; i <= 20 - 1; i++)
        {
            dr.Read();
            objX.WriteStartElement("item");
            objX.WriteElementString("title", dr["Name"].ToString());
            objX.WriteElementString("link", "http://thlb.biz?rid=" + (int)dr["ID"]);
            objX.WriteElementString("pubDate", Convert.ToDateTime(dr["Date"]).ToShortDateString());
            objX.WriteEndElement();
        }

        dr.Close();

        //End of XML file
        objX.WriteEndElement();
        objX.WriteEndElement();
        objX.WriteEndDocument();

        //Close the XmlTextWriter object
        objX.Flush();
        objX.Close();
        Response.End();
    }
Beispiel #36
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int i = 0;

        //Note: You need to change the domain name "myasp-net.com and ex-designz.net" to your site domain
        Response.Clear();
        Response.ContentType = "text/xml";
        XmlTextWriter objX = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
        objX.WriteStartDocument();
        objX.WriteStartElement("rss");
        objX.WriteAttributeString("version", "2.0");
        objX.WriteStartElement("channel");
        objX.WriteElementString("title", "ExamCrazy.com Newest RSS Feed");
        objX.WriteElementString("link", "http://www.examcrazy.com");
        objX.WriteElementString("description", "ExamCrazy.Com RSS");
        objX.WriteElementString("copyright", "(c) 2005, ExamCrazy.Com. All rights reserved.");
        objX.WriteElementString("ttl", "10");

        //Get data
        IDataReader dr = Blogic.ActionProcedureDataProvider.GetRssNewFeed;

        //loop through all record, and write XML for each item.
        for (i = 0; (i <= 20 - 1) && (dr.Read() == true); i++)
        {
            objX.WriteStartElement("item");
            objX.WriteElementString("title", dr["Title"].ToString());
            objX.WriteElementString("link", dr["Title"].ToString());
            objX.WriteElementString("pubDate", Convert.ToDateTime(dr["DatePublished"]).ToShortDateString());
            objX.WriteEndElement();
        }

        dr.Close();

        //End of XML file
        objX.WriteEndElement();
        objX.WriteEndElement();
        objX.WriteEndDocument();

        //Close the XmlTextWriter object
        objX.Flush();
        objX.Close();
        Response.End();
    }
    // Create example data to sign.
    public static void CreateSomeXml(string FileName)
    {
        // Create a new XmlDocument object.
        XmlDocument document = new XmlDocument();

        // Create a new XmlNode object.
        XmlNode node = document.CreateNode(XmlNodeType.Element, "", "MyElement", "samples");

        // Add some text to the node.
        node.InnerText = "Example text to be signed.";

        // Append the node to the document.
        document.AppendChild(node);

        // Save the XML document to the file name specified.
        XmlTextWriter xmltw = new XmlTextWriter(FileName, new UTF8Encoding(false));
        document.WriteTo(xmltw);
        xmltw.Close();
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        vidDocument.Load(Server.MapPath("/App_Data/data.xml"));
        XmlNode node = vidDocument.SelectNodes("/store")[0].LastChild;
        XmlNode newnode = node.CloneNode(true);

        newnode.SelectSingleNode("id").InnerText = (int.Parse(newnode.SelectSingleNode("id").InnerText) + 1).ToString();
        newnode.SelectSingleNode("title").InnerText = txtTitle.Text;
        newnode.SelectSingleNode("artist").InnerText = txtArtist.Text;
        newnode.SelectSingleNode("price").InnerText = txtPrice.Text;

        vidDocument.DocumentElement.AppendChild(newnode);

        XmlTextWriter writer = new XmlTextWriter(Server.MapPath("App_Data/data.xml"), null);
        writer.Formatting = Formatting.Indented;
        vidDocument.Save(writer);
        writer.Close();

        Response.Redirect(Request.RawUrl);
    }
Beispiel #39
0
        private string FormatXml(string sUnformattedXml)
        {
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(sUnformattedXml);
            StringBuilder sb            = new StringBuilder();
            StringWriter  stringWriter  = new StringWriter(sb);
            XmlTextWriter xmlTextWriter = (XmlTextWriter)null;

            try
            {
                xmlTextWriter            = new XmlTextWriter((TextWriter)stringWriter);
                xmlTextWriter.Formatting = Formatting.Indented;
                xmlDocument.WriteTo((XmlWriter)xmlTextWriter);
            }
            finally
            {
                xmlTextWriter?.Close();
            }
            return(sb.ToString());
        }
Beispiel #40
0
        /// <summary>
        /// 将对象序列化为Xml文件。
        /// </summary>
        /// <param name="obj">对象。</param>
        /// <param name="path">路径。</param>
        public static void SerializeToXmlFile(object obj, string path)
        {
            XmlTextWriter writer = null;

            try
            {
                writer = new XmlTextWriter(path, Encoding.Default)
                {
                    Formatting = Formatting.Indented
                };
                var xmlSerializer = new XmlSerializer(obj.GetType());
                xmlSerializer.Serialize(writer, obj);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                writer?.Close();
            }
        }
        public static string GetXMLFromObject(object o)
        {
            StringWriter  sw = new StringWriter();
            XmlTextWriter tw = null;

            try
            {
                XmlSerializer serializer = new XmlSerializer(o.GetType());
                tw = new XmlTextWriter(sw);
                serializer.Serialize(tw, o);
            }
            catch (Exception ex)
            {
                //Handle Exception Code
            }
            finally
            {
                sw.Close();
                tw?.Close();
            }
            return(sw.ToString());
        }
        public static string BeautifyXml(XmlNode xml)
        {
            var doc = new XmlDocument();

            doc.LoadXml(xml.OuterXml);
            var           builder = new StringBuilder();
            var           writer  = new StringWriter(builder);
            XmlTextWriter xtw     = null;

            try
            {
                xtw = new XmlTextWriter(writer)
                {
                    Formatting = Formatting.Indented
                };
                doc.WriteTo(xtw);
            }
            finally
            {
                xtw?.Close();
            }
            return(builder.ToString());
        }
Beispiel #43
0
        /// <summary>
        /// Create an XML file of the engine settings.
        /// This is done only if the XML file does not exist.
        /// </summary>
        void CreateEngineSettingsXMLFile()
        {
            if (!Directory.Exists(@"Content\Engine\Config\"))
            {
                Directory.CreateDirectory(@"Content\Engine\Config\");
            }

            XmlTextWriter xmlWriter = new XmlTextWriter(@"Content\Engine\Config\EngineConfig.xml", Encoding.UTF8);

            xmlWriter.Formatting = Formatting.Indented;

            xmlWriter.WriteStartDocument();

            xmlWriter.WriteStartElement("Engine");
            {
                xmlWriter.WriteStartElement("Video");
                {
                    xmlWriter.WriteStartElement("Resolution");
                    {
                        xmlWriter.WriteAttributeString("Width", Graphics.GraphicsDevice.Adapter.CurrentDisplayMode.Width.ToString());
                        xmlWriter.WriteAttributeString("Hight", Graphics.GraphicsDevice.Adapter.CurrentDisplayMode.Height.ToString());
                    }
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("RefreshRate");
                    {
                        xmlWriter.WriteAttributeString("Value", Graphics.GraphicsDevice.Adapter.CurrentDisplayMode.RefreshRate.ToString());
                    }
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("DisplayMode");
                    {
                        xmlWriter.WriteAttributeString("Value", "Window");
                    }
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("WindowPosition");
                    {
                        xmlWriter.WriteAttributeString("Center", "true");
                        xmlWriter.WriteAttributeString("X", "0");
                        xmlWriter.WriteAttributeString("Y", "0");
                    }
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("MultiSampling");
                    {
                        xmlWriter.WriteAttributeString("Value", "true");
                    }
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("Vsync");
                    {
                        xmlWriter.WriteAttributeString("Value", "true");
                    }
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("FrameRate");
                    {
                        xmlWriter.WriteAttributeString("IsCaped", "false");
                        xmlWriter.WriteAttributeString("CapLimit", "60");
                    }
                    xmlWriter.WriteEndElement();
                }
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("Audio");
                {
                    xmlWriter.WriteStartElement("Master");
                    {
                        xmlWriter.WriteAttributeString("Value", "50");
                    }
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("Sound");
                    {
                        xmlWriter.WriteAttributeString("Value", "50");
                    }
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("Music");
                    {
                        xmlWriter.WriteAttributeString("Value", "50");
                    }
                    xmlWriter.WriteEndElement();
                }
                xmlWriter.WriteEndElement();
            }
            xmlWriter.WriteEndElement();

            xmlWriter.WriteEndDocument();
            xmlWriter.Close();
        }
Beispiel #44
0
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            goto Skip_62338;

            StringBuilder escape = new StringBuilder();

            for (int i = 0; i < tainted_2.Length; ++i)
            {
                char current = tainted_2[i];
                switch (current)
                {
                case '\\':
                    escape.Append(@"\5c");
                    break;

                case '*':
                    escape.Append(@"\2a");
                    break;

                case '(':
                    escape.Append(@"\28");
                    break;

                case ')':
                    escape.Append(@"\29");
                    break;

                case '\u0000':
                    escape.Append(@"\00");
                    break;

                case '/':
                    escape.Append(@"\2f");
                    break;

                default:
                    escape.Append(current);
                    break;
                }
            }
            tainted_3 = escape.ToString();

Skip_62338:
            {}


            string query = tainted_3;


            string        filename = "file.xml";
            XDocument     document = XDocument.Load(filename);
            XmlTextWriter writer   = new XmlTextWriter(Console.Out);

            writer.Formatting = Formatting.Indented;
            var node = document.Root.Elements("foo")
                       .Where(x => (string)x.Element("bar") == query)
                       .SingleOrDefault();

            node.WriteTo(writer);
            writer.Close( );
        }
Beispiel #45
0
        /// <summary>
        /// Saves the package builder data to disk.
        /// </summary>
        /// <param name="path">Path to save the fabricator information.</param>
        public override void Save(string path)
        {
            IA.IsolatedApp isolatedApp = new IA.IsolatedApp();

            // Serialize out the package information.
            IA.Package package = new IA.Package();
            isolatedApp.AddChild(package);

            if (this.description != null && this.description.Length > 0)
            {
                IA.Description description = new IA.Description();
                description.Content = this.description;
                package.AddChild(description);
            }

            if (this.updateUrl != null)
            {
                IA.Feed feed = new IA.Feed();
                feed.Content = this.updateUrl.ToString();
                package.AddChild(feed);
            }

            if (this.updateRate > 0)
            {
                IA.UpdateRate updateRate = new IA.UpdateRate();
                updateRate.Content = this.updateRate;
                package.AddChild(updateRate);
            }

            if (this.packageId != Guid.Empty)
            {
                IA.Id id = new IA.Id();
                id.Content = this.packageId.ToString();
                package.AddChild(id);
            }

            if (this.manufacturer != null && this.manufacturer.Length > 0)
            {
                IA.Manufacturer manufacturer = new IA.Manufacturer();
                manufacturer.Content = this.manufacturer;
                package.AddChild(manufacturer);
            }

            if (this.appVersion != null)
            {
                IA.Version version = new IA.Version();
                version.Content = this.appVersion.ToString();
                package.AddChild(version);
            }

            // Serialize out the application information.
            IA.Application application = new IA.Application();
            isolatedApp.AddChild(application);

            if (this.details != null && this.details.Length > 0)
            {
                IA.Details details = new IA.Details();
                details.Content = this.details;
                application.AddChild(details);
            }

            if (this.entryPoint != null && this.entryPoint.Length > 0)
            {
                IA.EntryPoint entryPoint = new IA.EntryPoint();
                entryPoint.Content = this.entryPoint;
                application.AddChild(entryPoint);
            }

            if (this.iconPath != null && this.iconPath.Length > 0)
            {
                IA.Icon icon = new IA.Icon();
                icon.Content = this.iconPath;
                application.AddChild(icon);
            }

            if (this.appId != Guid.Empty)
            {
                IA.Id id = new IA.Id();
                id.Content = this.appId.ToString();
                application.AddChild(id);
            }

            if (this.name != null && this.name.Length > 0)
            {
                IA.Name name = new IA.Name();
                name.Content = this.name;
                application.AddChild(name);
            }

            if (this.source != null && this.source.Length > 0)
            {
                IA.Source source = new IA.Source();
                source.Content = this.source;
                application.AddChild(source);
            }

            // Serialize out the previous package path if there is one.
            if (this.previousFeedUrl != null)
            {
                IA.PreviousFeed previousFeed = new IA.PreviousFeed();
                previousFeed.Content = this.previousFeedUrl.AbsoluteUri;
                isolatedApp.AddChild(previousFeed);
            }

            // Serialize the data to disk.
            using (StreamWriter sw = new StreamWriter(path))
            {
                XmlTextWriter writer = null;
                try
                {
                    writer             = new XmlTextWriter(sw);
                    writer.Formatting  = Formatting.Indented;
                    writer.Indentation = 4;

                    isolatedApp.OutputXml(writer);
                }
                finally
                {
                    if (writer != null)
                    {
                        writer.Close();
                    }
                }
            }
        }
        public static void SaveSettings(MainWindow MainF)
        {
            XmlTextWriter xmlfile = new XmlTextWriter(pathSettings, Encoding.UTF8);

            xmlfile.Formatting = Formatting.Indented;
            xmlfile.WriteStartElement("Settings");
            xmlfile.WriteStartElement("Bookmakers");
            foreach (BasicBrokerData item in MainF.Bookmakers)
            {
                xmlfile.WriteStartElement("BookMaker");

                xmlfile.WriteStartElement("Name");
                xmlfile.WriteString(item.Name);
                xmlfile.WriteEndElement();

                xmlfile.WriteStartElement("Limit");
                xmlfile.WriteString(item.Limit.ToString());
                xmlfile.WriteEndElement();

                xmlfile.WriteStartElement("InUse");
                xmlfile.WriteString(item.InUse.ToString());
                xmlfile.WriteEndElement();

                xmlfile.WriteStartElement("Email");
                xmlfile.WriteString(item.EMailing.ToString());
                xmlfile.WriteEndElement();

                xmlfile.WriteStartElement("Dutch3Way");
                xmlfile.WriteString(item.Dutch3Way.ToString());
                xmlfile.WriteEndElement();

                xmlfile.WriteStartElement("EmailPLlimit");
                xmlfile.WriteString(item.PLlimit.ToString());
                xmlfile.WriteEndElement();

                xmlfile.WriteEndElement();
            }
            xmlfile.WriteEndElement();

            xmlfile.WriteStartElement("Leagues");
            foreach (LeagueState item in MainF.Leagues)
            {
                xmlfile.WriteStartElement("League");

                xmlfile.WriteStartElement("LeagueName");
                xmlfile.WriteString(item.Name);
                xmlfile.WriteEndElement();

                xmlfile.WriteStartElement("Value");
                xmlfile.WriteString(item.State.ToString());
                xmlfile.WriteEndElement();

                xmlfile.WriteEndElement();
            }
            xmlfile.WriteEndElement();
            xmlfile.WriteStartElement("SuspendedMatches");
            foreach (string str in MainF.SuspendedMatches)
            {
                xmlfile.WriteStartElement("Match");
                xmlfile.WriteString(str);
                xmlfile.WriteEndElement();
            }

            xmlfile.WriteEndElement();
            xmlfile.WriteEndElement();
            xmlfile.Close();
        }
        public void Save(MainWindow MainF, List <FData> FootData)
        {
            XmlTextWriter xmlfile = new XmlTextWriter(pathAllMatches, Encoding.UTF8);

            xmlfile.Formatting = Formatting.Indented;
            xmlfile.WriteStartElement("Data");
            for (int i = FootData.Count - 1; i >= 0; i--)
            {
                FData item = FootData[i];
                xmlfile.WriteStartElement("Match");

                xmlfile.WriteStartElement("League");
                xmlfile.WriteString(item.League);
                xmlfile.WriteEndElement();

                xmlfile.WriteStartElement("Team1");
                xmlfile.WriteString(item.Team1);
                xmlfile.WriteEndElement();

                xmlfile.WriteStartElement("Team2");
                xmlfile.WriteString(item.Team2);
                xmlfile.WriteEndElement();

                xmlfile.WriteStartElement("Time");
                xmlfile.WriteString(item.time.ToString());
                xmlfile.WriteEndElement();

                xmlfile.WriteStartElement("Match");
                xmlfile.WriteString(item.Match);
                xmlfile.WriteEndElement();
                xmlfile.WriteStartElement("BookieOdds");

                foreach (KeyValuePair <int, X> it in FootData[i].XKoef)
                {
                    BasicBrokerData data = MainF.Bookmakers[it.Key];
                    xmlfile.WriteStartElement("B_" + data.Name);

                    xmlfile.WriteStartElement("LastUpdate");
                    xmlfile.WriteString(it.Value.LastUpdate);
                    xmlfile.WriteEndElement();

                    xmlfile.WriteStartElement("X1");
                    xmlfile.WriteString(it.Value.Koef[1].ToString());
                    xmlfile.WriteEndElement();

                    xmlfile.WriteStartElement("X0");
                    xmlfile.WriteString(it.Value.Koef[0].ToString());
                    xmlfile.WriteEndElement();

                    xmlfile.WriteStartElement("X2");
                    xmlfile.WriteString(it.Value.Koef[2].ToString());
                    xmlfile.WriteEndElement();



                    if (MainF.Bookmakers[it.Key].Type == BrokerType.LAY)
                    {
                        xmlfile.WriteStartElement("LX1");
                        xmlfile.WriteString(item.Lay[1].ToString());
                        xmlfile.WriteEndElement();

                        xmlfile.WriteStartElement("LX0");
                        xmlfile.WriteString(item.Lay[0].ToString());
                        xmlfile.WriteEndElement();

                        xmlfile.WriteStartElement("LX2");
                        xmlfile.WriteString(item.Lay[2].ToString());
                        xmlfile.WriteEndElement();
                    }



                    xmlfile.WriteEndElement();
                }

/*
 *              for (int id = 0; id < MainF.Bookmakers.Count; id++)
 *              {
 *                  if (item.Koef[id, 1] == 0) continue;
 *                  BasicBrokerData data = MainF.Bookmakers[id];
 *                  xmlfile.WriteStartElement("B_" + data.Name);
 *
 *                  xmlfile.WriteStartElement("LastUpdate");
 *                  xmlfile.WriteString(item.LastUpdate[id]);
 *                  xmlfile.WriteEndElement();
 *
 *                  xmlfile.WriteStartElement("X1");
 *                  xmlfile.WriteString(item.Koef[id, 1].ToString());
 *                  xmlfile.WriteEndElement();
 *
 *                  xmlfile.WriteStartElement("X0");
 *                  xmlfile.WriteString(item.Koef[id, 0].ToString());
 *                  xmlfile.WriteEndElement();
 *
 *                  xmlfile.WriteStartElement("X2");
 *                  xmlfile.WriteString(item.Koef[id, 2].ToString());
 *                  xmlfile.WriteEndElement();
 *
 *                  xmlfile.WriteEndElement();
 *              }
 */

                xmlfile.WriteEndElement();
                xmlfile.WriteEndElement();
            }
            xmlfile.WriteEndElement();
            xmlfile.Close();
        }
Beispiel #48
0
            private void save(IEnumerable <string> list, int max)
            {
                using (var ms = new MemoryStream())
                {
                    XmlTextWriter x = null;

                    try
                    {
                        x = new XmlTextWriter(ms, Encoding.UTF8)
                        {
                            Formatting = Formatting.Indented
                        };

                        x.WriteStartDocument();

                        x.WriteStartElement("RecentFiles");

                        var cpt = 0;
                        foreach (var loopFilePath in list)
                        {
                            x.WriteStartElement("RecentFile");
// ReSharper disable StringLiteralsWordIsNotInDictionary
                            x.WriteAttributeString("Filepath", loopFilePath);
// ReSharper restore StringLiteralsWordIsNotInDictionary
                            x.WriteEndElement();
                            cpt++;
                            if (cpt > max)
                            {
                                break;
                            }
                        }

                        x.WriteEndElement();

                        x.WriteEndDocument();

                        x.Flush();

                        using (var ss = openStream(FileMode.Create))
                        {
                            ss.Stream.SetLength(0);

                            ms.Position = 0;

                            var buffer = new byte[1 << 20];
                            for (; ;)
                            {
                                int bytes = ms.Read(buffer, 0, buffer.Length);
                                if (bytes == 0)
                                {
                                    break;
                                }
                                ss.Stream.Write(buffer, 0, bytes);
                            }
                        }
                    }
                    finally
                    {
                        x?.Close();
                    }
                }
            }
Beispiel #49
0
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            if ((4 + 2 >= 42))
            {
                StringBuilder escape = new StringBuilder();
                for (int i = 0; i < tainted_2.Length; ++i)
                {
                    char current = tainted_2[i];
                    switch (current)
                    {
                    case '\\':
                        escape.Append(@"\5c");
                        break;

                    case '*':
                        escape.Append(@"\2a");
                        break;

                    case '(':
                        escape.Append(@"\28");
                        break;

                    case ')':
                        escape.Append(@"\29");
                        break;

                    case '\u0000':
                        escape.Append(@"\00");
                        break;

                    case '/':
                        escape.Append(@"\2f");
                        break;

                    default:
                        escape.Append(current);
                        break;
                    }
                }
                tainted_3 = escape.ToString();
            }
            else if (!(4 + 2 >= 42))
            {
                {}
            }

            //flaw

            string query = "//user[@name='" + tainted_3 + "']";


            string      filename = "file.xml";
            XmlDocument document = new XmlDocument( );

            document.Load(filename);
            XmlTextWriter writer = new XmlTextWriter(Console.Out);

            writer.Formatting = Formatting.Indented;

            XmlNode node = document.SelectSingleNode(query);

            node.WriteTo(writer);

            writer.Close( );
        }
Beispiel #50
0
        static void CreateXML(string file)
        {
            XmlTextWriter writer = null;

            try
            {
                writer            = new XmlTextWriter(file, Encoding.Unicode);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                {
                    //< !DOCTYPE clients[<!ENTITY hello "Привіт з Ощад! " >] >
                    writer.WriteDocType("students", null, null, "<!ENTITY hello \"Привіт з Ощад! \">");
                    writer.WriteStartElement("students");
                    {
                        writer.WriteStartElement("student");
                        {
                            writer.WriteComment("Тест коментаря");
                            writer.WriteStartElement("fname");
                            {
                                writer.WriteEntityRef("hello");
                                writer.WriteString("Ivan");
                                writer.WriteEndElement();
                            }
                            writer.WriteElementString("lname", "Ivasyk");
                            writer.WriteElementString("suma", "10.59");
                            writer.WriteStartElement("address");
                            {
                                writer.WriteAttributeString("country", "Україна");
                                writer.WriteAttributeString("region", "Житомирська область");
                                writer.WriteString("Житомир");
                                writer.WriteEndElement();
                            }

                            writer.WriteElementString("birthday", "15.05.1978");
                        }
                        writer.WriteEndElement();
                        writer.WriteStartElement("student");
                        {
                            writer.WriteComment("Тест коментаря");
                            writer.WriteStartElement("fname");
                            {
                                writer.WriteEntityRef("hello");
                                writer.WriteString("Petro");
                                writer.WriteEndElement();
                            }
                            writer.WriteElementString("lname", "Petrenko");
                            writer.WriteElementString("suma", "1.59");
                            writer.WriteStartElement("address");
                            {
                                writer.WriteAttributeString("country", "Україна");
                                writer.WriteAttributeString("region", "Київська область");
                                writer.WriteString("Київ");
                                writer.WriteEndElement();
                            }

                            writer.WriteElementString("birthday", "15.05.1978");
                        }
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                }
                writer.WriteEndDocument();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                writer?.Close();
            }
        }
Beispiel #51
0
            public static void SaveAsXml(DockPanel dockPanel, Stream stream, Encoding encoding, bool upstream)
            {
                XmlTextWriter xmlOut = new XmlTextWriter(stream, encoding);

                // Use indenting for readability
                xmlOut.Formatting = Formatting.Indented;

                if (!upstream)
                {
                    xmlOut.WriteStartDocument();
                }

                // Always begin file with identification and warning
                xmlOut.WriteComment(Strings.DockPanel_Persistor_XmlFileComment1);
                xmlOut.WriteComment(Strings.DockPanel_Persistor_XmlFileComment2);

                // Associate a version number with the root element so that future version of the code
                // will be able to be backwards compatible or at least recognise out of date versions
                xmlOut.WriteStartElement("DockPanel");
                xmlOut.WriteAttributeString("FormatVersion", ConfigFileVersion);
                xmlOut.WriteAttributeString("DockLeftPortion", dockPanel.DockLeftPortion.ToString(CultureInfo.InvariantCulture));
                xmlOut.WriteAttributeString("DockRightPortion", dockPanel.DockRightPortion.ToString(CultureInfo.InvariantCulture));
                xmlOut.WriteAttributeString("DockTopPortion", dockPanel.DockTopPortion.ToString(CultureInfo.InvariantCulture));
                xmlOut.WriteAttributeString("DockBottomPortion", dockPanel.DockBottomPortion.ToString(CultureInfo.InvariantCulture));
                xmlOut.WriteAttributeString("ActiveDocumentPane", dockPanel.Panes.IndexOf(dockPanel.ActiveDocumentPane).ToString(CultureInfo.InvariantCulture));
                xmlOut.WriteAttributeString("ActivePane", dockPanel.Panes.IndexOf(dockPanel.ActivePane).ToString(CultureInfo.InvariantCulture));

                // Contents
                xmlOut.WriteStartElement("Contents");
                xmlOut.WriteAttributeString("Count", dockPanel.Contents.Count.ToString(CultureInfo.InvariantCulture));
                foreach (IDockContent content in dockPanel.Contents)
                {
                    xmlOut.WriteStartElement("Content");
                    xmlOut.WriteAttributeString("ID", dockPanel.Contents.IndexOf(content).ToString(CultureInfo.InvariantCulture));
                    xmlOut.WriteAttributeString("PersistString", content.DockHandler.PersistString);
                    xmlOut.WriteAttributeString("AutoHidePortion", content.DockHandler.AutoHidePortion.ToString(CultureInfo.InvariantCulture));
                    xmlOut.WriteAttributeString("IsHidden", content.DockHandler.IsHidden.ToString(CultureInfo.InvariantCulture));
                    xmlOut.WriteAttributeString("IsFloat", content.DockHandler.IsFloat.ToString(CultureInfo.InvariantCulture));
                    xmlOut.WriteEndElement();
                }
                xmlOut.WriteEndElement();

                // Panes
                xmlOut.WriteStartElement("Panes");
                xmlOut.WriteAttributeString("Count", dockPanel.Panes.Count.ToString(CultureInfo.InvariantCulture));
                foreach (DockPane pane in dockPanel.Panes)
                {
                    xmlOut.WriteStartElement("Pane");
                    xmlOut.WriteAttributeString("ID", dockPanel.Panes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
                    xmlOut.WriteAttributeString("DockState", pane.DockState.ToString());
                    xmlOut.WriteAttributeString("ActiveContent", dockPanel.Contents.IndexOf(pane.ActiveContent).ToString(CultureInfo.InvariantCulture));
                    xmlOut.WriteStartElement("Contents");
                    xmlOut.WriteAttributeString("Count", pane.Contents.Count.ToString(CultureInfo.InvariantCulture));
                    foreach (IDockContent content in pane.Contents)
                    {
                        xmlOut.WriteStartElement("Content");
                        xmlOut.WriteAttributeString("ID", pane.Contents.IndexOf(content).ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteAttributeString("RefID", dockPanel.Contents.IndexOf(content).ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteEndElement();
                    }
                    xmlOut.WriteEndElement();
                    xmlOut.WriteEndElement();
                }
                xmlOut.WriteEndElement();

                // DockWindows
                xmlOut.WriteStartElement("DockWindows");
                int dockWindowId = 0;

                foreach (DockWindow dw in dockPanel.DockWindows)
                {
                    xmlOut.WriteStartElement("DockWindow");
                    xmlOut.WriteAttributeString("ID", dockWindowId.ToString(CultureInfo.InvariantCulture));
                    dockWindowId++;
                    xmlOut.WriteAttributeString("DockState", dw.DockState.ToString());
                    xmlOut.WriteAttributeString("ZOrderIndex", dockPanel.Controls.IndexOf(dw).ToString(CultureInfo.InvariantCulture));
                    xmlOut.WriteStartElement("NestedPanes");
                    xmlOut.WriteAttributeString("Count", dw.NestedPanes.Count.ToString(CultureInfo.InvariantCulture));
                    foreach (DockPane pane in dw.NestedPanes)
                    {
                        xmlOut.WriteStartElement("Pane");
                        xmlOut.WriteAttributeString("ID", dw.NestedPanes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteAttributeString("RefID", dockPanel.Panes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
                        NestedDockingStatus status = pane.NestedDockingStatus;
                        xmlOut.WriteAttributeString("PrevPane", dockPanel.Panes.IndexOf(status.PreviousPane).ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteAttributeString("Alignment", status.Alignment.ToString());
                        xmlOut.WriteAttributeString("Proportion", status.Proportion.ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteEndElement();
                    }
                    xmlOut.WriteEndElement();
                    xmlOut.WriteEndElement();
                }
                xmlOut.WriteEndElement();

                // FloatWindows
                RectangleConverter rectConverter = new RectangleConverter();

                xmlOut.WriteStartElement("FloatWindows");
                xmlOut.WriteAttributeString("Count", dockPanel.FloatWindows.Count.ToString(CultureInfo.InvariantCulture));
                foreach (FloatWindow fw in dockPanel.FloatWindows)
                {
                    xmlOut.WriteStartElement("FloatWindow");
                    xmlOut.WriteAttributeString("ID", dockPanel.FloatWindows.IndexOf(fw).ToString(CultureInfo.InvariantCulture));
                    xmlOut.WriteAttributeString("Bounds", rectConverter.ConvertToInvariantString(fw.Bounds));
                    xmlOut.WriteAttributeString("ZOrderIndex", fw.DockPanel.FloatWindows.IndexOf(fw).ToString(CultureInfo.InvariantCulture));
                    xmlOut.WriteStartElement("NestedPanes");
                    xmlOut.WriteAttributeString("Count", fw.NestedPanes.Count.ToString(CultureInfo.InvariantCulture));
                    foreach (DockPane pane in fw.NestedPanes)
                    {
                        xmlOut.WriteStartElement("Pane");
                        xmlOut.WriteAttributeString("ID", fw.NestedPanes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteAttributeString("RefID", dockPanel.Panes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
                        NestedDockingStatus status = pane.NestedDockingStatus;
                        xmlOut.WriteAttributeString("PrevPane", dockPanel.Panes.IndexOf(status.PreviousPane).ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteAttributeString("Alignment", status.Alignment.ToString());
                        xmlOut.WriteAttributeString("Proportion", status.Proportion.ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteEndElement();
                    }
                    xmlOut.WriteEndElement();
                    xmlOut.WriteEndElement();
                }
                xmlOut.WriteEndElement();       //	</FloatWindows>

                xmlOut.WriteEndElement();

                if (!upstream)
                {
                    xmlOut.WriteEndDocument();
                    xmlOut.Close();
                }
                else
                {
                    xmlOut.Flush();
                }
            }
Beispiel #52
0
        //flush the cache to disk in XML format & possibly apply XSL
        private void WriteXPLasXML()
        {
            bool   tmpFile = false;
            string tempXML = mPath + mXML + "tmp0.xml";

            if (File.Exists(mPath + mXML))
            {
                try
                {
                    if (File.Exists(tempXML))
                    {
                        File.Delete(tempXML);
                    }
                    File.Move(mPath + mXML, tempXML);
                    tmpFile = true;
                }
                catch (Exception ex)
                {
                    //Log
                    EventLog.WriteEntry("File IO error: " + ex.Message, EventLogEntryType.Error);
                    //cannot continue
                    return;
                }
            }
            else
            {
                tmpFile = false;
            }

            XmlTextWriter xw = new XmlTextWriter(mPath + mXML, null);

            try
            {
                xw.Formatting = Formatting.Indented;
                xw.WriteStartDocument();
                xw.WriteComment("File generated by " + VENDORID + "-" + DEVICEID);

                //add the following 2 lines if you want an inline style-sheet
                //if (mXSL.Length>0)
                //	xw.WriteProcessingInstruction("xml-stylesheet","type='text/xsl' href='" + mXSL + "'");

                xw.WriteStartElement("log");

                XplMsg m;
                //write cached msgs, FIFO
                for (int i = MsgCacheIdx - 1; i >= 0; i--)
                {
                    m = MsgCache[i];
                    xw.WriteStartElement("xplmsg");
                    xw.WriteAttributeString("logdate", XmlConvert.ToString(MsgCacheIn[i], "dd-MM-yy HH:mm:ss"));

                    xw.WriteStartElement("header");

                    xw.WriteElementString("msgtype", m.MsgTypeString);

                    xw.WriteStartElement("source");
                    xw.WriteElementString("vendor", m.SourceVendor);
                    xw.WriteElementString("device", m.SourceDevice);
                    xw.WriteElementString("instance", m.SourceInstance);
                    xw.WriteEndElement();                      //source

                    xw.WriteStartElement("target");
                    xw.WriteElementString("vendor", m.TargetVendor);
                    xw.WriteElementString("device", m.TargetDevice);
                    xw.WriteElementString("instance", m.TargetInstance);
                    xw.WriteEndElement();                      //target

                    xw.WriteEndElement();                      //header

                    xw.WriteStartElement("schema");
                    xw.WriteElementString("class", m.Class);
                    xw.WriteElementString("type", m.Type);

                    xw.WriteStartElement("infopairs");

                    foreach (XplMsg.KeyValuePair kv in m.KeyValues)
                    {
                        xw.WriteStartElement("info");
                        xw.WriteAttributeString("name", kv.Key);
                        xw.WriteAttributeString("value", kv.Value);
                        xw.WriteEndElement();
                    }
                    xw.WriteEndElement();                      //infopairs
                    xw.WriteEndElement();                      //schema

                    xw.WriteStartElement("raw");

                    xw.WriteCData(m.RawXPL);

                    xw.WriteEndElement();                      //raw

                    xw.WriteEndElement();                      //xplmsg
                }
            }

            catch (Exception ex)
            {
                //log
                EventLog.WriteEntry("XML Write file IO error: " + ex.Message, EventLogEntryType.Error);
                //try to restore the backup
                if (xw != null)
                {
                    xw.Close();
                }
                try
                {
                    if (File.Exists(mPath + mXML))
                    {
                        File.Delete(mPath + mXML);
                    }
                    File.Move(tempXML, mPath + mXML);
                    EventLog.WriteEntry("Restored log to previous state", EventLogEntryType.Warning);
                }
                catch
                {
                    EventLog.WriteEntry("Could not restore log to previous state", EventLogEntryType.Error);
                }
                //and quit
                return;
            }

            bool addendtag = true;

            if (tmpFile)
            {
                int n = 0;

                //copy nodes from previous log
                XmlTextReader xr = new XmlTextReader(tempXML);
                xr.WhitespaceHandling = WhitespaceHandling.None;
                xr.MoveToContent();
                xr.Read();
                while ((n < mLogSize - MsgCacheIdx) && !xr.EOF)
                {
                    n++;
                    xw.WriteNode(xr, false);
                    if (xr.EOF)
                    {
                        addendtag = false;
                    }
                }
                xr.Close();
            }

            if (addendtag)              //funny: the nodes copied from xr also add an end tag ?!
            {
                xw.WriteEndElement();   //log
            }
            xw.Close();

            if (mXSL.Length > 0 && mOut.Length > 0)
            {
                ApplyXSL();
            }
        }
Beispiel #53
0
        public void Save()
        {
            projectPath = ProjectPathFromFile(projectPath);

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

            writer.Formatting = Formatting.Indented;

            writer.WriteStartElement("NUnitProject");

            if (configs.Count > 0 || this.BasePath != this.DefaultBasePath)
            {
                writer.WriteStartElement("Settings");
                if (configs.Count > 0)
                {
                    writer.WriteAttributeString("activeconfig", ActiveConfigName);
                }
                if (this.BasePath != this.DefaultBasePath)
                {
                    writer.WriteAttributeString("appbase", this.BasePath);
                }
                if (this.AutoConfig)
                {
                    writer.WriteAttributeString("autoconfig", "true");
                }
                if (this.ProcessModel != ProcessModel.Default)
                {
                    writer.WriteAttributeString("processModel", this.ProcessModel.ToString());
                }
                if (this.DomainUsage != DomainUsage.Default)
                {
                    writer.WriteAttributeString("domainUsage", this.DomainUsage.ToString());
                }
                writer.WriteEndElement();
            }

            foreach (ProjectConfig config in Configs)
            {
                writer.WriteStartElement("Config");
                writer.WriteAttributeString("name", config.Name);
                string appbase = config.BasePath;
                if (!PathUtils.SamePathOrUnder(this.BasePath, appbase))
                {
                    writer.WriteAttributeString("appbase", appbase);
                }
                else if (config.RelativeBasePath != null)
                {
                    writer.WriteAttributeString("appbase", config.RelativeBasePath);
                }

                string configFile = config.ConfigurationFile;
                if (configFile != null && configFile != this.ConfigurationFile)
                {
                    writer.WriteAttributeString("configfile", config.ConfigurationFile);
                }

                if (config.BinPathType == BinPathType.Manual)
                {
                    writer.WriteAttributeString("binpath", config.PrivateBinPath);
                }
                else
                {
                    writer.WriteAttributeString("binpathtype", config.BinPathType.ToString());
                }

                if (config.RuntimeFramework != null)
                {
                    writer.WriteAttributeString("runtimeFramework", config.RuntimeFramework.ToString());
                }

                foreach (string assembly in config.Assemblies)
                {
                    writer.WriteStartElement("assembly");
                    writer.WriteAttributeString("path", PathUtils.RelativePath(config.BasePath, assembly));
                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
            }

            writer.WriteEndElement();

            writer.Close();
            this.IsDirty = false;

            // Once we save a project, it's no longer
            // loaded as an assembly wrapper on reload.
            this.isAssemblyWrapper = false;
        }
Beispiel #54
0
    // <Snippet2>
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, string SubjectName)
    {
        if (null == FileName)
        {
            throw new ArgumentNullException("FileName");
        }
        if (null == SignedFileName)
        {
            throw new ArgumentNullException("SignedFileName");
        }
        if (null == SubjectName)
        {
            throw new ArgumentNullException("SubjectName");
        }

        // Load the certificate from the certificate store.
        X509Certificate2 cert = GetCertificateBySubject(SubjectName);

        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Format the document to ignore white spaces.
        doc.PreserveWhitespace = false;

        // Load the passed XML file using it's name.
        doc.Load(new XmlTextReader(FileName));

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(doc);

        // Add the key to the SignedXml document.
        signedXml.SigningKey = cert.PrivateKey;

        // Create a reference to be signed.
        Reference reference = new Reference();

        reference.Uri = "";

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

        reference.AddTransform(env);

        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);

        // Create a new KeyInfo object.
        KeyInfo keyInfo = new KeyInfo();

        // Load the certificate into a KeyInfoX509Data object
        // and add it to the KeyInfo object.
        keyInfo.AddClause(new KeyInfoX509Data(cert));

        // Add the KeyInfo object to the SignedXml object.
        signedXml.KeyInfo = keyInfo;

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

        if (doc.FirstChild is XmlDeclaration)
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        using (XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)))
        {
            doc.WriteTo(xmltw);
            xmltw.Close();
        }
    }
Beispiel #55
0
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            tainted_2 = args[1];

            tainted_3 = tainted_2;

            if ((1 == 0))
            {
                {}
            }
            else
            {
                StringBuilder escape = new StringBuilder();
                for (int i = 0; i < tainted_2.Length; ++i)
                {
                    char current = tainted_2[i];
                    switch (current)
                    {
                    case '\\':
                        escape.Append(@"\5c");
                        break;

                    case '*':
                        escape.Append(@"\2a");
                        break;

                    case '(':
                        escape.Append(@"\28");
                        break;

                    case ')':
                        escape.Append(@"\29");
                        break;

                    case '\u0000':
                        escape.Append(@"\00");
                        break;

                    case '/':
                        escape.Append(@"\2f");
                        break;

                    default:
                        escape.Append(current);
                        break;
                    }
                }
                tainted_3 = escape.ToString();
            }


            string query = tainted_3;


            string        filename = "file.xml";
            XDocument     document = XDocument.Load(filename);
            XmlTextWriter writer   = new XmlTextWriter(Console.Out);

            writer.Formatting = Formatting.Indented;
            var node = document.Root.Elements("foo")
                       .Where(x => (string)x.Element("bar") == query)
                       .SingleOrDefault();

            node.WriteTo(writer);
            writer.Close( );
        }
Beispiel #56
0
        private void xmlcamera(bool write)
        {
            string filename = "cameras.xml";

            if (write || !File.Exists(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + filename))
            {
                try
                {
                    XmlTextWriter xmlwriter = new XmlTextWriter(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + filename, Encoding.ASCII);
                    xmlwriter.Formatting = Formatting.Indented;

                    xmlwriter.WriteStartDocument();

                    xmlwriter.WriteStartElement("Cameras");

                    foreach (string key in cameras.Keys)
                    {
                        try
                        {
                            if (key == "")
                            {
                                continue;
                            }
                            xmlwriter.WriteStartElement("Camera");
                            xmlwriter.WriteElementString("name", cameras[key].name);
                            xmlwriter.WriteElementString("flen", cameras[key].focallen.ToString(new System.Globalization.CultureInfo("en-US")));
                            xmlwriter.WriteElementString("imgh", cameras[key].imageheight.ToString(new System.Globalization.CultureInfo("en-US")));
                            xmlwriter.WriteElementString("imgw", cameras[key].imagewidth.ToString(new System.Globalization.CultureInfo("en-US")));
                            xmlwriter.WriteElementString("senh", cameras[key].sensorheight.ToString(new System.Globalization.CultureInfo("en-US")));
                            xmlwriter.WriteElementString("senw", cameras[key].sensorwidth.ToString(new System.Globalization.CultureInfo("en-US")));
                            xmlwriter.WriteEndElement();
                        }
                        catch { }
                    }

                    xmlwriter.WriteEndElement();

                    xmlwriter.WriteEndDocument();
                    xmlwriter.Close();
                }
                catch (Exception ex) { CustomMessageBox.Show(ex.ToString()); }
            }
            else
            {
                try
                {
                    using (XmlTextReader xmlreader = new XmlTextReader(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + filename))
                    {
                        while (xmlreader.Read())
                        {
                            xmlreader.MoveToElement();
                            try
                            {
                                switch (xmlreader.Name)
                                {
                                case "Camera":
                                {
                                    camerainfo camera = new camerainfo();

                                    while (xmlreader.Read())
                                    {
                                        bool dobreak = false;
                                        xmlreader.MoveToElement();
                                        switch (xmlreader.Name)
                                        {
                                        case "name":
                                            camera.name = xmlreader.ReadString();
                                            break;

                                        case "imgw":
                                            camera.imagewidth = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US"));
                                            break;

                                        case "imgh":
                                            camera.imageheight = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US"));
                                            break;

                                        case "senw":
                                            camera.sensorwidth = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US"));
                                            break;

                                        case "senh":
                                            camera.sensorheight = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US"));
                                            break;

                                        case "flen":
                                            camera.focallen = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US"));
                                            break;

                                        case "Camera":
                                            cameras.Add(camera.name, camera);
                                            CMB_camera.Items.Add(camera.name);
                                            dobreak = true;
                                            break;
                                        }
                                        if (dobreak)
                                        {
                                            break;
                                        }
                                    }
                                    string temp = xmlreader.ReadString();
                                }
                                break;

                                case "Config":
                                    break;

                                case "xml":
                                    break;

                                default:
                                    if (xmlreader.Name == "")     // line feeds
                                    {
                                        break;
                                    }
                                    //config[xmlreader.Name] = xmlreader.ReadString();
                                    break;
                                }
                            }
                            catch (Exception ee) { Console.WriteLine(ee.Message); } // silent fail on bad entry
                        }
                    }
                }
                catch (Exception ex) { Console.WriteLine("Bad Camera File: " + ex.ToString()); } // bad config file
            }
        }
Beispiel #57
0
        // speichert den gesamten Datenbank in personal_verwaltung.xml
        private void btnSaveDbInXml_Click(object sender, EventArgs e)
        {
            try
            {
                // XML-Datei erzeugen
                XmlTextWriter myXmlTextWriter = new XmlTextWriter("personal_verwaltung.xml", System.Text.Encoding.UTF8);
                myXmlTextWriter.Formatting = Formatting.Indented;
                myXmlTextWriter.WriteStartDocument(false);

                myXmlTextWriter.WriteStartElement("PersonalVerwaltung"); // Haupttag Init

                myXmlTextWriter.WriteStartElement("Mitarbeiter");
                foreach (Mitarbeiter ma in listMA)
                {
                    myXmlTextWriter.WriteStartElement("Mitarbeiter", null);
                    myXmlTextWriter.WriteAttributeString("MitarbeiterID", ma.ma_id.ToString());
                    myXmlTextWriter.WriteAttributeString("Nachname", ma.nachname);
                    myXmlTextWriter.WriteAttributeString("Vorname", ma.vorname);
                    myXmlTextWriter.WriteAttributeString("Geburtsdatum", ma.geburtsdatum.ToShortDateString());
                    myXmlTextWriter.WriteAttributeString("tagesArbeitszeit", ma.tagesArbeitszeit.ToString());
                    myXmlTextWriter.WriteAttributeString("urlaubsAnspruch", ma.urlaubsAnspruch.ToString());
                    myXmlTextWriter.WriteEndElement();
                }
                myXmlTextWriter.WriteEndElement(); // Mitarbeiter

                myXmlTextWriter.WriteStartElement("Einsatz");
                foreach (Einsatz ei in listE)
                {
                    myXmlTextWriter.WriteStartElement("Einsatz", null);
                    myXmlTextWriter.WriteAttributeString("EinsatzID", ei.e_id.ToString());
                    myXmlTextWriter.WriteAttributeString("MitarbeiterID", ei.ma_id.ToString());
                    myXmlTextWriter.WriteAttributeString("Datum", ei.e_datum.ToShortDateString());
                    myXmlTextWriter.WriteAttributeString("ZeitVon", ei.e_von.ToString());
                    myXmlTextWriter.WriteAttributeString("ZeitBis", ei.e_bis.ToString());
                    myXmlTextWriter.WriteEndElement();
                }
                myXmlTextWriter.WriteEndElement(); // Einsatz

                myXmlTextWriter.WriteStartElement("Fehlzeit");
                foreach (Fehlzeit fz in listFZ)
                {
                    myXmlTextWriter.WriteStartElement("Fehlzeit", null);
                    myXmlTextWriter.WriteAttributeString("FehlzeitID", fz.fz_id.ToString());
                    myXmlTextWriter.WriteAttributeString("MitarbeiterID", fz.ma_id.ToString());
                    myXmlTextWriter.WriteAttributeString("FehlzeitVon", fz.fz_von.ToShortDateString());
                    myXmlTextWriter.WriteAttributeString("FehlzeitBis", fz.fz_bis.ToShortDateString());
                    myXmlTextWriter.WriteAttributeString("Fehlgrund", fz.fehlgrund.ToString());
                    myXmlTextWriter.WriteAttributeString("Fehltage", fz.fehltage.ToString());
                    myXmlTextWriter.WriteEndElement();
                }
                myXmlTextWriter.WriteEndElement(); // Fehlzeit


                myXmlTextWriter.WriteStartElement("Fehlgrund");
                foreach (Fehlgrund fg in listFG)
                {
                    myXmlTextWriter.WriteStartElement("Fehlgrund", null);
                    myXmlTextWriter.WriteAttributeString("FehlgrundID", fg.fg_id.ToString());
                    myXmlTextWriter.WriteAttributeString("Fehlgrund", fg.fehlgrund);
                    myXmlTextWriter.WriteEndElement();
                }
                myXmlTextWriter.WriteEndElement(); // Fehlgrund

                // aufraeumen
                myXmlTextWriter.WriteEndElement(); // Init
                myXmlTextWriter.Flush();
                myXmlTextWriter.Close();
                MessageBox.Show("Der Datenbank wurde in einer XML-Datei erfolgreich geschrieben");
            }
            catch (Exception ex)
            {
                MessageBox.Show("AusnahmeFehler XML-Schreiben. Bitte notieren. " + ex.Message);
            }
        }
Beispiel #58
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Clear();
            Response.ContentType = "application/rss+xml";
            //Response.AppendHeader("Refresh", "120");

            XmlTextWriter objX = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);

            objX.WriteStartDocument();
            objX.WriteStartElement("rss");
            objX.WriteAttributeString("version", "2.0");

            objX.WriteAttributeString("xmlns:stats", "http://tempuri.org");

            objX.WriteStartElement("channel");

            objX.WriteElementString("title", "EWA DataFlow Report");

            objX.WriteElementString("stats:sender_name", "Sender name");
            objX.WriteElementString("stats:frequency", "Frequency of data");
            objX.WriteElementString("stats:table_code", "Table code");
            objX.WriteElementString("stats:ref_area", "Reference area");
            objX.WriteElementString("stats:dataset", "Dataset");
            objX.WriteElementString("stats:csv_file", "CSV filepath");
            objX.WriteElementString("stats:prepared_date", "Prepared date");
            objX.WriteElementString("stats:last_modified_date", "Last modified date");
            objX.WriteElementString("stats:COMMENT_DSET", "Comment dataset");
            objX.WriteElementString("stats:COMMENT_TS_FIRST", "Comments series");

            //objX.WriteElementString("stats:COMMENT_OBS", "Comments obs");

            objX.WriteElementString("description", "Files that arrive in EWA appear here");
            objX.WriteElementString("language", "en-us");
            objX.WriteElementString("ttl", "60");
            objX.WriteElementString("lastBuildDate", String.Format("{0:R}", DateTime.Now));

            int FileCreationDateDaysLimit = 0;
            int FileCountLimit            = 0;

            if (Request["FileCreationDateDaysLimit"] != null)
            {
                int.TryParse(Request["FileCreationDateDaysLimit"].ToString(), out FileCreationDateDaysLimit);
            }

            if (Request["FileCountLimit"] != null)
            {
                int.TryParse(Request["FileCountLimit"].ToString(), out FileCountLimit);
            }

            //FileCountLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileCountLimit"]);

            // Put all file names in root directory into array.
            var orderedFiles = new System.IO.DirectoryInfo(ConfigurationManager.AppSettings["EWAPath"])
                               .GetFiles("*.*")
                               .Where(f =>
                                      (FileCreationDateDaysLimit > 0 && f.CreationTime >= DateTime.Now.AddDays(-FileCreationDateDaysLimit)) ||
                                      (FileCreationDateDaysLimit == 0)
                                      )
                               .OrderByDescending(x => x.CreationTime);

            //string[] extensions = new[] { ".jpg", ".tiff", ".bmp" };

            int i = 0;

            // Loop thru files
            foreach (System.IO.FileInfo SDMXFile in orderedFiles)
            {
                // Ignore zipped and non-XML files.  Allow files that are XML but with wrong file extension.
                if (SDMXFile.Extension == ".7z" || SDMXFile.Extension == ".zip" || SDMXFile.Extension == ".csv" ||
                    SDMXFile.Extension.StartsWith(".xls") || SDMXFile.Extension.StartsWith(".doc"))
                {
                    continue;
                }

                i++;
                //string FileName = SDMXFile.Substring(SDMXFile.LastIndexOf('\\') + 1);
                string FileName = SDMXFile.Name;

                // only process information for SDMX files
                objX.WriteStartElement("item");

                // if SDMX file
                try
                {
                    string[] ID_Bits = null;
                    string   TableCode = "";
                    string   DSD = "";
                    string   SenderCode = "";
                    string   SenderName = "";
                    DateTime PublishDate = DateTime.MinValue;
                    string   PreparedDate = "", ReportDate = "";
                    string   Content    = "";
                    string   CSVFile    = "";
                    string   sError     = "";
                    string   Freq       = "";
                    string   Country    = "";
                    bool     bInHeader  = false;
                    bool     bInDataSet = false;

                    string CommentDataSet = "", CommentSeriesFirst = "";

                    bool Validated = FileName.ToLower().Contains("_valid_");

                    XmlReaderSettings settings = new XmlReaderSettings();
                    settings.IgnoreWhitespace             = true;
                    settings.IgnoreProcessingInstructions = true;
                    settings.IgnoreComments = true;

                    XmlReader xmlReader = XmlReader.Create(SDMXFile.FullName, settings);

                    // Read each line in the file
                    while (xmlReader.Read())
                    {
                        //CommentsSeries = new List<string>();
                        //CommentsObs = new List<string>();
                        //string CommentSeries = "", CommentObs = "";

                        if (xmlReader.LocalName == "Header" && xmlReader.NodeType == XmlNodeType.Element)
                        {
                            bInHeader = true;
                        }
                        if (xmlReader.LocalName == "DataSet" && xmlReader.NodeType == XmlNodeType.Element)
                        {
                            bInHeader  = false;
                            bInDataSet = true;
                        }

                        // If we're in the header
                        if (bInHeader && xmlReader.NodeType == XmlNodeType.Element)
                        {
                            // Get table code from header DataSetID or ID
                            if (xmlReader.LocalName == "DataSetID")
                            {
                                ID_Bits = xmlReader.ReadString().Split('_');
                            }
                            if (ID_Bits == null && xmlReader.LocalName == "ID")
                            {
                                ID_Bits = xmlReader.ReadString().Split('_');
                            }

                            if (xmlReader.LocalName == "Sender")
                            {
                                SenderCode += xmlReader.GetAttribute("id");
                            }
                            if (xmlReader.LocalName == "Name")
                            {
                                SenderName += xmlReader.ReadString();
                            }
                            if (xmlReader.LocalName == "Prepared")
                            {
                                try
                                {
                                    PreparedDate += xmlReader.ReadString();

                                    PreparedDate = PreparedDate.Replace('T', ' ').Trim();
                                    PreparedDate = PreparedDate.Substring(0, 16);

                                    PublishDate = DateTime.ParseExact(PreparedDate, "yyyy-MM-dd HH:mm", System.Globalization.CultureInfo.InvariantCulture);

                                    ReportDate = PublishDate.Year + "-" + PublishDate.Month.ToString("D2") + "-" + PublishDate.Day.ToString("D2") + " " + PublishDate.Hour.ToString("D2") + ":" + PublishDate.Minute.ToString("D2") + ":" + PublishDate.Second.ToString("D2");
                                }
                                catch (Exception ex)
                                {
                                    sError = "; Wrong format prepared date:" + PreparedDate;
                                }
                            }
                        }
                        // If we're not in the header
                        else if (bInDataSet && xmlReader.NodeType == XmlNodeType.Element)
                        {
                            //COMMENT_DSET
                            if (xmlReader.LocalName == "DataSet")
                            {
                                CommentDataSet = xmlReader.GetAttribute("COMMENT_DSET");
                            }

                            if (xmlReader.LocalName == "Series")
                            {
                                Freq    = xmlReader.GetAttribute("FREQ");
                                Country = xmlReader.GetAttribute("REF_AREA");

                                CommentSeriesFirst = xmlReader.GetAttribute("COMMENT_TS");
                                //if (CommentSeries != null && CommentSeries != "") CommentsSeries.Add(CommentSeries);

                                break; // Stop reading the file
                            }
                        }
                    } // end while loop on file lines

                    xmlReader.Close();

                    // Cleanup TableCode and DSD value
                    if (ID_Bits != null)
                    {
                        if (ID_Bits.Count() > 1)
                        {
                            TableCode = ID_Bits[1].ToString().Trim();
                            DSD       = ID_Bits[0].ToString().Trim();
                        }
                        else
                        {
                            TableCode = ID_Bits[0];
                        }
                    }

                    //// Build content string
                    Content =
                        "TableCode:" + TableCode
                        + "; Frequency:" + Freq
                        + "; Country:" + Country
                        + "; Validated:" + Validated
                        + "; DSD:" + DSD
                        + "; SenderCode:" + SenderCode
                        + "; SenderName:" + SenderName;

                    if (sError != "")
                    {
                        Content += sError;
                    }


                    // Make CSV file name
                    if (Validated)
                    {
                        CSVFile = ConfigurationManager.AppSettings["CSVPath"] + FileName.Replace(".xml", ".csv");
                    }

                    // Write RSS object

                    objX.WriteElementString("stats:dataset", DSD);

                    objX.WriteElementString("stats:frequency", Freq);

                    objX.WriteElementString("stats:table_code", TableCode);

                    objX.WriteElementString("stats:ref_area", Country);

                    objX.WriteElementString("title", FileName);

                    objX.WriteElementString("stats:prepared_date", ReportDate);

                    objX.WriteElementString("stats:last_modified_date", SDMXFile.LastWriteTime.ToShortDateString() + " " + SDMXFile.LastWriteTime.ToShortTimeString());

                    if (PublishDate != DateTime.MinValue)
                    {
                        objX.WriteElementString("pubDate", String.Format("{0:R}", PublishDate));
                    }

                    objX.WriteElementString("author", SenderCode);

                    objX.WriteElementString("stats:sender_name", SenderName);

                    objX.WriteStartElement("category");
                    if (Validated)
                    {
                        objX.WriteString("Validated");
                    }
                    else
                    {
                        objX.WriteString("Not validated");
                    }
                    objX.WriteEndElement(); // end category

                    objX.WriteElementString("stats:csv_file", CSVFile);

                    objX.WriteElementString("enclosure", SDMXFile.FullName);

                    objX.WriteElementString("stats:COMMENT_DSET", CommentDataSet);
                    objX.WriteElementString("stats:COMMENT_TS_FIRST", CommentSeriesFirst);

                    //objX.WriteElementString("stats:COMMENT_TS", CommentsSeries);
                    //objX.WriteElementString("stats:COMMENT_OBS", CommentsObs);
                }
                catch (Exception ex)
                {
                    objX.WriteElementString("title", FileName + " is not valid SDMX");
                    objX.WriteElementString("author", "");
                    objX.WriteStartElement("category");
                    objX.WriteString("Invalid");
                    objX.WriteEndElement(); // end category
                }

                objX.WriteEndElement(); // end item

                // If the no of files to process is not limited by the request parameters, limit it by the file count limit
                if (FileCreationDateDaysLimit == 0 && i > FileCountLimit)
                {
                    break;
                }
            } // loop

            objX.WriteEndElement();
            objX.WriteEndElement();

            objX.WriteEndDocument();

            objX.Flush();
            objX.Close();
            Response.End();
        }
        /// <summary>
        /// データベース保存
        /// </summary>
        public void Save()
        {
            if (this.GetChanges() == null)
            {
                //変更無し
                return;
            }


            //*.tmpファイル名生成
            string tmpFilename = Common.File.GetWithoutExtension(this.TranslationDataTableFilePath) + ".tmp";

            if (Common.File.ExistsFile(tmpFilename))
            {
                //*.tmpが存在したら消す
                Common.File.DeleteFile(tmpFilename);
            }


            //シリアライズしてXMLで保存
            //一旦*.tmpで保存
            using (XmlTextWriter sw = new XmlTextWriter(tmpFilename,
                                                        new System.Text.UTF8Encoding(false)))
            {
                sw.Formatting = Formatting.Indented;
                sw.WriteStartDocument();

                //ソートしてXML保存する
                var sortOrder = new System.Text.StringBuilder();
                sortOrder.Append(ColumnNameDirName + " ASC");
                sortOrder.Append(",");
                sortOrder.Append(ColumnNameExists + " DESC");
                sortOrder.Append(",");
                sortOrder.Append(ColumnNameSortOrder + " ASC");


                // dtのスキーマや制約をコピーしたDataTableを作成します。
                System.Data.DataTable sortTable = this.Clone();
                DataRow[]             rows      = this.Select(null, sortOrder.ToString());
                foreach (DataRow row in rows)
                {
                    DataRow addRow = sortTable.NewRow();
                    // カラム情報をコピーします。
                    addRow.ItemArray = row.ItemArray;
                    // DataTableに格納します。
                    sortTable.Rows.Add(addRow);
                }
                sortTable.WriteXml(sw);

                sw.WriteEndDocument();
                sw.Close();
            }


            //Bakファイル作成
            if (Common.File.ExistsFile(this.TranslationDataTableFilePath))
            {
                for (int i = 9; i >= 0; i--)
                {
                    string file1 = Common.File.GetWithoutExtension(this.TranslationDataTableFilePath) + (i == 0 ? ".bak" : ".bk" + i.ToString());
                    if (Common.File.ExistsFile(file1))
                    {
                        //存在したら消す
                        Common.File.DeleteFile(file1);
                    }
                    string file2 = Common.File.GetWithoutExtension(this.TranslationDataTableFilePath);
                    switch (i - 1)
                    {
                    case -1:
                        file2 += "." + Common.File.GetExtension(this.TranslationDataTableFilePath);
                        break;

                    case 0:
                        file2 += ".bak";
                        break;

                    default:
                        file2 += ".bk" + (i - 1).ToString();
                        break;
                    }
                    if (Common.File.ExistsFile(file2))
                    {
                        //存在したらファイル名変更
                        Common.File.MoveFile(file2, file1);
                    }
                }
            }


            //*.tmpを*.xmlへ変更
            Common.File.MoveFile(tmpFilename, this.TranslationDataTableFilePath);

            //正常に保存できたら、変更無しに設定
            this.AcceptChanges();
        }
Beispiel #60
0
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            tainted_2 = Console.ReadLine();

            tainted_3 = tainted_2;

            if ((Math.Sqrt(42) <= 42))
            {
                {}
            }
            else if (!(Math.Sqrt(42) <= 42))
            {
                StringBuilder escape = new StringBuilder();
                for (int i = 0; i < tainted_2.Length; ++i)
                {
                    char current = tainted_2[i];
                    switch (current)
                    {
                    case '\\':
                        escape.Append(@"\5c");
                        break;

                    case '*':
                        escape.Append(@"\2a");
                        break;

                    case '(':
                        escape.Append(@"\28");
                        break;

                    case ')':
                        escape.Append(@"\29");
                        break;

                    case '\u0000':
                        escape.Append(@"\00");
                        break;

                    case '/':
                        escape.Append(@"\2f");
                        break;

                    default:
                        escape.Append(current);
                        break;
                    }
                }
                tainted_3 = escape.ToString();
            }
            else
            {
                {}
            }

            //flaw

            string query = "//user[@name='" + tainted_3 + "']";


            string      filename = "file.xml";
            XmlDocument document = new XmlDocument( );

            document.Load(filename);
            XmlTextWriter writer = new XmlTextWriter(Console.Out);

            writer.Formatting = Formatting.Indented;

            XmlNode node = document.SelectSingleNode(query);

            node.WriteTo(writer);

            writer.Close( );
        }