Example #1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();
        Response.ContentType = "text/xml";
        XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
        writer.WriteStartDocument();
        writer.WriteStartElement("urlset");
        writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");

        string siteUrl = Request.Url.Scheme + Uri.SchemeDelimiter + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
        if (!Request.Url.IsDefaultPort)
        {
            siteUrl += ":" + Request.Url.Port;
        }
        Menu menu = new Menu();
        Utils.InitMenu(menu, false, false, false);
        foreach (MenuItem item in menu.Items)
        {
            writer.WriteStartElement("url");
            writer.WriteElementString("loc", siteUrl + item.NavigateUrl);
            writer.WriteEndElement();
            foreach (MenuItem childItem in item.ChildItems)
            {
                writer.WriteStartElement("url");
                writer.WriteElementString("loc", siteUrl + childItem.NavigateUrl);
                writer.WriteEndElement();
            }
        }
        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Flush();
        Response.End();
    }
Example #2
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);
            }
        }
    }
Example #3
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 ();
	}
Example #4
0
    static void Main()
    {
        XmlReader reader = XmlReader.Create("../../catalogue.xml");
        using (reader)
        {
            StreamWriter textWriter = new StreamWriter("../../albums.xml", false, Encoding.GetEncoding("utf-8"));
            XmlTextWriter writer = new XmlTextWriter(textWriter);
            using (writer)
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("album-catalog");
                while (reader.Read())
                {
                    if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "album"))
                    {
                        writer.WriteStartElement("album");
                        reader.ReadToDescendant("name");
                        writer.WriteElementString(reader.Name, reader.ReadInnerXml());
                        reader.ReadToNextSibling("artist");
                        writer.WriteElementString(reader.Name, reader.ReadInnerXml());
                        writer.WriteEndElement();
                    }
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
        }
    }
Example #5
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string folderpath = @"/var/www/weavver.com/messages";
          if (!Directory.Exists(folderpath))
              return;

          XmlTextWriter writer    = new XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8);
          writer.Indentation      = 5;
          writer.Formatting       = Formatting.Indented;
          WriteRSSPrologue(writer);
          int i = 0;

          Random r = new Random(10);
          foreach (string file in System.IO.Directory.GetFiles(folderpath))
          {
               if (file.EndsWith("wav"))
               {
                    string num = r.Next(10).ToString() + r.Next(10).ToString() + r.Next(10).ToString() + "-" + r.Next(10).ToString() + r.Next(10).ToString() + r.Next(10).ToString() + r.Next(10).ToString();
                    AddRSSItem(writer, "Jane Doe left you a message from 714-" + num, file, System.IO.Path.GetFileName(file), DateTime.Now.Subtract(TimeSpan.FromDays(i)).ToString("r"));
                    i++;
               }
               if (i > 10)
               {
                    break;
               }
          }
          WriteRSSClosing(writer);
          writer.Flush();
          writer.Close();

          Response.ContentEncoding = System.Text.Encoding.UTF8;
          Response.ContentType     = "text/xml";
          Response.Cache.SetCacheability(HttpCacheability.Private);
          Response.End();
    }
Example #6
0
	public object DeserializeObject(string pXmlizedString , System.Type ty)
	{
		XmlSerializer xs  = new XmlSerializer(ty);
		MemoryStream memoryStream  = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
		XmlTextWriter xmlTextWriter   = new XmlTextWriter(memoryStream, Encoding.UTF8);
		return xs.Deserialize(memoryStream);
	}
Example #7
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();

    }
    private void GetRssFeedContens(AspxCommonInfo aspxCommonObj, string pageURL, int count)
    {
        try
        {
            string[] path = pageURL.Split('?');
            string pagepath = path[0];
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "text/xml";
            XmlTextWriter rssXml = new XmlTextWriter(HttpContext.Current.Response.OutputStream, Encoding.UTF8);

            rssXml.WriteStartDocument();

            rssXml.WriteStartElement("rss");
            rssXml.WriteAttributeString("version", "2.0");
            rssXml.WriteStartElement("channel");
            rssXml.WriteElementString("link", pagepath);
            rssXml.WriteElementString("title", getLocale("AspxCommerce Services"));
            GetItemRssFeedContents(aspxCommonObj, rssXml, pageURL,count);
            rssXml.WriteEndElement();
            rssXml.WriteEndElement();
            rssXml.WriteEndDocument();
            rssXml.Flush();
            rssXml.Close();
            HttpContext.Current.Response.End();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    static void Main()
    {
        using (var writer = new XmlTextWriter(filePath, encoding))
        {
            writer.Formatting = Formatting.Indented;
            writer.IndentChar = '\t';
            writer.Indentation = 1;

            writer.WriteStartDocument();
            writer.WriteStartElement("catalogue");
            writer.WriteAttributeString("name", "Awesome Mix Vol. 1");

            WriteAlbum(writer, "Hooked on a Feeling", "Blue Swede", 1968, "Scepter Records", 20);

            WriteAlbum(writer, "Record World", "Raspberries", 1972, "Capitol Records", 18.50m,
                new List<string>() { "Don't Want to Say Goodbye", "Go All the Way", "I Wanna Be with You" });

            WriteAlbum(writer, "Starting Over", "Raspberries", 1974, "Capitol", 17.50m);

            WriteAlbum(writer, "Wovoka", "Redbone", 1974, "Lolly Vegas", 11,
                new List<string>() { "Come and Get Your Love", "When You Got Trouble" });

            WriteAlbum(writer, "The 5th Dimension", "Blue Swede", 1974, "Warner Bros.", 9.99m);

            writer.WriteEndDocument();
        }

        Console.WriteLine("Document saved to {0}", filePath);
    }
Example #10
0
    static void Main()
    {
        using (var reader = new StreamReader(inputFile))
        {
            string line = reader.ReadLine();

            if (line == null)
            {
                Console.WriteLine("The text file is empty");
                return;
            }

            using (var writer = new XmlTextWriter(outputFile, Encoding.UTF8))
            {
                writer.Formatting = Formatting.Indented;
                writer.IndentChar = '\t';
                writer.Indentation = 1;

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

                while (line != null)
                {
                    var tokens = line.Split(';').Select(t => t.Trim()).ToArray();

                    WritePerson(writer, name: tokens[0], address: tokens[1], phone: tokens[2]);
                    line = reader.ReadLine();
                }

                writer.WriteEndDocument();

                Console.WriteLine("XML file saved to {0}", outputFile);
            }
        }
    }
    private void Images()
    {
         // Dataset containing 
        string catname ="Electricals";
        ProductImageService.serProdctImage prodimage = new ProductImageService.serProdctImage();
        DataSet dataset = prodimage.ProductImage_GetFashImgtwoForHandler(catname);
        //string x = dataset.GetXml();
        string xmlfile = dataset.GetXml();

        XslTransform xslt = new XslTransform();
        xslt.Load(Server.MapPath("~/xslt/HomeXSLTFile.xslt"));
        XPathDocument xpathdocument = new
        XPathDocument(xmlfile);
        XmlTextWriter writer = new XmlTextWriter(Console.Out);
        writer.Formatting = Formatting.Indented;

        xslt.Transform(xpathdocument, null, writer, null);
        


        //strstudentDetails = GetHtml(Server.MapPath("~/xsl/studentDetails.xsl"), strXML);

        //XPathDocument myXPathDoc = new XPathDocument(myXmlFile);
        //XslCompiledTransform myXslTrans = new XslCompiledTransform();
        //myXslTrans.Load(myStyleSheet);
        //XmlTextWriter myWriter = new XmlTextWriter("result.html", null);
        //myXslTrans.Transform(myXPathDoc, null, myWriter);
     }
Example #12
0
 private void AddURL(XmlTextWriter writer, string siteUrl, string url, DateTime dateUpdate)
 {
     writer.WriteStartElement("url");
     writer.WriteElementString("loc", siteUrl + url);
     writer.WriteElementString("lastmod", String.Format("{0:yyyy-MM-dd}", dateUpdate));
     writer.WriteEndElement();
 }
    /* 08. Write a program, which (using XmlReader and XmlWriter) reads the file catalog.xml 
     * and creates the file album.xml, in which stores in appropriate way 
     * the names of all albums and their authors.*/

    static void Main(string[] args)
    {
        using (XmlReader reader = XmlReader.Create("../../catalog.xml"))
        {
            string fileName = "../../albums.xml";
            Encoding encoding = Encoding.GetEncoding("windows-1251");
            using (XmlTextWriter writer = new XmlTextWriter(fileName, encoding))
            {
                writer.Formatting = Formatting.Indented;
                writer.IndentChar = '\t';
                writer.Indentation = 1;

                writer.WriteStartDocument();
                writer.WriteStartElement("albums");
                var title = string.Empty;
                var artist = string.Empty;

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.Name == "name")
                        {
                            title = reader.ReadElementString();
                        }
                        else if (reader.Name == "artist")
                        {
                            artist = reader.ReadElementString();
                            WriteAlbum(writer, title, artist);
                        }
                    }
                }
            }
        }
    }
    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());
    }
Example #15
0
    public static void WriteOutput(object data, Stream output, bool closeStreams )
    {
        if (data == output) return;

        XmlDocument xml = data as XmlDocument;
        if (xml != null)
        {
            XmlTextWriter xmlWriter = new XmlTextWriter(output, System.Text.Encoding.UTF8);
            xml.WriteTo(xmlWriter);
            xmlWriter.Flush();
        }

        Stream stream = data as Stream;
        if (stream != null)
        {
            stream.Seek(0, SeekOrigin.Begin);
            byte[] buffer = new byte[0x5000];
            int read;
            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                output.Write(buffer, 0, read);

            if ( closeStreams ) stream.Close();
        }

        byte[] block = data as byte[];
        if ( block != null && block.Length > 0 )
            output.Write( block, 0, block.Length );
    }
Example #16
0
    private void AddRequestXml(string url, HttpWebRequest req)
    {
        Stream stream = (Stream)req.GetRequestStream();
        using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
        {
            writer.WriteStartDocument(true);
            writer.WriteStartElement("methodCall");
            writer.WriteElementString("methodName", "pingback.ping");
            writer.WriteStartElement("params");

            writer.WriteStartElement("param");
            writer.WriteStartElement("value");
            writer.WriteElementString("string", Blogsa.Url);
            writer.WriteEndElement();
            writer.WriteEndElement();

            writer.WriteStartElement("param");
            writer.WriteStartElement("value");
            writer.WriteElementString("string", url);
            writer.WriteEndElement();
            writer.WriteEndElement();

            writer.WriteEndElement();
            writer.WriteEndElement();
        }
    }
Example #17
0
    static void ComplexSearch(XmlTextWriter writer)
    {
        BookstoreEntities context = new BookstoreEntities();
        using (context)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Bookstore.Data.Settings.Default.complexSearchReadFile);
            XmlNodeList queries = doc.SelectNodes("/review-queries/query");
            foreach (XmlNode query in queries)
            {
                string type = query.Attributes["type"].Value;
                if (type == "by-period")
                {
                    string start = query.SelectSingleNode("start-date").InnerText;
                    string end = query.SelectSingleNode("end-date").InnerText;
                    IList<Review> found =
                        BookstoreDAL.FindReviewPeriod(start, end, context);
                    WriteResultSet(writer, found);
                }
                else if (type == "by-author")
                {
                    string author = query.SelectSingleNode("author-name").InnerText;
                    IList<Review> found =
                        BookstoreDAL.FindReviewAuthor(author, context);
                    WriteResultSet(writer, found);
                }

                SearchLogsImporter.AddLog(DateTime.Now, query.OuterXml);
            }
        }
    }
Example #18
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;
 }
Example #19
0
    public List<string> GetSpeaking_PracticeContents(int ID_Unit)
    {
        IEnumerable<SPEAKING> speaking_Practices = this.GetSpeakingUnit(ID_Unit);

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

        foreach (SPEAKING item in speaking_Practices)
        {
            XmlDocument xmlDoc = new XmlDocument();
            Stream stream;
            try
            {
                stream = File.OpenRead(System.Web.Hosting.HostingEnvironment.MapPath("~/ClientBin/" + item.Suggestion));                
                xmlDoc.Load(stream);                
            }
            catch (XmlException e)
            {
                Console.WriteLine(e.Message);
            }
            // Now create StringWriter object to get data from xml document.
            StringWriter sw = new StringWriter();
            XmlTextWriter xw = new XmlTextWriter(sw);

            xmlDoc.WriteTo(xw);
            list.Add(sw.ToString());

        }

        return list;        
    }
    private string BuildXMLString()
    {
        StringWriter str = new StringWriter();
        XmlTextWriter xml = new XmlTextWriter(str);

        // start doc and root el.
        xml.WriteStartDocument();
        xml.WriteStartElement("playerScoreList");

        // data element
        xml.WriteStartElement("player");
        xml.WriteElementString("name", "matt");
        xml.WriteElementString("score", "200");
        xml.WriteEndElement();

        // data element
        xml.WriteStartElement("player");
        xml.WriteElementString("name", "jane");
        xml.WriteElementString("score", "150");
        xml.WriteEndElement();

        // end root and document
        xml.WriteEndElement();
        xml.WriteEndDocument();

        return str.ToString();
    }
    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 = "";
    }
    private static void TreverseDirectories(XmlTextWriter writer, DirectoryInfo dir)
    {
        var folders = dir.GetDirectories();
        var files = dir.GetFiles();
        writer.WriteStartElement("folder");
        writer.WriteElementString("name", dir.Name);

        try
        {
            if (files.Count() > 0)
            {
                writer.WriteStartElement("files");
                foreach (var file in files)
                {
                    writer.WriteElementString("name", file.Name);
                }

                writer.WriteEndElement();
            }

            foreach (var child in folders)
            {
                TreverseDirectories(writer, child);
            }

            writer.WriteEndElement();
        }
        catch (Exception)
        {
            Console.WriteLine("Access denied! ");
        }
    }
Example #23
0
 public static string Xml(this XElement e)
 {
     StringBuilder builder = new StringBuilder();
     XmlTextWriter writer = new XmlTextWriter(new StringWriter(builder));
     e.WriteTo(writer);
     return builder.ToString();
 }
Example #24
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();
    }
Example #25
0
    public static int Main(string[] args)
    {
        if (args.Length < 1) {
            Console.Error.WriteLine("Usage: RunMorphoCli tagger_file");
            return 1;
        }

        Console.Error.Write("Loading tagger: ");
        Tagger tagger = Tagger.load(args[0]);
        if (tagger == null) {
            Console.Error.WriteLine("Cannot load tagger from file '{0}'", args[0]);
            return 1;
        }
        Console.Error.WriteLine("done");

        Forms forms = new Forms();
        TaggedLemmas lemmas = new TaggedLemmas();
        TokenRanges tokens = new TokenRanges();
        Tokenizer tokenizer = tagger.newTokenizer();
        if (tokenizer == null) {
            Console.Error.WriteLine("No tokenizer is defined for the supplied model!");
            return 1;
        }

        XmlTextWriter xmlOut = new XmlTextWriter(Console.Out);
        for (bool not_eof = true; not_eof; ) {
            string line;
            StringBuilder textBuilder = new StringBuilder();

            // Read block
            while ((not_eof = (line = Console.In.ReadLine()) != null) && line.Length > 0) {
                textBuilder.Append(line).Append('\n');
            }
            if (not_eof) textBuilder.Append('\n');

            // Tokenize and tag
            string text = textBuilder.ToString();
            tokenizer.setText(text);
            int t = 0;
            while (tokenizer.nextSentence(forms, tokens)) {
                tagger.tag(forms, lemmas);

                for (int i = 0; i < lemmas.Count; i++) {
                    TaggedLemma lemma = lemmas[i];
                    int token_start = (int)tokens[i].start, token_length = (int)tokens[i].length;
                    xmlOut.WriteString(text.Substring(t, token_start - t));
                    if (i == 0) xmlOut.WriteStartElement("sentence");
                    xmlOut.WriteStartElement("token");
                    xmlOut.WriteAttributeString("lemma", lemma.lemma);
                    xmlOut.WriteAttributeString("tag", lemma.tag);
                    xmlOut.WriteString(text.Substring(token_start, token_length));
                    xmlOut.WriteEndElement();
                    if (i + 1 == lemmas.Count) xmlOut.WriteEndElement();
                    t = token_start + token_length;
                }
            }
            xmlOut.WriteString(text.Substring(t));
        }
        return 0;
    }
	private static void WriteBookmarks(
		XmlTextWriter writer, IList<Bookmark> bookmarks)
	{
		writer.WriteStartElement("result-set");
		foreach (var bookmark in bookmarks)
		{
			writer.WriteStartElement("bookmark");
			if (bookmark.User.Username != null)
			{
				writer.WriteElementString("username", bookmark.User.Username);
			}
			if (bookmark.Title != null)
			{
				writer.WriteElementString("title", bookmark.Title);
			}
			if (bookmark.URL != null)
			{
				writer.WriteElementString("url", bookmark.URL);
			}
			if (bookmark.Tags.Count > 0)
			{
				string tags = string.Join(", ",
					bookmark.Tags.Select(t => t.Name).OrderBy(t => t));
				writer.WriteElementString("tags", tags);
			}
			if (bookmark.Notes != null)
			{
				writer.WriteElementString("notes", bookmark.Notes);
			}
			writer.WriteEndElement();
		}
		writer.WriteEndElement();
	}
            public void WriteGestureLog(Dictionary<String, Point3D> gestureDict, string timeStamp)
            {
                using (StringWriter sw = new StringWriter(_sBuilder))
                {
                    using (XmlWriter xmlWriter = new XmlTextWriter(sw))
                    {
                        //START MOVEMENT
                        xmlWriter.WriteStartElement("mov");
                        xmlWriter.WriteStartAttribute("time_stamp");
                        xmlWriter.WriteValue(timeStamp);
                        xmlWriter.WriteEndAttribute();
                        //PRINT ALL JOINTS
                        foreach (var point in gestureDict)
                        {
                            xmlWriter.WriteStartElement(point.Key);//START JOINT
                            xmlWriter.WriteStartElement("x");
                            xmlWriter.WriteValue(point.Value.X);
                            xmlWriter.WriteEndElement();
                            xmlWriter.WriteStartElement("Y");
                            xmlWriter.WriteValue(point.Value.Y);
                            xmlWriter.WriteEndElement();
                            xmlWriter.WriteStartElement("Z");
                            xmlWriter.WriteValue(point.Value.Z);
                            xmlWriter.WriteEndElement();
                            xmlWriter.WriteEndElement();//END JOINT
                        }
                        xmlWriter.WriteEndElement();//END MOV
                    }

                }
                WriteToXMLLogFile();
            }
Example #28
0
 // Here we deserialize it back into its original form
 object DeserializeObject(string pXmlizedString)
 {
     XmlSerializer xs = new XmlSerializer(typeof(UserData));
     MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
     XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
     return xs.Deserialize(memoryStream);
 }
	private static void ProcessSearchQueries(XmlTextWriter writer)
	{
		XmlDocument xmlDoc = new XmlDocument();
		xmlDoc.Load("../../complex-query.xml");
		foreach (XmlNode query in xmlDoc.SelectNodes("/queries/query"))
		{
			string username = query.GetChildText("username");
			int maxResults = 10;
			var maxResultsAttrib = query.Attributes["max-results"];
			if (maxResultsAttrib != null)
			{
				maxResults = int.Parse(maxResultsAttrib.Value);
			}
			List<string> tags = new List<string>();
			foreach (XmlNode tag in query.SelectNodes("tag"))
			{
				tags.Add(tag.InnerText.Trim());
			}

			var bookmarks =
				BookmarksDAL.FindBookmarks(username, tags, maxResults);

			WriteBookmarks(writer, bookmarks);
		}		
	}
    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();
    }
Example #31
0
        /// <summary>
        /// Serialize Chart Properties
        /// </summary>
        /// <param name="tw"></param>

        public void SerializeChartProperties(XmlTextWriter tw)
        {
            if (!ChartPropertiesEnabled)
            {
                return;
            }

            tw.WriteStartElement("ChartProperties");

            tw.WriteAttributeString("ShapeRenderingMode", ShapeRenderingMode.ToString());
            tw.WriteAttributeString("Jitter", JitterX.ToString());
            tw.WriteAttributeString("ChartStretch", JitterTheSameForXandY.ToString());

            tw.WriteAttributeString("ShowLegend", ShowLegend.ToString());
            if (LegendAlignmentHorizontal != ModelView.LegendAlignmentHorizontal)
            {
                tw.WriteAttributeString("LegendAlignmentHorizontal", LegendAlignmentHorizontal.ToString());
            }
            if (LegendAlignmentVertical != ModelView.LegendAlignmentVertical)
            {
                tw.WriteAttributeString("LegendAlignmentVertical", LegendAlignmentVertical.ToString());
            }
            if (LegendMaxHorizontalPercentage != ModelView.LegendMaxHorizontalPercentage)
            {
                tw.WriteAttributeString("LegendMaxHorizontalPercentage", LegendMaxHorizontalPercentage.ToString());
            }
            if (LegendMaxVerticalPercentage != ModelView.LegendMaxVerticalPercentage)
            {
                tw.WriteAttributeString("LegendMaxVerticalPercentage", LegendMaxVerticalPercentage.ToString());
            }
            if (LegendItemOrder != ModelView.LegendItemOrder)
            {
                tw.WriteAttributeString("LegendItemOrder", LegendItemOrder.ToString());
            }

            tw.WriteAttributeString("MainChartAreaMaximized", MainViewPanelMaximized.ToString());
            tw.WriteAttributeString("ShowFilters", ShowFilters.ToString());
            tw.WriteAttributeString("ShowSelectedDataRows", ShowSelectedDataRows.ToString());
            tw.WriteAttributeString("ShowAxesTitles", ShowAxesTitles.ToString());
            tw.WriteAttributeString("ShowAxesScaleLabels", ShowAxesScaleLabels.ToString());
            tw.WriteAttributeString("RotateAxes", RotateAxes.ToString());

            tw.WriteAttributeString("UseExistingCondFormatting", UseExistingCondFormatting.ToString());
            tw.WriteAttributeString("PivotedData", PivotedData.ToString());

            SerializeAxis(XAxisMx, "XAxis", tw);
            SerializeAxis(YAxisMx, "YAxis", tw);
            SerializeAxis(ZAxisMx, "ZAxis", tw);

            for (int ai = 0; ai < AxesMx.Count; ai++)
            {
                SerializeAxis(AxesMx[ai], "Axis" + (ai + 1).ToString(), tw);
            }

            MarkerColor.Serialize("MarkerColor", tw);           // marker color

            MarkerSize.Serialize("MarkerSize", tw);             // marker size

            MarkerShape.Serialize("MarkerShape", tw);           // marker shape

            MarkerLabel.Serialize("MarkerLabel", tw);           // marker labels

            // Tooltip

            MarkerTooltip.Serialize("ToolTipFields", tw);

            // Surface attributes

            tw.WriteStartElement("Surface");
            tw.WriteAttributeString("FillMode", SurfaceFillMode.ToString());
            tw.WriteAttributeString("FrameMode", SurfaceFrameMode.ToString());
            tw.WriteAttributeString("SmoothPalette", SmoothPalette.ToString());
            tw.WriteAttributeString("SmoothShading", SmoothShading.ToString());
            tw.WriteAttributeString("SemiTransparent", SemiTransparent.ToString());
            tw.WriteAttributeString("DrawFlat", DrawFlat.ToString());
            tw.WriteEndElement();

            // Trellis attributes

            tw.WriteStartElement("Trellis");
            tw.WriteAttributeString("ByRowCol", TrellisByRowCol.ToString());
            tw.WriteAttributeString("Manual", TrellisManual.ToString());
            tw.WriteAttributeString("MaxRows", TrellisMaxRows.ToString());
            tw.WriteAttributeString("MaxCols", TrellisMaxCols.ToString());
            SerializeQueryColumnRef(TrellisColQc, "ColumnQc", tw);
            SerializeQueryColumnRef(TrellisRowQc, "RowQc", tw);
            SerializeQueryColumnRef(TrellisPageQc, "PageQc", tw);
            SerializeQueryColumnRef(TrellisFlowQc, "FlowQc", tw);
            tw.WriteEndElement();

            tw.WriteEndElement();             // ChartProperties
            return;
        }
Example #32
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.Pow(4, 2) <= 42))
            {
                {}
            }
            else if (!(Math.Pow(4, 2) <= 42))
            {
                {}
            }
            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();
            }

            //flaw

            string query = string.Format("//user[@name='{0}']", 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( );
        }
Example #33
0
        /// <summary>
        /// Converts a xaml element into an appropriate html element.
        /// </summary>
        /// <param name="xamlReader">
        /// On entry this XmlTextReader must be on Element start tag;
        /// on exit - on EndElement tag.
        /// </param>
        /// <param name="htmlWriter">
        /// May be null, in which case we are skipping xaml content
        /// without producing any html output
        /// </param>
        /// <param name="inlineStyle">
        /// StringBuilder used for collecting css properties for inline STYLE attributes on every level.
        /// </param>
        private static void WriteElement(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
        {
            Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);

            if (htmlWriter == null)
            {
                // Skipping mode; recurse into the xaml element without any output
                WriteElementContent(xamlReader, /*htmlWriter:*/ null, null);
            }
            else
            {
                string htmlElementName = null;

                switch (xamlReader.Name)
                {
                case "Run":
                case "Span":
                    htmlElementName = "SPAN";
                    break;

                case "InlineUIContainer":
                    htmlElementName = "SPAN";
                    break;

                case "Bold":
                    htmlElementName = "B";
                    break;

                case "Italic":
                    htmlElementName = "I";
                    break;

                case "Paragraph":
                    htmlElementName = "P";
                    break;

                case "BlockUIContainer":
                    htmlElementName = "DIV";
                    break;

                case "Section":
                    htmlElementName = "DIV";
                    break;

                case "Table":
                    htmlElementName = "TABLE";
                    break;

                case "TableColumn":
                    htmlElementName = "COL";
                    break;

                case "TableRowGroup":
                    htmlElementName = "TBODY";
                    break;

                case "TableRow":
                    htmlElementName = "TR";
                    break;

                case "TableCell":
                    htmlElementName = "TD";
                    break;

                case "List":
                    string marker = xamlReader.GetAttribute("MarkerStyle");
                    if (marker == null || marker == "None" || marker == "Disc" || marker == "Circle" || marker == "Square" || marker == "Box")
                    {
                        htmlElementName = "UL";
                    }
                    else
                    {
                        htmlElementName = "OL";
                    }
                    break;

                case "ListItem":
                    htmlElementName = "LI";
                    break;

                default:
                    htmlElementName = null;     // Ignore the element
                    break;
                }

                if (htmlWriter != null && htmlElementName != null)
                {
                    htmlWriter.WriteStartElement(htmlElementName);

                    WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle);

                    WriteElementContent(xamlReader, htmlWriter, inlineStyle);

                    htmlWriter.WriteEndElement();
                }
                else
                {
                    // Skip this unrecognized xaml element
                    WriteElementContent(xamlReader, /*htmlWriter:*/ null, null);
                }
            }
        }
Example #34
0
        /// <summary>
        /// Reads a content of current xaml element, converts it
        /// </summary>
        /// <param name="xamlReader">
        /// XmlTextReader which is expected to be at XmlNodeType.Element
        /// (opening element tag) position.
        /// </param>
        /// <param name="htmlWriter">
        /// May be null, in which case we are skipping the xaml element;
        /// witout producing any output to html.
        /// </param>
        /// <param name="inlineStyle">
        /// StringBuilder used for collecting css properties for inline STYLE attribute.
        /// </param>
        private static void WriteElementContent(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
        {
            Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);

            bool elementContentStarted = false;

            if (xamlReader.IsEmptyElement)
            {
                if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0)
                {
                    // Output STYLE attribute and clear inlineStyle buffer.
                    htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
                    inlineStyle.Remove(0, inlineStyle.Length);
                }
                elementContentStarted = true;
            }
            else
            {
                while (ReadNextToken(xamlReader) && xamlReader.NodeType != XmlNodeType.EndElement)
                {
                    switch (xamlReader.NodeType)
                    {
                    case XmlNodeType.Element:
                        if (xamlReader.Name.Contains("."))
                        {
                            AddComplexProperty(xamlReader, inlineStyle);
                        }
                        else
                        {
                            if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0)
                            {
                                // Output STYLE attribute and clear inlineStyle buffer.
                                htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
                                inlineStyle.Remove(0, inlineStyle.Length);
                            }
                            elementContentStarted = true;
                            WriteElement(xamlReader, htmlWriter, inlineStyle);
                        }
                        Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement || xamlReader.NodeType == XmlNodeType.Element && xamlReader.IsEmptyElement);
                        break;

                    case XmlNodeType.Comment:
                        if (htmlWriter != null)
                        {
                            if (!elementContentStarted && inlineStyle.Length > 0)
                            {
                                htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
                            }
                            htmlWriter.WriteComment(xamlReader.Value);
                        }
                        elementContentStarted = true;
                        break;

                    case XmlNodeType.CDATA:
                    case XmlNodeType.Text:
                    case XmlNodeType.SignificantWhitespace:
                        if (htmlWriter != null)
                        {
                            if (!elementContentStarted && inlineStyle.Length > 0)
                            {
                                htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
                            }
                            htmlWriter.WriteString(xamlReader.Value);
                        }
                        elementContentStarted = true;
                        break;
                    }
                }

                Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement);
            }
        }
Example #35
0
        /// <summary>
        /// Reads attributes of the current xaml element and converts
        /// them into appropriate html attributes or css styles.
        /// </summary>
        /// <param name="xamlReader">
        /// XmlTextReader which is expected to be at XmlNodeType.Element
        /// (opening element tag) position.
        /// The reader will remain at the same level after function complete.
        /// </param>
        /// <param name="htmlWriter">
        /// XmlTextWriter for output html, which is expected to be in
        /// after WriteStartElement state.
        /// </param>
        /// <param name="inlineStyle">
        /// String builder for collecting css properties for inline STYLE attribute.
        /// </param>
        private static void WriteFormattingProperties(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
        {
            Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);

            // Clear string builder for the inline style
            inlineStyle.Remove(0, inlineStyle.Length);

            if (!xamlReader.HasAttributes)
            {
                return;
            }

            bool borderSet = false;

            while (xamlReader.MoveToNextAttribute())
            {
                string css = null;

                switch (xamlReader.Name)
                {
                // Character fomatting properties
                // ------------------------------
                case "Background":
                    css = "background-color:" + ParseXamlColor(xamlReader.Value) + ";";
                    break;

                case "FontFamily":
                    css = "font-family:" + xamlReader.Value + ";";
                    break;

                case "FontStyle":
                    css = "font-style:" + xamlReader.Value.ToLower() + ";";
                    break;

                case "FontWeight":
                    css = "font-weight:" + xamlReader.Value.ToLower() + ";";
                    break;

                case "FontStretch":
                    break;

                case "FontSize":
                    css = "font-size:" + xamlReader.Value + ";";
                    break;

                case "Foreground":
                    css = "color:" + ParseXamlColor(xamlReader.Value) + ";";
                    break;

                case "TextDecorations":
                    css = "text-decoration:underline;";
                    break;

                case "TextEffects":
                    break;

                case "Emphasis":
                    break;

                case "StandardLigatures":
                    break;

                case "Variants":
                    break;

                case "Capitals":
                    break;

                case "Fraction":
                    break;

                // Paragraph formatting properties
                // -------------------------------
                case "Padding":
                    css = "padding:" + ParseXamlThickness(xamlReader.Value) + ";";
                    break;

                case "Margin":
                    css = "margin:" + ParseXamlThickness(xamlReader.Value) + ";";
                    break;

                case "BorderThickness":
                    css       = "border-width:" + ParseXamlThickness(xamlReader.Value) + ";";
                    borderSet = true;
                    break;

                case "BorderBrush":
                    css       = "border-color:" + ParseXamlColor(xamlReader.Value) + ";";
                    borderSet = true;
                    break;

                case "LineHeight":
                    break;

                case "TextIndent":
                    css = "text-indent:" + xamlReader.Value + ";";
                    break;

                case "TextAlignment":
                    css = "text-align:" + xamlReader.Value + ";";
                    break;

                case "IsKeptTogether":
                    break;

                case "IsKeptWithNext":
                    break;

                case "ColumnBreakBefore":
                    break;

                case "PageBreakBefore":
                    break;

                case "FlowDirection":
                    break;

                // Table attributes
                // ----------------
                case "Width":
                    css = "width:" + xamlReader.Value + ";";
                    break;

                case "ColumnSpan":
                    htmlWriter.WriteAttributeString("COLSPAN", xamlReader.Value);
                    break;

                case "RowSpan":
                    htmlWriter.WriteAttributeString("ROWSPAN", xamlReader.Value);
                    break;
                }

                if (css != null)
                {
                    inlineStyle.Append(css);
                }
            }

            if (borderSet)
            {
                inlineStyle.Append("border-style:solid;mso-element:para-border-div;");
            }

            // Return the xamlReader back to element level
            xamlReader.MoveToElement();
            Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
        }
        /// <summary>
        /// Create a .oiv package with XML metadata in the archive based on the supplied OIV package info.
        /// </summary>
        /// <param name="relativePath"></param>
        /// <param name="data"></param>
        private void WriteXMLMetadata(OIVPackageInfo data)
        {
            if (version != OIVPackageFormat.OIVFormat_2)
            {
                throw new InvalidDataException("Wrong package format.");
            }

            string filePath = workingDir + "assembly.xml";

            var xmlDoc = new XmlDocument();

            var xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);

            var root = xmlDoc.DocumentElement;

            xmlDoc.InsertBefore(xmlDec, root);

            var packageRoot = xmlDoc.CreateElement(null, "package", null);

            xmlDoc.AppendChild(packageRoot);

            var attribute = xmlDoc.CreateAttribute("version");

            attribute.Value = data.Version.ToString(".0#");

            packageRoot.Attributes.Append(attribute);

            attribute       = xmlDoc.CreateAttribute("id");
            attribute.Value = data.ID.ToUpper();

            packageRoot.Attributes.Append(attribute);

            attribute       = xmlDoc.CreateAttribute("target");
            attribute.Value = data.Target.ToString();

            packageRoot.Attributes.Append(attribute);

            var subNode = xmlDoc.CreateElement("metadata");

            packageRoot.AppendChild(subNode);

            var element = xmlDoc.CreateElement("name");

            element.InnerText = data.Name;

            subNode.AppendChild(element);

            #region version

            element = xmlDoc.CreateElement("version");

            var element1 = xmlDoc.CreateElement("major");
            element1.InnerText = data.MajorVersion.ToString();

            element.AppendChild(element1);

            element1           = xmlDoc.CreateElement("minor");
            element1.InnerText = data.MinorVersion.ToString();

            element.AppendChild(element1);

            if (data.Tag?.Length > 0)
            {
                element1           = xmlDoc.CreateElement("tag");
                element1.InnerText = data.Tag;

                element.AppendChild(element1);
            }

            subNode.AppendChild(element);

            #endregion

            #region author

            element = xmlDoc.CreateElement("author");
            subNode.AppendChild(element);

            element1           = xmlDoc.CreateElement("displayName");
            element1.InnerText = data.DisplayName;

            element.AppendChild(element1);

            if (data.ActionLink?.Length > 0)
            {
                element1           = xmlDoc.CreateElement("actionLink");
                element1.InnerText = data.ActionLink;

                element.AppendChild(element1);
            }

            if (data.Web?.Length > 0)
            {
                element1           = xmlDoc.CreateElement("web");
                element1.InnerText = data.Web;

                element.AppendChild(element1);
            }

            if (data.Facebook?.Length > 0)
            {
                element1           = xmlDoc.CreateElement("facebook");
                element1.InnerText = data.Facebook;

                element.AppendChild(element1);
            }

            if (data.Twitter?.Length > 0)
            {
                element1           = xmlDoc.CreateElement("twitter");
                element1.InnerText = data.Twitter;

                element.AppendChild(element1);
            }

            if (data.Youtube?.Length > 0)
            {
                element1           = xmlDoc.CreateElement("youtube");
                element1.InnerText = data.Youtube;

                element.AppendChild(element1);
            }

            #endregion

            #region description

            element = xmlDoc.CreateElement("description");
            subNode.AppendChild(element);

            if (data.FooterLink?.Length > 0)
            {
                attribute       = xmlDoc.CreateAttribute("footerLink");
                attribute.Value = data.FooterLink;

                element.Attributes.Append(attribute);
            }

            if (data.FooterLinkTitle?.Length > 0)
            {
                attribute       = xmlDoc.CreateAttribute("footerLinkTitle");
                attribute.Value = data.FooterLinkTitle;

                element.Attributes.Append(attribute);
            }

            var cData = xmlDoc.CreateCDataSection(data.Description);

            element.AppendChild(cData);

            #endregion

            #region largeDescription

            if (data.LDDescription?.Length > 0)
            {
                element = xmlDoc.CreateElement("largeDescription");
                subNode.AppendChild(element);

                attribute       = xmlDoc.CreateAttribute("displayName");
                attribute.Value = data.LDDisplayName;

                element.Attributes.Append(attribute);

                attribute       = xmlDoc.CreateAttribute("footerLink");
                attribute.Value = data.LDFooterLink;

                element.Attributes.Append(attribute);

                attribute       = xmlDoc.CreateAttribute("footerLinkTitle");
                attribute.Value = data.LDFooterLinkTitle;

                element.Attributes.Append(attribute);

                cData = xmlDoc.CreateCDataSection(data.LDDescription);

                element.AppendChild(cData);
            }

            #endregion

            #region license

            if (data.License?.Length > 0)
            {
                element = xmlDoc.CreateElement("license");
                subNode.AppendChild(element);

                attribute       = xmlDoc.CreateAttribute("footerLink");
                attribute.Value = data.LFooterLink;

                cData = xmlDoc.CreateCDataSection("value");

                element.AppendChild(cData);
            }

            #endregion

            #region colors

            subNode = xmlDoc.CreateElement("colors");
            packageRoot.AppendChild(subNode);

            element = xmlDoc.CreateElement("headerBackground");
            subNode.AppendChild(element);

            attribute       = xmlDoc.CreateAttribute("useBlackTextColor");
            attribute.Value = data.BlackTextEnabled.ToString();

            element.Attributes.Append(attribute);

            element.InnerText = string.Format("${0}{1}{2}{3}",
                                              data.HeaderBackground.A.ToString("X2"),
                                              data.HeaderBackground.R.ToString("X2"),
                                              data.HeaderBackground.G.ToString("X2"),
                                              data.HeaderBackground.B.ToString("X2"));

            element = xmlDoc.CreateElement("iconBackground");

            element.InnerText = string.Format("${0}{1}{2}{3}",
                                              data.IconBackground.A.ToString("X2"),
                                              data.IconBackground.R.ToString("X2"),
                                              data.IconBackground.G.ToString("X2"),
                                              data.IconBackground.B.ToString("X2"));

            subNode.AppendChild(element);

            #endregion

            subNode = xmlDoc.CreateElement("content");
            packageRoot.AppendChild(subNode);

            if (!ReferenceEquals(data.GenericFiles, null))
            {
                foreach (var file in data.GenericFiles)
                {
                    element = xmlDoc.CreateElement("add");
                    subNode.AppendChild(element);

                    attribute = xmlDoc.CreateAttribute("source");

                    attribute.Value = "file\\" + file.Destination.TrimEnd('\\');

                    element.Attributes.Append(attribute);

                    element.InnerText = file.Destination.TrimEnd('\\');
                }
            }

            if (!ReferenceEquals(data.Archives, null))
            {
                foreach (var arc in data.Archives)
                {
                    element = xmlDoc.CreateElement("archive");
                    subNode.AppendChild(element);

                    attribute       = xmlDoc.CreateAttribute("path");
                    attribute.Value = arc.Path;

                    element.Attributes.Append(attribute);

                    attribute       = xmlDoc.CreateAttribute("createIfNotExist");
                    attribute.Value = arc.CreateIfNotExist.ToString();

                    element.Attributes.Append(attribute);

                    attribute       = xmlDoc.CreateAttribute("type");
                    attribute.Value = arc.Version.ToString();

                    element.Attributes.Append(attribute);

                    foreach (var source in arc.SourceFiles)
                    {
                        element1 = xmlDoc.CreateElement("add");
                        element.AppendChild(element1);

                        attribute = xmlDoc.CreateAttribute("source");

                        attribute.Value = "rpf\\" + arc.Name + "\\" + source.Name.Trim('\\');

                        element1.Attributes.Append(attribute);

                        element1.InnerText = source.Name;
                    }

                    foreach (var n in arc.NestedArchives)
                    {
                        foreach (var innerN in n.GetNodes())
                        {
                            element1 = xmlDoc.CreateElement("archive");
                            element.AppendChild(element1);

                            attribute       = xmlDoc.CreateAttribute("path");
                            attribute.Value = innerN.Path;

                            element1.Attributes.Append(attribute);

                            attribute       = xmlDoc.CreateAttribute("createIfNotExist");
                            attribute.Value = innerN.CreateIfNotExist.ToString();

                            element1.Attributes.Append(attribute);

                            attribute       = xmlDoc.CreateAttribute("type");
                            attribute.Value = innerN.Version.ToString();

                            element1.Attributes.Append(attribute);

                            foreach (var f in innerN.SourceFiles)
                            {
                                var element2 = xmlDoc.CreateElement("add");
                                element1.AppendChild(element2);

                                attribute = xmlDoc.CreateAttribute("source");

                                attribute.Value = "rpf\\" + arc.Name + "\\" + f.Name.Trim('\\');

                                element2.Attributes.Append(attribute);

                                element2.InnerText = f.Name;
                            }
                        }
                    }
                }
            }

            using (XmlTextWriter writer = new XmlTextWriter(filePath, null))
            {
                writer.Formatting = Formatting.Indented;
                xmlDoc.Save(writer);
            }
        }
Example #37
0
        string BuildPackageInternal(IProgressStatus monitor, bool debugSymbols, string targetDirectory, string filePath, PackageFormat format)
        {
            AddinDescription conf = registry.GetAddinDescription(monitor, filePath);

            if (conf == null)
            {
                monitor.ReportError("Could not read add-in file: " + filePath, null);
                return(null);
            }

            string basePath = Path.GetDirectoryName(Path.GetFullPath(filePath));

            if (targetDirectory == null)
            {
                targetDirectory = basePath;
            }

            // Generate the file name

            string name;

            if (conf.LocalId.Length == 0)
            {
                name = Path.GetFileNameWithoutExtension(filePath);
            }
            else
            {
                name = conf.LocalId;
            }
            name = Addin.GetFullId(conf.Namespace, name, conf.Version);
            name = name.Replace(',', '_').Replace(".__", ".");

            string outFilePath = Path.Combine(targetDirectory, name);

            switch (format)
            {
            case PackageFormat.Mpack:
                outFilePath += ".mpack";
                break;

            case PackageFormat.Vsix:
                outFilePath += ".vsix";
                break;

            default:
                throw new NotSupportedException(format.ToString());
            }

            ZipOutputStream s = new ZipOutputStream(File.Create(outFilePath));

            s.SetLevel(5);

            if (format == PackageFormat.Vsix)
            {
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                doc.LoadXml(conf.SaveToVsixXml().OuterXml);
                MemoryStream  ms = new MemoryStream();
                XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
                tw.Formatting = Formatting.Indented;
                doc.WriteTo(tw);
                tw.Flush();
                byte [] data = ms.ToArray();

                var infoEntry = new ZipEntry("extension.vsixmanifest")
                {
                    Size = data.Length
                };
                s.PutNextEntry(infoEntry);
                s.Write(data, 0, data.Length);
                s.CloseEntry();
            }

            // Generate a stripped down description of the add-in in a file, since the complete
            // description may be declared as assembly attributes

            if (format == PackageFormat.Mpack || format == PackageFormat.Vsix)
            {
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                doc.LoadXml(conf.SaveToXml().OuterXml);
                CleanDescription(doc.DocumentElement);
                MemoryStream  ms = new MemoryStream();
                XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
                tw.Formatting = Formatting.Indented;
                doc.WriteTo(tw);
                tw.Flush();
                byte [] data = ms.ToArray();

                var infoEntry = new ZipEntry("addin.info")
                {
                    Size = data.Length
                };
                s.PutNextEntry(infoEntry);
                s.Write(data, 0, data.Length);
                s.CloseEntry();
            }

            // Now add the add-in files

            var files = new HashSet <string> ();

            files.Add(Path.GetFileName(Util.NormalizePath(filePath)));

            foreach (string f in conf.AllFiles)
            {
                var file = Util.NormalizePath(f);
                files.Add(file);
                if (debugSymbols)
                {
                    if (File.Exists(Path.ChangeExtension(file, ".pdb")))
                    {
                        files.Add(Path.ChangeExtension(file, ".pdb"));
                    }
                    else if (File.Exists(file + ".mdb"))
                    {
                        files.Add(file + ".mdb");
                    }
                }
            }

            foreach (var prop in conf.Properties)
            {
                try {
                    var file = Util.NormalizePath(prop.Value);
                    if (File.Exists(Path.Combine(basePath, file)))
                    {
                        files.Add(file);
                    }
                } catch {
                    // Ignore errors
                }
            }

            //add satellite assemblies for assemblies in the list
            var satelliteFinder = new SatelliteAssemblyFinder();

            foreach (var f in files.ToList())
            {
                foreach (var satellite in satelliteFinder.FindSatellites(Path.Combine(basePath, f)))
                {
                    var relativeSatellite = satellite.Substring(basePath.Length + 1);
                    files.Add(relativeSatellite);
                }
            }

            monitor.Log("Creating package " + Path.GetFileName(outFilePath));

            foreach (string file in files)
            {
                string fp = Path.Combine(basePath, file);
                using (FileStream fs = File.OpenRead(fp)) {
                    byte[] buffer = new byte [fs.Length];
                    fs.Read(buffer, 0, buffer.Length);

                    var fileName = Path.DirectorySeparatorChar == '\\' ? file.Replace('\\', '/') : file;
                    var entry    = new ZipEntry(fileName)
                    {
                        Size = fs.Length
                    };
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                    s.CloseEntry();
                }
            }

            if (format == PackageFormat.Vsix)
            {
                files.Add("addin.info");
                files.Add("extension.vsixmanifest");
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                XmlElement     root           = doc.DocumentElement;
                doc.InsertBefore(xmlDeclaration, root);
                HashSet <string> alreadyAddedExtensions = new HashSet <string> ();
                var typesEl = doc.CreateElement("Types");
                typesEl.SetAttribute("xmlns", "http://schemas.openxmlformats.org/package/2006/content-types");
                foreach (var file in files)
                {
                    var extension = Path.GetExtension(file);
                    if (string.IsNullOrEmpty(extension))
                    {
                        continue;
                    }
                    if (extension.StartsWith(".", StringComparison.Ordinal))
                    {
                        extension = extension.Substring(1);
                    }
                    if (alreadyAddedExtensions.Contains(extension))
                    {
                        continue;
                    }
                    alreadyAddedExtensions.Add(extension);
                    var typeEl = doc.CreateElement("Default");
                    typeEl.SetAttribute("Extension", extension);
                    typeEl.SetAttribute("ContentType", GetContentType(extension));
                    typesEl.AppendChild(typeEl);
                }
                doc.AppendChild(typesEl);
                MemoryStream  ms = new MemoryStream();
                XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
                tw.Formatting = Formatting.Indented;
                doc.WriteTo(tw);
                tw.Flush();
                byte [] data = ms.ToArray();

                var infoEntry = new ZipEntry("[Content_Types].xml")
                {
                    Size = data.Length
                };
                s.PutNextEntry(infoEntry);
                s.Write(data, 0, data.Length);
                s.CloseEntry();
            }

            s.Finish();
            s.Close();
            return(outFilePath);
        }
Example #38
0
 protected virtual void OnWrite(XmlTextWriter xml)
 {
 }
Example #39
0
 public void g_four_2Generate(NuGenEQML control1, string number)
 {
     this.xmlDocument.Load("GapfillingXML/g_four_2.xml");
     foreach (XmlNode node in this.xmlDocument.FirstChild.ChildNodes)
     {
         int num   = 0;
         int num2  = 0;
         int num3  = 0;
         int num4  = 0;
         int num5  = 0;
         int num6  = 0;
         int num7  = 0;
         int num8  = 0;
         int num9  = 0;
         int num10 = 0;
         int num11 = 0;
         int num12 = 0;
         int num13 = 0;
         int num14 = 0;
         int num15 = 0;
         if (StudentModel.isReGeneration)
         {
             num   = 1;
             num2  = this.numberTools.myRandom(5);
             num3  = this.numberTools.myRandom(5);
             num4  = this.numberTools.myRandom(5);
             num5  = 6;
             num6  = this.numberTools.myRandom(5);
             num7  = this.numberTools.myRandom(5);
             num8  = this.numberTools.myRandom(5);
             num9  = this.numberTools.myRandom(3);
             num10 = this.numberTools.myRandom(3);
             num11 = this.random.Next(0, 2);
             num12 = (num9 * num) + (num10 * num5);
             num13 = (num9 * num2) + (num10 * num6);
             num14 = ((num9 * num3) + (num10 * num7)) + num11;
             num15 = ((num9 * num4) + (num10 * num8)) + num11;
             string        str    = SupportTools.getGuid();
             string        path   = "temp/generate/g_four_2.xml";
             FileStream    w      = new FileStream(path, FileMode.Create);
             XmlTextWriter writer = new XmlTextWriter(w, Encoding.UTF8)
             {
                 Formatting = Formatting.Indented
             };
             writer.WriteStartDocument();
             writer.WriteStartElement("Info");
             writer.WriteAttributeString("save", "false");
             writer.WriteAttributeString("guid", str);
             writer.WriteStartElement("Params");
             writer.WriteElementString("a11", num.ToString());
             writer.WriteElementString("a12", num2.ToString());
             writer.WriteElementString("a13", num3.ToString());
             writer.WriteElementString("a14", num4.ToString());
             writer.WriteElementString("a21", num5.ToString());
             writer.WriteElementString("a22", num6.ToString());
             writer.WriteElementString("a23", num7.ToString());
             writer.WriteElementString("a24", num8.ToString());
             writer.WriteElementString("a31", num12.ToString());
             writer.WriteElementString("a32", num13.ToString());
             writer.WriteElementString("a33", num14.ToString());
             writer.WriteElementString("a34", num15.ToString());
             writer.WriteEndElement();
             writer.WriteStartElement("Answer");
             writer.WriteElementString("d", num11.ToString());
             writer.WriteEndElement();
             writer.WriteEndElement();
             writer.WriteEndDocument();
             writer.Flush();
             writer.Close();
         }
         else
         {
             XmlDocument xmldoc = new XmlDocument();
             xmldoc.Load("temp/generate/g_four_2.xml");
             XmlNode node2 = SupportTools.ParamsXmlNode(xmldoc);
             foreach (XmlNode node3 in node2.ChildNodes)
             {
                 if (node3.Name.Equals("a11"))
                 {
                     num = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("a12"))
                 {
                     num2 = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("a13"))
                 {
                     num3 = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("a14"))
                 {
                     num4 = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("a21"))
                 {
                     num5 = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("a22"))
                 {
                     num6 = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("a23"))
                 {
                     num7 = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("a24"))
                 {
                     num8 = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("a31"))
                 {
                     num12 = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("a32"))
                 {
                     num13 = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("a33"))
                 {
                     num14 = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("a34"))
                 {
                     num15 = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("k1"))
                 {
                     num9 = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("k2"))
                 {
                     num10 = int.Parse(node3.InnerText);
                 }
                 else if (node3.Name.Equals("d"))
                 {
                     num11 = int.Parse(node3.InnerText);
                 }
             }
         }
         string sXML = node.InnerText.Replace("#x#", number).Replace("#a#", num.ToString()).Replace("#b#", num2.ToString()).Replace("#c#", num3.ToString()).Replace("#d#", num4.ToString()).Replace("#e#", num5.ToString()).Replace("#f#", num6.ToString()).Replace("#g#", num7.ToString()).Replace("#h#", num8.ToString()).Replace("#i#", num12.ToString()).Replace("#j#", num13.ToString()).Replace("#k#", num14.ToString()).Replace("#l#", num15.ToString());
         control1.Size    = new Size(550, 110);
         control1.Enabled = false;
         control1.pub_LoadXML(sXML);
         control1.Anchor = AnchorStyles.None;
     }
 }
Example #40
0
        /// <summary>
        /// Creates an xml document that HHRECO can use to learn
        /// </summary>
        /// <param name="filename"></param>
        public void writeXML(string filename)
        {
            //Create filename for the XML document
            XmlTextWriter xmlDocument = new XmlTextWriter(filename, System.Text.Encoding.ASCII);            //, System.Text.Encoding.UTF8);

            //Use indentation
            xmlDocument.Formatting = System.Xml.Formatting.Indented;

            //Create the XML document
            xmlDocument.WriteStartDocument();

            //<MSTrainingModel>
            xmlDocument.WriteStartElement("MSTrainingModel");

            Sketch.Shape[] shapes = this.sketch.Shapes;
            string[]       labels = this.sketch.LabelStrings;


            //Loop through the labels
            for (int i = 0; i < labels.Length; ++i)
            {
                //<type name="label">
                xmlDocument.WriteStartElement("type");
                xmlDocument.WriteAttributeString("name", labels[i]);

                //Loop through the shapes
                for (int j = 0; j < shapes.Length; ++j)
                {
                    //If we are not at the correct label....                                       We cannot handle nested shapes right now...
                    if (!((string)shapes[j].XmlAttrs.Name).ToLower().Equals(labels[i].ToLower()) || shapes[j].Shapes.Length > 0)
                    {
                        continue;
                    }

                    //<example label="+" numStrokes="#">
                    xmlDocument.WriteStartElement("example");
                    xmlDocument.WriteAttributeString("label", "+");
                    xmlDocument.WriteAttributeString("numStrokes", shapes[j].Substrokes.Length.ToString());

                    //Loop through the substrokes
                    for (int k = 0; k < shapes[j].Substrokes.Length; ++k)
                    {
                        string xytime = "";
                        //Loop through the points
                        for (int L = 0; L < shapes[j].Substrokes[k].Points.Length; ++L)
                        {
                            xytime += shapes[j].Substrokes[k].Points[L].X + " " +
                                      shapes[j].Substrokes[k].Points[L].Y + " " +
                                      shapes[j].Substrokes[k].Points[L].Time + " ";
                        }
                        xytime = xytime.Trim();

                        //<stroke points="x y time x y time ... " />
                        xmlDocument.WriteStartElement("stroke");
                        xmlDocument.WriteAttributeString("points", xytime);
                        xmlDocument.WriteEndElement();
                    }

                    //</example>
                    xmlDocument.WriteEndElement();
                }

                //</type>
                xmlDocument.WriteEndElement();
            }

            //</MSTrainingModel>
            xmlDocument.WriteEndElement();

            xmlDocument.WriteEndDocument();
            xmlDocument.Close();
        }
        /// <summary>
        /// Writes an entry to the log
        /// </summary>
        /// <param name="entry"></param>
        /// <returns></returns>
        public bool WriteEntry(WebLogEntry entry)
        {
            lock (_writeLock)
            {
                if (entry.Id == 0)
                {
                    entry.Id = entry.GetHashCode();
                }


                string     logFilename = ConnectionString;
                bool       writeEndDoc = true;
                FileStream fileStream  = null;
                try
                {
                    fileStream = new FileStream(logFilename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
                    fileStream.Seek(0, SeekOrigin.End);

                    // *** If the file's not empty start writing over the end doc tag
                    // *** We'll rewrite it at the end
                    if (fileStream.Position > 0)
                    {
                        fileStream.Seek(-1 * "</ApplicationLog>\r\n".Length, SeekOrigin.End);
                    }
                }
                catch
                {
                    return(false);
                }

                XmlTextWriter writer = new XmlTextWriter((Stream)fileStream, Encoding.UTF8);
                writer.Formatting  = Formatting.Indented;
                writer.IndentChar  = ' ';
                writer.Indentation = 4;

                // *** If the file is empty write the root element
                if (fileStream.Position == 0)
                {
                    writer.WriteStartElement("ApplicationLog");
                    writeEndDoc = false; // it'll automatically unwind the StartElement
                }

                writer.WriteStartElement("LogEntry");
                writer.WriteElementString("Id", entry.Id.ToString());

                writer.WriteStartElement("Entered");
                writer.WriteValue(entry.Entered);
                writer.WriteEndElement();

                writer.WriteElementString("Message", entry.Message);
                writer.WriteElementString("ErrorLevel", entry.ErrorLevel.ToString());
                writer.WriteElementString("Details", entry.Details);

                writer.WriteElementString("Url", entry.Url);
                writer.WriteElementString("QueryString", entry.QueryString);
                writer.WriteElementString("UserAgent", entry.UserAgent);
                writer.WriteElementString("Referrer", entry.Referrer);
                writer.WriteElementString("PostData", entry.PostData);
                writer.WriteElementString("IpAddress", entry.IpAddress);
                writer.WriteElementString("RequestDuration", entry.RequestDuration.ToString());

                writer.WriteEndElement(); // error


                if (writeEndDoc)
                {
                    writer.WriteRaw("\r\n</ApplicationLog>\r\n");
                }
                else
                {
                    writer.WriteEndElement();
                    writer.WriteRaw("\r\n");
                }

                writer.Close();
                fileStream.Close();

                return(true);
            }
        }
Example #42
0
        private void Patch(XmlReader sourceReader, Stream outputStream, XmlDocument diffDoc)
        {
            bool     bFragments = diffDoc.DocumentElement.GetAttribute("fragments") == "yes";
            Encoding enc        = null;

            if (bFragments)
            {
                // load fragment
                XmlDocument         tmpDoc = new XmlDocument();
                XmlDocumentFragment frag   = tmpDoc.CreateDocumentFragment();

                XmlNode node;
                while ((node = tmpDoc.ReadNode(sourceReader)) != null)
                {
                    switch (node.NodeType)
                    {
                    case XmlNodeType.Whitespace:
                        break;

                    case XmlNodeType.XmlDeclaration:
                        frag.InnerXml = node.OuterXml;
                        break;

                    default:
                        frag.AppendChild(node);
                        break;
                    }

                    if (enc == null)
                    {
                        if (sourceReader is XmlTextReader)
                        {
                            enc = ((XmlTextReader)sourceReader).Encoding;
                        }
                        else
                        {
                            enc = Encoding.Unicode;
                        }
                    }
                }

                // patch
                XmlNode sourceNode = frag;
                Patch(ref sourceNode, diffDoc);
                Debug.Assert(sourceNode == frag);

                // save
                if (frag.FirstChild != null && frag.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
                {
                    enc = Encoding.GetEncoding(((XmlDeclaration)sourceNode.FirstChild).Encoding);
                }
                XmlTextWriter tw = new XmlTextWriter(outputStream, enc);
                frag.WriteTo(tw);
                tw.Flush();
            }
            else
            {
                // load document
                XmlDocument sourceDoc = new XmlDocument();
                sourceDoc.XmlResolver = null;
                sourceDoc.Load(sourceReader);

                // patch
                XmlNode sourceNode = sourceDoc;
                Patch(ref sourceNode, diffDoc);
                Debug.Assert(sourceNode == sourceDoc);

                // save
                sourceDoc.Save(outputStream);
            }
        }
Example #43
0
 /// <summary>
 /// Parses the parameter information.
 /// </summary>
 /// <param name="fileContents">The file contents.</param>
 /// <param name="objXmlTextWriter">The obj XML text writer.</param>
 private static void ParseParameterInformation(string fileContents, XmlTextWriter objXmlTextWriter)
 {
    ParseParameterInformation(fileContents, objXmlTextWriter, string.Empty);
 }
Example #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;

            if ((4 + 2 >= 42))
            {
                {}
            }
            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();
            }

            //flaw

            string query = string.Format("//user[@name='{0}']", 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( );
        }
        public bool WriteXMLFile(string filename)
        {
            CultureInfo current = Thread.CurrentThread.CurrentCulture;

            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

            XmlDocument    doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");

            doc.AppendChild(dec);

            XmlElement el = doc.CreateElement("ifc:ifcXML", mXmlNamespace);

            doc.AppendChild(el);
            XmlAttribute schemaLocation = doc.CreateAttribute("xsi", "schemaLocation", mXsiNamespace);

            schemaLocation.Value = mXmlSchema;
            el.SetAttributeNode(schemaLocation);

            XmlAttribute ns = doc.CreateAttribute("xlmns", "ifc", mXmlNamespace);

            ns.Value = mXmlNamespace;
            el.SetAttribute("xlmns", mXmlNamespace);

            Dictionary <int, XmlElement> processed = new Dictionary <int, XmlElement>();
            IfcContext context = Context;

            if (context != null)
            {
                el.AppendChild(Context.GetXML(doc, "", null, processed));
            }

            if (context == null || (context.mIsDecomposedBy.Count == 0 && context.Declares.Count == 0))
            {
                foreach (BaseClassIfc e in this)
                {
                    if (!processed.ContainsKey(e.Index))
                    {
                        el.AppendChild(e.GetXML(doc, "", null, processed));
                    }
                }
            }

            XmlTextWriter writer;

            try
            {
                writer            = new XmlTextWriter(filename, Encoding.UTF8);
                writer.Formatting = Formatting.Indented;
                try
                {
                    doc.WriteTo(writer);
                }
                finally
                {
                    writer.Flush();
                    writer.Close();
                }
            }
            catch (Exception) { }
            Thread.CurrentThread.CurrentUICulture = current;
            return(true);
        }
Example #46
0
        public XMLWrite(string pathToFile, SystemData systemData, ColumnMaterial columnMaterial, GeoTextile geoTextile, List <SoilMaterial> soilLayer)
        {
            int i = 0;

            PathToFile = pathToFile;
            XmlTextWriter xw = new XmlTextWriter(pathToFile, new UnicodeEncoding());

            xw.WriteStartDocument();

            xw.WriteStartElement("projectFile");

            xw.WriteStartElement("SystemData");
            xw.WriteAttributeString("projectName", Convert.ToString(systemData.Project));
            xw.WriteAttributeString("columnGrid", Convert.ToString(systemData.ColumGrid));
            xw.WriteAttributeString("method", Convert.ToString(systemData.Method));
            xw.WriteAttributeString("areaRatio", Convert.ToString(systemData.AreaRatio));
            xw.WriteAttributeString("columnRadius", Convert.ToString(systemData.ColumnRadius));
            xw.WriteAttributeString("widening", Convert.ToString(systemData.Rgeo));
            xw.WriteAttributeString("elongationStiffness", Convert.ToString(systemData.J));
            xw.WriteAttributeString("load", Convert.ToString(systemData.TotalLoad));
            xw.WriteAttributeString("athmosphericPressure", Convert.ToString(systemData.Pref));
            xw.WriteAttributeString("ohde", Convert.ToString(systemData.M));
            xw.WriteAttributeString("poisson", Convert.ToString(systemData.Poisson));
            xw.WriteAttributeString("columnDistance", Convert.ToString(systemData.S));
            xw.WriteEndElement();

            xw.WriteStartElement("ColumnMaterial");
            xw.WriteAttributeString("effectivShearStrength", Convert.ToString(columnMaterial.Phis));
            xw.WriteAttributeString("specificWeight", Convert.ToString(columnMaterial.Gammas));
            xw.WriteEndElement();

            xw.WriteStartElement("Geotextile");
            xw.WriteAttributeString("shortStrength", Convert.ToString(geoTextile.Rbk0));
            xw.WriteAttributeString("a1", Convert.ToString(geoTextile.A1));
            xw.WriteAttributeString("a2", Convert.ToString(geoTextile.A2));
            xw.WriteAttributeString("a3", Convert.ToString(geoTextile.A3));
            xw.WriteAttributeString("a4", Convert.ToString(geoTextile.A4));
            xw.WriteAttributeString("a5", Convert.ToString(geoTextile.A5));
            xw.WriteAttributeString("safetyFactor", Convert.ToString(geoTextile.GammaM));
            xw.WriteEndElement();

            foreach (SoilMaterial layer in soilLayer)
            {
                xw.WriteStartElement("soilLayer_" + i);
                xw.WriteAttributeString("layerThickness", Convert.ToString(layer.LayerThickness));
                xw.WriteAttributeString("referenceModul", Convert.ToString(layer.ReferenceEModul));
                xw.WriteAttributeString("effectiveCohesion", Convert.ToString(layer.EffectiveCohesion));
                xw.WriteAttributeString("effectiveShearStrength", Convert.ToString(layer.EffectiveShearStrengthLayer));
                xw.WriteAttributeString("specificWeight", Convert.ToString(layer.SpecificWeightLayer));
                xw.WriteEndElement();
                i++;
            }

            xw.WriteStartElement("Time_stamp");
            xw.WriteAttributeString("Saved_file_on", Convert.ToString(DateTime.Now));
            xw.WriteEndElement();

            xw.WriteEndElement();



            xw.Close();
        }
        public IActionResult AddTOSiteMap(string boardName)
        {
            bool result = false;

            try
            {
                string      appendNode = "<url><loc>https://boards.socioboard.com/" + boardName + "</loc><lastmod>" + DateTime.UtcNow.ToString("yyyy-MM-dd") + "</lastmod><changefreq>Hourly</changefreq><priority>0.6</priority></url>";
                XmlDocument doc        = new XmlDocument();
                doc.Load(_appSettings.sitemapPath);
                var abc = doc.DocumentElement.GetElementsByTagName("url");
                if (abc.Count >= 500)
                {
                    DirectoryInfo d     = new DirectoryInfo(_appSettings.sitefilePath);//Assuming Test is your Folder
                    FileInfo[]    Files = d.GetFiles("*.xml");

                    if (Files.Count() > 0)
                    {
                        XmlTextWriter writer = new XmlTextWriter(_appSettings.sitemapPath.Replace("sitemap", "sitemap" + Files.Count().ToString()), System.Text.Encoding.UTF8);
                        writer.Close();
                        XmlTextWriter writer1 = new XmlTextWriter(_appSettings.sitemapPath, System.Text.Encoding.UTF8);
                        writer1.WriteStartDocument();
                        writer1.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
                        writer1.WriteStartElement("url");
                        writer1.WriteElementString("loc", "https://boards.socioboard.com/" + boardName);
                        writer1.WriteElementString("priority", "0.6");
                        writer1.WriteElementString("changefreq", "Hourly");
                        writer1.WriteElementString("lastmod", DateTime.UtcNow.ToString("yyyy-MM-dd"));
                        writer1.WriteEndElement();
                        writer1.WriteEndDocument();
                        writer1.Close();
                        doc.Save(_appSettings.sitemapPath.Replace("sitemap", "sitemap" + Files.Count().ToString()));

                        int    length1    = d.GetFiles("*.xml").Length;
                        int    filelength = length1 - 1;
                        string location   = "https://boards.socioboard.com/contents/socioboard/boardSitemap/sitemap" + filelength + ".xml";
                        string lastmode   = DateTime.UtcNow.ToString("yyyy-MM-dd");
                        string priority   = "0.6";

                        XmlDocument xdoc1 = new XmlDocument();
                        xdoc1.Load(_appSettings.sitemapPathIndex);
                        XmlNode url = xdoc1.CreateElement("Url");
                        XmlNode loc = xdoc1.CreateElement("loc");
                        url.InnerText = location;
                        url.AppendChild(loc);

                        XmlNode lastmod = xdoc1.CreateElement("lastmod");
                        lastmod.InnerText = lastmode;
                        url.AppendChild(lastmod);

                        XmlNode prioritys = xdoc1.CreateElement("priority");
                        prioritys.InnerText = priority;
                        url.AppendChild(prioritys);

                        xdoc1.DocumentElement.AppendChild(url);
                        xdoc1.Save(_appSettings.sitemapPathIndex);


                        //XmlDocument docIndex = new XmlDocument();
                        //docIndex.Load(_appSettings.sitemapPathIndex);
                        //docIndex.LoadXml(appendNodeIndex);
                        //XmlNode newNodeIndex = docIndex.DocumentElement;
                        //var attributename = newNodeIndex.Attributes;
                        //docIndex.DocumentElement.AppendChild(docIndex.ImportNode(newNodeIndex, true));
                        //docIndex.Save(_appSettings.sitemapPathIndex);
                    }
                    else
                    {
                        XmlTextWriter writer = new XmlTextWriter(_appSettings.sitemapPath, System.Text.Encoding.UTF8);
                        writer.WriteStartDocument();
                        writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
                        int i = 0;
                        writer.WriteStartElement("url");
                        writer.WriteElementString("loc", "https://boards.socioboard.com/" + boardName);
                        writer.WriteElementString("priority", "0.6");
                        writer.WriteElementString("changefreq", "Hourly");
                        writer.WriteElementString("lastmod", DateTime.UtcNow.ToString("yyyy-MM-dd"));
                        writer.WriteEndElement();
                        writer.WriteEndDocument();
                        writer.Close();
                    }

                    result = true;
                }
                else
                {
                    XmlDocument doc1 = new XmlDocument();
                    doc1.LoadXml(appendNode);
                    XmlNode newNode       = doc1.DocumentElement;
                    var     attributename = newNode.Attributes;
                    doc.DocumentElement.AppendChild(doc.ImportNode(newNode, true));
                    doc.Save(_appSettings.sitemapPath);
                    XDocument doss = XDocument.Load(_appSettings.sitemapPath);
                    foreach (var node in doss.Root.Descendants())
                    {
                        // If we have an empty namespace...
                        if (node.Name.NamespaceName == "")
                        {
                            node.Attributes("xmlns").Remove();
                            // Inherit the parent namespace instead
                            node.Name = node.Parent.Name.Namespace + node.Name.LocalName;
                        }
                    }
                    doss.Save(_appSettings.sitemapPath);

                    result = true;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("issue while creating sitemap" + ex.Message);
                result = false;
            }
            return(Ok(result));
        }
Example #48
0
        /// <summary>
        /// Creates a photo package and a snapshot package.
        /// </summary>
        private static void CreateArchive(string photoPath, string outputPath)
        {
            DirectoryInfo photoDir  = new DirectoryInfo(photoPath);
            DirectoryInfo serverDir = photoDir.Parent;

            // Suppose the path of photo directory is in this format:
            // ...\Server1\Photos
            // Then the name of photo package is: Photos.package.zip
            // The name of snapshot package is:   Server1-Snapshot.package.zip
            string photoPackagePath =
                serverDir.FullName + "\\" + photoDir.Name
                + SharedLibrary.PackageExt;

            string archiveSnapshotPath =
                outputPath + "\\" + serverDir.Name + "-" + _archiveSnapshotName;

            Package photoPackage =
                Package.Open(photoPackagePath, FileMode.Create);

            Package snapshotPackage =
                Package.Open(archiveSnapshotPath, FileMode.Create);

            // The snapshot package has an Info.xml part, which contains the
            // information of photos and thumbnails.
            Uri infoXmlUri =
                PackUriHelper.CreatePartUri(
                    new Uri(SharedLibrary.InfoXmlName, UriKind.Relative));

            PackagePart InfoXmlPart =
                snapshotPackage.CreatePart(infoXmlUri,
                                           SharedLibrary.InfoContentType,
                                           CompressionOption.Normal);

            // Creates a relationship for the snapshot package, which points
            // to the Info.xml part.
            snapshotPackage.CreateRelationship(infoXmlUri, TargetMode.Internal,
                                               SharedLibrary.InfoRelationshipType);

            using (XmlTextWriter infoXmlWriter =
                       new XmlTextWriter(InfoXmlPart.GetStream(), Encoding.UTF8))
            {
                infoXmlWriter.WriteStartDocument();

                Uri packUri = new Uri(photoPackagePath);
                infoXmlWriter.WriteStartElement("PackInfo", SharedLibrary.Namespace);

                // Writes the pack Uri of the photo package to the SourcePackUri
                // attribute.
                infoXmlWriter.WriteAttributeString("SourcePackUri",
                                                   packUri.ToString());
                infoXmlWriter.WriteStartElement("Photos");

                // A counter that is used to give each thumbnail a unique ID
                // and name. Start the counter from 0.
                _currentId = 0;

                // Photos are stored in subfolders based on categories.
                // For example, photos of dogs are stored in Photos\Dogs\
                foreach (DirectoryInfo subFolder in photoDir.GetDirectories())
                {
                    ArchiveSubFolderPhotos(photoPackage, snapshotPackage,
                                           infoXmlWriter, subFolder);
                }

                infoXmlWriter.WriteEndDocument();
            }   //end:using(infoXmlWriter) - Close and dispose infoXmlWriter.

            photoPackage.Close();
            snapshotPackage.Close();

            Console.WriteLine("Successfully created archive package for photo folder on Photo Archive Server.");
            Console.WriteLine("Successfully sent snapshot package to Retail Server.");
            Console.WriteLine("------------------------------------------------------------------------------");
            Console.WriteLine("<Photo Folder>:\n\t" + photoPath);
            Console.WriteLine("<Archive package>:\n\t" + photoPackagePath);
            Console.WriteLine("<Snapshot Package>:\n\t" + archiveSnapshotPath);
            Console.WriteLine("------------------------------------------------------------------------------");
        }
Example #49
0
 internal void WriteEmbeddedXml(XmlTextWriter xmlWriter)
 {
     WriteXml(xmlWriter, true);
 }
Example #50
0
 public XmlISerializedObjectWriter(XmlTextWriter writer)
 {
     _writer = writer;
     WriteStartObject("root");
 }
Example #51
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Demonstrate
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    var request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Relationships,
                        RetrieveAsIfPublished = true
                    };

                    // Retrieve the MetaData.
                    var response = (RetrieveAllEntitiesResponse)service.Execute(request);


                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("RelationshipInfo.xml");
                    using (var sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        var metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            //if (currentEntity.IsIntersect.Value == false)
                            if (true)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);

                                // Start OneToManyRelationships Node
                                metadataWriter.WriteStartElement("OneToManyRelationships");

                                foreach (OneToManyRelationshipMetadata currentRelationship in currentEntity.OneToManyRelationships)
                                {
                                    // Start  Node
                                    metadataWriter.WriteStartElement("Relationship");

                                    metadataWriter.WriteElementString("OtoM_SchemaName", currentRelationship.SchemaName);
                                    metadataWriter.WriteElementString("OtoM_ReferencingEntity", currentRelationship.ReferencingEntity);
                                    metadataWriter.WriteElementString("OtoM_ReferencedEntity", currentRelationship.ReferencedEntity);
                                    // End  Node
                                    metadataWriter.WriteEndElement();
                                }

                                // End OneToManyRelationships Node
                                metadataWriter.WriteEndElement();

                                // Start ManyToManyRelationships Node
                                metadataWriter.WriteStartElement("ManyToManyRelationships");


                                foreach (ManyToManyRelationshipMetadata currentRelationship in currentEntity.ManyToManyRelationships)
                                {
                                    // Start  Node
                                    metadataWriter.WriteStartElement("Relationship");

                                    metadataWriter.WriteElementString("MtoM_SchemaName", currentRelationship.SchemaName);
                                    metadataWriter.WriteElementString("MtoM_Entity1", currentRelationship.Entity1LogicalName);
                                    metadataWriter.WriteElementString("MtoM_Entity2", currentRelationship.Entity2LogicalName);
                                    metadataWriter.WriteElementString("IntersectEntity", currentRelationship.IntersectEntityName);
                                    // End  Node
                                    metadataWriter.WriteEndElement();
                                }

                                // End ManyToManyRelationships Node
                                metadataWriter.WriteEndElement();

                                // Start ManyToOneRelationships Node
                                metadataWriter.WriteStartElement("ManyToOneRelationships");


                                foreach (OneToManyRelationshipMetadata currentRelationship in currentEntity.ManyToOneRelationships)
                                {
                                    // Start  Node
                                    metadataWriter.WriteStartElement("Relationship");

                                    metadataWriter.WriteElementString("MtoO_SchemaName", currentRelationship.SchemaName);
                                    metadataWriter.WriteElementString("MtoO_ReferencingEntity", currentRelationship.ReferencingEntity);
                                    metadataWriter.WriteElementString("MtoO_ReferencedEntity", currentRelationship.ReferencedEntity);
                                    // End  Node
                                    metadataWriter.WriteEndElement();
                                }

                                // End ManyToOneRelationships Node
                                metadataWriter.WriteEndElement();

                                // End Relationships Node
                                // metadataWriter.WriteEndElement();



                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }



                    Console.WriteLine("Done.");

                    #endregion Demonstrate
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Example #52
0
        public Stream Save(Stream stream)
        {
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);

            writer.Formatting = Formatting.Indented;

            writer.WriteStartDocument();

            #region Header
            writer.WriteStartElement("rsm:CrossIndustryDocument");
            writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
            writer.WriteAttributeString("xmlns", "rsm", null, "urn:ferd:CrossIndustryDocument:invoice:1p0");
            writer.WriteAttributeString("xmlns", "ram", null, "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:12");
            writer.WriteAttributeString("xmlns", "udt", null, "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15");
            #endregion

            #region SpecifiedExchangedDocumentContext
            writer.WriteStartElement("rsm:SpecifiedExchangedDocumentContext");
            writer.WriteStartElement("ram:TestIndicator");
            writer.WriteElementString("udt:Indicator", "true");
            writer.WriteEndElement();
            writer.WriteStartElement("ram:GuidelineSpecifiedDocumentContextParameter");
            writer.WriteElementString("ram:ID", "urn:ferd:CrossIndustryDocument:invoice:1p0:" + Profile.ToString().ToLower());
            writer.WriteEndElement();
            writer.WriteEndElement();

            #endregion

            WriteHeaderExchangeDocument(writer);

            writer.WriteStartElement("rsm:SpecifiedSupplyChainTradeTransaction");

            writer.WriteStartElement("ram:ApplicableSupplyChainTradeAgreement");

            //Seller details.
            WriteUserDetails(writer, "ram:SellerTradeParty", Seller);

            //Buyer details
            WriteUserDetails(writer, "ram:BuyerTradeParty", Buyer);

            //End of ApplicableSupplyChainTradeAgreement
            writer.WriteEndElement();

            writer.WriteStartElement("ram:ApplicableSupplyChainTradeSettlement");

            writer.WriteElementString("ram:InvoiceCurrencyCode", Currency.ToString("g"));

            writer.WriteStartElement("ram:SpecifiedTradeSettlementMonetarySummation");

            WriteOptionalAmount(writer, "ram:GrandTotalAmount", TotalAmount);

            writer.WriteEndElement();

            writer.WriteEndElement();

            AddTradeLineItems(writer);

            writer.WriteEndDocument();
            writer.Flush();
            stream.Position = 0;
            return(stream);
        }
Example #53
0
        public static void CreateHtml(string filename, string url)
        {
            var n = 0;
            string progName = GetProgramName(url);
            using (var stream = new StreamWriter(filename))
            using (var xmlWr = new XmlTextWriter(stream) { Formatting = Formatting.Indented })
            {
                xmlWr.WriteStartElement("html");
                xmlWr.WriteStartElement("head");

                xmlWr.WriteStartElement("meta");
                xmlWr.WriteAttributeString("charset", "utf-8");
                xmlWr.WriteEndElement();//meta

                xmlWr.WriteStartElement("meta");
                xmlWr.WriteAttributeString("name", "author");
                xmlWr.WriteAttributeString("content", "Oleksandr Viter, [email protected]");
                xmlWr.WriteEndElement();//meta

                xmlWr.WriteStartElement("title");
                xmlWr.WriteString($"Подкасты программы «{progName}»");
                xmlWr.WriteEndElement();//title

                xmlWr.WriteStartElement("link");
                xmlWr.WriteAttributeString("rel", "icon");
                xmlWr.WriteAttributeString("type", "image/x-icon");
                xmlWr.WriteAttributeString("href", "https://echo.msk.ru/favicon.ico?echo");
                xmlWr.WriteEndElement();//link

                xmlWr.WriteStartElement("style");
                xmlWr.WriteString(
                    "table{" +
                    "  border: 3px solid;" +
                    "  border-collapse: collapse;" +
                    "}\r\n" +
                    "th{" +
                    "  background-color: #888888;" +
                    "  border-left: 2px solid;" +
                    "}\r\n" +
                    "td{" +
                    "  border-left: 2px solid;" +
                    "  padding: 10px;" +
                    "}\r\n" +
                    "tr{" +
                    "  border-top: 1px solid;" +
                    "}\r\n" +
                    "tr:nth-child(odd) {" +
                    "  background-color: #f2f2f2;" +
                    "}\r\n");
                xmlWr.WriteEndElement();//style
                xmlWr.WriteEndElement(); //head

                xmlWr.WriteStartElement("body");
                xmlWr.WriteStartElement("h2");
                xmlWr.WriteStartElement("a");
                xmlWr.WriteAttributeString("href", $"https://echo.msk.ru{url}");
                xmlWr.WriteAttributeString("target", "_blank");
                xmlWr.WriteAttributeString("title", $"Перейти на страницу программы «{progName}»");
                xmlWr.WriteString(progName);
                xmlWr.WriteEndElement();//a
                xmlWr.WriteEndElement();//h2
                xmlWr.WriteStartElement("table");

                foreach (var item in GetAllPodcastLinks(url))
                {
                    if (item.Url.IsNullOrEmpty())
                    {
                        continue;
                    }
                    OnLinkProcessed(++n);
                    //Console.Write($"\rПолучение ссылок: {++n}");
                    xmlWr.WriteStartElement("tr");

                    xmlWr.WriteStartElement("td");
                    xmlWr.WriteString(n.ToString().PadRight(10, '\u00A0'));
                    xmlWr.WriteEndElement();//td

                    xmlWr.WriteStartElement("td");

                    //xmlWr.WriteStartElement("p");
                    xmlWr.WriteStartElement("a");
                    xmlWr.WriteAttributeString("href", item.Url);
                    xmlWr.WriteAttributeString("title", $"Скачать подкаст за {item.DateTime}. ({item.Size.Trim()})");
                    xmlWr.WriteString($"{item.Title} ({item.Duration})");
                    xmlWr.WriteEndElement();//a
                    //xmlWr.WriteEndElement();//p

                    if (!item.Author.IsNullOrEmpty())
                    {
                        xmlWr.WriteRaw("<br>");
                        xmlWr.WriteString($"Автор: {item.Author}");
                    }

                    if (!item.Guests.IsNullOrEmpty())
                    {
                        xmlWr.WriteRaw("<br>");
                        //xmlWr.WriteStartElement("p");
                        xmlWr.WriteString($"Гости: {item.Guests}");
                        //xmlWr.WriteEndElement();//p
                    }

                    xmlWr.WriteEndElement();//td

                    xmlWr.WriteStartElement("td");
                    xmlWr.WriteString(item.DateTime);
                    xmlWr.WriteEndElement();//td

                    xmlWr.WriteEndElement();//tr
                }
            }

        }
Example #54
0
 internal override void WriteXml(XmlTextWriter xmlWriter)
 {
     WriteXml(xmlWriter, false);
 }
Example #55
0
        public static void Write(InventoryItem[] records, Order[] orders)
        {
            onEvent.Invoke("Opening File");
            XmlTextWriter textWriter;

            if (File.Exists("Data.xml"))
            {
                textWriter = new XmlTextWriter("Data.xml", Encoding.Unicode);
            }
            else
            {
                XDocument xmlFile = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XComment("XML File for storing Records"));
                xmlFile.Add(new XElement("Root"));
                xmlFile.Save("Data.xml");
                textWriter = new XmlTextWriter("Data.xml", Encoding.Unicode);
            }


            // Opens the document
            textWriter.WriteStartDocument();
            // Write comments
            textWriter.WriteComment("Inventory Data: LG Electronics. All Rights Reserved.");
            // Write first element
            textWriter.WriteStartElement("Data");
            textWriter.WriteStartElement("StockListing");
            foreach (InventoryItem record in records)
            {
                textWriter.WriteStartElement("Stock");
                // Write next element
                for (int i = 0; i < record.Keys.Length; i++)
                {
                    textWriter.WriteStartElement(record.Keys[i], "");
                    textWriter.WriteString(record.Values[i]);
                    textWriter.WriteEndElement();
                }

                textWriter.WriteEndElement();  // for Each record
            }

            textWriter.WriteEndElement(); // for StockListing

            textWriter.WriteStartElement("StockHistory");
            foreach (Order record in orders)
            {
                textWriter.WriteStartElement("History");
                // Write next element
                for (int i = 0; i < record.Keys.Length; i++)
                {
                    textWriter.WriteStartElement(record.Keys[i], "");
                    textWriter.WriteString(record.Values[i]);
                    textWriter.WriteEndElement();
                }

                textWriter.WriteEndElement();  // for Each record
            }

            textWriter.WriteEndElement(); // for StockHistory

            textWriter.WriteEndElement(); // for Data



            // Ends the document.
            textWriter.WriteEndDocument();
            // close writer
            textWriter.Close();
            onEvent.Invoke("Write Finished");
        }
        private bool modificarIngrediente()
        {
            bool check = false;
            try
            {
                #region Archivo existe
                if (File.Exists("ingredientes.xml"))
                {
                    XmlTextWriter temp = new XmlTextWriter("ingredientes.temp", null);
                    temp.Formatting = Formatting.Indented;
                    temp.WriteStartDocument();
                    temp.WriteStartElement("ingredientes");
                    XmlTextReader original = new XmlTextReader("ingredientes.xml");
                    int cont = 0, signo, nuevaCant;
                    string nombre, id, maxima, actual;
                    while (original.ReadToFollowing("ingrediente"))
                    {
                        id = original.GetAttribute(0);
                        original.ReadToFollowing("nombre");
                        nombre = original.ReadString();
                        original.ReadToFollowing("cantidad_maxima");
                        maxima = original.ReadString();
                        original.ReadToFollowing("cantidad_actual");
                        actual = original.ReadString();

                        //cambiar cantidad
                        if (id == this.textBox1.Text)
                        {
                            check = true;
                            if (radioButton1.Checked)
                                signo = 1;
                            else
                                signo = -1;
                            nuevaCant = Convert.ToInt32(actual) + Convert.ToInt32(this.textBox2.Text) * signo;
                            if (nuevaCant < 0)
                            {
                                MessageBox.Show("Cantidad retirada es mayor que la cantidad actual!", "Alerta",
                                MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                                temp.Close();
                                File.Delete("ingredientes.temp");
                                original.Close();
                                return false;
                            }
                            else if (nuevaCant > Convert.ToInt32(maxima))
                            {
                                MessageBox.Show("Nueva cantidad es mayor que la máxima permitida!", "Alerta",
                                MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                                temp.Close();
                                File.Delete("ingredientes.temp");
                                original.Close();
                                return false;
                            }
                            else
                                actual = nuevaCant.ToString();
                        }

                        //escribir temporal
                        temp.WriteStartElement("ingrediente");
                        temp.WriteAttributeString("id", id);
                        temp.WriteElementString("nombre", nombre);
                        temp.WriteElementString("cantidad_maxima", maxima);
                        temp.WriteElementString("cantidad_actual", actual);
                        temp.WriteEndElement();
                        cont++;
                    }
                    temp.WriteEndElement();
                    temp.WriteEndDocument();
                    temp.Flush();
                    temp.Close();
                    original.Close();
                    File.Delete("ingredientes.xml");
                    File.Move("ingredientes.temp", "ingredientes.xml");
                    if (check == false)
                    {
                        MessageBox.Show("No se modificó el inventario!\nEl ingrediente a modificar no existe!", "Notificación",
                        MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                }
                #endregion
                #region Archivo no existe
                else
                {
                    MessageBox.Show("No existe inventario de ingredientes!", "Alerta",
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return false;
                }
                #endregion
            }
            catch
            {
                return false;
            }
            finally
            {
                if (check)
                    MessageBox.Show("Ingrediente modificado correctamente!", "OK",
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            return check;
        }
Example #57
0
        public static void SaveLastUser(LastUser lastUser)
        {
            if (!lastUser.Remember)
            {
                return;
            }

            XmlDocument lastUserDoc = new XmlDocument
            {
                PreserveWhitespace = true
            };
            XmlNode    xmlDeclaration = lastUserDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            XmlElement root           = lastUserDoc.DocumentElement;

            lastUserDoc.InsertBefore(xmlDeclaration, root);

            XmlElement xRoot    = lastUserDoc.CreateElement("Последний_пользователь");
            XmlElement server   = lastUserDoc.CreateElement("Сервер");
            XmlElement login    = lastUserDoc.CreateElement("Логин");
            XmlElement password = lastUserDoc.CreateElement("Пароль");

            xRoot.AppendChild(server);
            xRoot.AppendChild(login);
            xRoot.AppendChild(password);
            server.AppendChild(lastUserDoc.CreateTextNode(lastUser.Server));
            login.AppendChild(lastUserDoc.CreateTextNode(lastUser.User));
            password.AppendChild(lastUserDoc.CreateTextNode(lastUser.Pass));
            lastUserDoc.AppendChild(xRoot);

            try
            {
                RijndaelManaged Key = new RijndaelManaged
                {
                    Key = key,
                    IV  = iv
                };
                Encrypt(Key, password);
            }
            catch (Exception e)
            {
                LogController.Error(logger, e, "Не удалось cоздать симметричный ключ");
            }

            //XDocument lastUserDoc1 = new XDocument(
            //    new XElement("Последний_пользователь",
            //    new XElement("Сервер", lastUser.Server),
            //    new XElement("Логин", lastUser.User),
            //    new XElement("Пароль", lastUser.Pass)
            //    ));

            try
            {
                string path = Settings.FilesSavePath + "LastUser.xml";
                if (!Directory.Exists(Settings.FilesSavePath))
                {
                    Directory.CreateDirectory(Settings.FilesSavePath);
                }
                using (XmlTextWriter writer = new XmlTextWriter(File.OpenWrite(path), null))
                {
                    writer.Formatting = Formatting.Indented;
                    lastUserDoc.Save(writer);
                    LogController.Info(logger, "Файл LastUser.xml успешно сохранен");
                }
            }
            catch (Exception e)
            {
                LogController.Error(logger, e, $"Не удалось сохранить файл LastUser.xml");
            }
        }
Example #58
0
        private void WriteProperties(XmlTextWriter writer, MarkupObject markupObj)
        {
            List <MarkupProperty> propertyElements = new List <MarkupProperty>();
            MarkupProperty        contentProperty  = null;
            string contentString = string.Empty;

            foreach (MarkupProperty markupProperty in markupObj.Properties)
            {
                if (IsContentProperty(markupObj, markupProperty))
                {
                    contentProperty = markupProperty;
                    continue;
                }

                if (markupProperty.IsValueAsString)
                {
                    contentString = markupProperty.Value as string;
                }
                else if (!markupProperty.IsComposite)
                {
                    string temp = markupProperty.Value == null ? string.Empty : markupProperty.Value.ToString();

                    if (markupProperty.IsAttached)
                    {
                        string ns1     = _namespaceCache.GetXmlNamespace(markupProperty.DependencyProperty.OwnerType);
                        string prefix1 = _namespaceCache.GetPrefixForNamespace(ns1);
                        if (string.IsNullOrEmpty(prefix1))
                        {
                            writer.WriteAttributeString(markupProperty.Name, temp);
                        }
                        else
                        {
                            writer.WriteAttributeString(prefix1 + ":" + markupProperty.Name, temp);
                        }
                    }
                    else
                    {
                        DependencyProperty dependencyProperty = markupProperty.DependencyProperty;
                        Type ownerType = dependencyProperty == null ? null : dependencyProperty.OwnerType;
                        if (markupProperty.Name == "Name" && ownerType != null && NamespaceCache.GetAssemblyNameFromType(ownerType).Equals("PresentationFramework"))
                        {
                            writer.WriteAttributeString("x:" + markupProperty.Name, temp);
                        }
                        else
                        {
                            writer.WriteAttributeString(markupProperty.Name, temp);
                        }
                    }
                }
                else if (markupProperty.Value.GetType() == typeof(NullExtension))
                {
                    writer.WriteAttributeString(markupProperty.Name, "{x:Null}");
                }
                else
                {
                    propertyElements.Add(markupProperty);
                }
            }

            if (contentProperty != null || propertyElements.Count > 0 || !string.IsNullOrEmpty(contentString))
            {
                foreach (MarkupProperty markupProp in propertyElements)
                {
                    string ns2             = _namespaceCache.GetXmlNamespace(markupObj.ObjectType);
                    string prefix2         = _namespaceCache.GetPrefixForNamespace(ns2);
                    string propElementName = markupObj.ObjectType.Name + "." + markupProp.Name;

                    WriteStartElement(writer, prefix2, propElementName);
                    WriteChildren(writer, markupProp);
                    writer.WriteEndElement();
                }

                if (!string.IsNullOrEmpty(contentString))
                {
                    writer.WriteValue(contentString);
                }
                else if (contentProperty != null)
                {
                    if (contentProperty.Value is string)
                    {
                        writer.WriteValue(contentProperty.StringValue);
                    }
                    else
                    {
                        WriteChildren(writer, contentProperty);
                    }
                }
            }
        }
Example #59
0
        public static string Serialize(SimplePointsToGraph ptg)
        {
            using (var stringWriter = new StringWriter())
                using (var xmlWriter = new XmlTextWriter(stringWriter))
                {
                    xmlWriter.Formatting = Formatting.Indented;
                    xmlWriter.WriteStartElement("DirectedGraph");
                    xmlWriter.WriteAttributeString("xmlns", "http://schemas.microsoft.com/vs/2009/dgml");
                    xmlWriter.WriteStartElement("Nodes");

                    foreach (var variable in ptg.Roots)
                    {
                        var label = variable.Name;

                        xmlWriter.WriteStartElement("Node");
                        xmlWriter.WriteAttributeString("Id", label);
                        xmlWriter.WriteAttributeString("Label", label);
                        xmlWriter.WriteAttributeString("Shape", "None");
                        xmlWriter.WriteEndElement();
                    }

                    foreach (var node in ptg.Nodes)
                    {
                        var nodeId = Convert.ToString(node.Id);
                        var label  = DGMLSerializer.Serialize(node);

                        xmlWriter.WriteStartElement("Node");
                        xmlWriter.WriteAttributeString("Id", nodeId);
                        xmlWriter.WriteAttributeString("Label", label);

                        if (node.Kind == PTGNodeKind.Null)
                        {
                            xmlWriter.WriteAttributeString("Background", "Yellow");
                        }
                        else if (node.Kind == PTGNodeKind.Delegate)
                        {
                            xmlWriter.WriteAttributeString("Background", "Cyan");
                        }
                        else if (node.Kind == PTGNodeKind.Parameter)
                        {
                            xmlWriter.WriteAttributeString("Background", "Red");
                            xmlWriter.WriteAttributeString("StrokeDashArray", "6,6");
                        }
                        else if (node.Kind == PTGNodeKind.Unknown)
                        {
                            xmlWriter.WriteAttributeString("Background", "#FFB445");
                            xmlWriter.WriteAttributeString("StrokeDashArray", "6,6");
                        }

                        xmlWriter.WriteEndElement();
                    }

                    xmlWriter.WriteEndElement();
                    xmlWriter.WriteStartElement("Links");

                    foreach (var variable in ptg.Roots)
                    {
                        var sourceId = variable.Name;
                        foreach (var target in ptg.GetTargets(variable))
                        {
                            var targetId = Convert.ToString(target.Id);

                            xmlWriter.WriteStartElement("Link");
                            xmlWriter.WriteAttributeString("Source", sourceId);
                            xmlWriter.WriteAttributeString("Target", targetId);
                            xmlWriter.WriteEndElement();
                        }
                    }

                    foreach (var node in ptg.Nodes)
                    {
                        var sourceId = Convert.ToString(node.Id);

                        foreach (var targetMap in ptg.GetTargets(node))
                        {
                            foreach (var target in targetMap.Value)
                            {
                                var targetId = Convert.ToString(target.Id);
                                var label    = targetMap.Key.Name;

                                xmlWriter.WriteStartElement("Link");
                                xmlWriter.WriteAttributeString("Source", sourceId);
                                xmlWriter.WriteAttributeString("Target", targetId);
                                xmlWriter.WriteAttributeString("Label", label);
                                xmlWriter.WriteEndElement();
                            }
                        }
                    }

                    xmlWriter.WriteEndElement();
                    xmlWriter.WriteStartElement("Styles");
                    xmlWriter.WriteStartElement("Style");
                    xmlWriter.WriteAttributeString("TargetType", "Node");

                    xmlWriter.WriteStartElement("Setter");
                    xmlWriter.WriteAttributeString("Property", "FontFamily");
                    xmlWriter.WriteAttributeString("Value", "Consolas");
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("Setter");
                    xmlWriter.WriteAttributeString("Property", "NodeRadius");
                    xmlWriter.WriteAttributeString("Value", "5");
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("Setter");
                    xmlWriter.WriteAttributeString("Property", "MinWidth");
                    xmlWriter.WriteAttributeString("Value", "0");
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteEndElement();
                    xmlWriter.WriteEndElement();
                    xmlWriter.WriteEndElement();
                    xmlWriter.Flush();
                    return(stringWriter.ToString());
                }
        }
Example #60
0
        string BuildPackageInternal(IProgressStatus monitor, string targetDirectory, string filePath)
        {
            AddinDescription conf = registry.GetAddinDescription(monitor, filePath);

            if (conf == null)
            {
                monitor.ReportError("Could not read add-in file: " + filePath, null);
                return(null);
            }

            string basePath = Path.GetFullPath(Path.GetDirectoryName(filePath));

            if (targetDirectory == null)
            {
                targetDirectory = basePath;
            }

            // Generate the file name

            string name;

            if (conf.LocalId.Length == 0)
            {
                name = Path.GetFileNameWithoutExtension(filePath);
            }
            else
            {
                name = conf.LocalId;
            }
            name = Addin.GetFullId(conf.Namespace, name, conf.Version);
            name = name.Replace(',', '_').Replace(".__", ".");

            string outFilePath = Path.Combine(targetDirectory, name) + ".mpack";

            ZipOutputStream s = new ZipOutputStream(File.Create(outFilePath));

            s.SetLevel(5);

            // Generate a stripped down description of the add-in in a file, since the complete
            // description may be declared as assembly attributes

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = false;
            doc.LoadXml(conf.SaveToXml().OuterXml);
            CleanDescription(doc.DocumentElement);
            MemoryStream  ms = new MemoryStream();
            XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);

            tw.Formatting = Formatting.Indented;
            doc.WriteTo(tw);
            tw.Flush();
            byte[] data = ms.ToArray();

            var infoEntry = new ZipEntry("addin.info")
            {
                Size = data.Length
            };

            s.PutNextEntry(infoEntry);
            s.Write(data, 0, data.Length);
            s.CloseEntry();

            // Now add the add-in files

            var files = new HashSet <string> ();

            files.Add(Path.GetFileName(Util.NormalizePath(filePath)));

            foreach (string f in conf.AllFiles)
            {
                files.Add(Util.NormalizePath(f));
            }

            foreach (var prop in conf.Properties)
            {
                try {
                    var file = Util.NormalizePath(prop.Value);
                    if (File.Exists(Path.Combine(basePath, file)))
                    {
                        files.Add(file);
                    }
                } catch {
                    // Ignore errors
                }
            }

            //add satellite assemblies for assemblies in the list
            var satelliteFinder = new SatelliteAssemblyFinder();

            foreach (var f in files.ToList())
            {
                foreach (var satellite in satelliteFinder.FindSatellites(Path.Combine(basePath, f)))
                {
                    var relativeSatellite = satellite.Substring(basePath.Length + 1);
                    files.Add(relativeSatellite);
                }
            }

            monitor.Log("Creating package " + Path.GetFileName(outFilePath));

            foreach (string file in files)
            {
                string fp = Path.Combine(basePath, file);
                using (FileStream fs = File.OpenRead(fp)) {
                    byte[] buffer = new byte [fs.Length];
                    fs.Read(buffer, 0, buffer.Length);

                    var fileName = Path.PathSeparator == '\\' ? file.Replace('\\', '/') : file;
                    var entry    = new ZipEntry(fileName)
                    {
                        Size = fs.Length
                    };
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                    s.CloseEntry();
                }
            }

            s.Finish();
            s.Close();
            return(outFilePath);
        }