示例#1
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);
            }
        }
    }
示例#2
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();
    }
    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);
    }
示例#4
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();

    }
示例#5
0
    public static void Main()
    {
        string pathToSourceFile = "../../../albums.xml";
        string pathToTargetFile = "../../../album.xml";
        Encoding encoding = Encoding.GetEncoding("windows-1251");
        using (XmlReader reader = XmlReader.Create(pathToSourceFile))
        {
            using (XmlTextWriter writer = new XmlTextWriter(pathToTargetFile, encoding))
            {
                string name = "", artist = "";
                writer.Formatting = Formatting.Indented;
                writer.IndentChar = '\t';
                writer.Indentation = 1;
                writer.WriteStartDocument();
                writer.WriteStartElement("albums");

                while (reader.Read())
                {
                    if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "name"))
                    {
                        name = reader.ReadElementString();
                    }

                    if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "artist"))
                    {
                        artist = reader.ReadElementString();
                        WriteAlbum(writer, name, artist);
                    }
                }

                writer.WriteEndDocument();
            }
        }
    }
示例#6
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 ();
	}
    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();
    }
示例#8
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();
            }
        }
    }
示例#9
0
    public XmlTextWriter WriteRSSClosing(XmlTextWriter writer)
    {
        writer.WriteEndElement();
           writer.WriteEndElement();
           writer.WriteEndDocument();

           return writer;
    }
示例#10
0
文件: Xml.cs 项目: walrus7521/code
 public static void Write()
 {
     XmlTextWriter writer = new XmlTextWriter(Console.Out);
     writer.WriteStartDocument();
     writer.WriteElementString("Hello", "Xml");
     writer.WriteEndDocument();
     writer.Close();
 }
    public static void WriteXmlReport(IEnumerable<XmlReport> reports)
    {

        string fileName = "../../../Sales-by-Vendors-report.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("sales");

            string vendorName = "";
            bool isFirst = true;
            foreach (var report in reports)
            {
                if (report.VendorName !=vendorName && isFirst == true)
                {
                    writer.WriteStartElement("sale");
                    writer.WriteAttributeString("vendor", report.VendorName);

                    writer.WriteStartElement("summary");
                    writer.WriteAttributeString("date", string.Format("{0:d}", report.FromDate));
                    writer.WriteAttributeString("total-sum", report.Sum.ToString());
                    writer.WriteEndElement();

                    vendorName = report.VendorName;
                    isFirst = false;
                }
                else if (report.VendorName !=vendorName && isFirst == false)
                {
                    writer.WriteEndElement();
                    writer.WriteStartElement("sale");
                    writer.WriteAttributeString("vendor", report.VendorName);

                    writer.WriteStartElement("summary");
                    writer.WriteAttributeString("date", string.Format("{0:d}", report.FromDate));
                    writer.WriteAttributeString("total-sum", report.Sum.ToString());
                    writer.WriteEndElement();

                    vendorName = report.VendorName;
                }
                else
                {
                    writer.WriteStartElement("summary");
                    writer.WriteAttributeString("date", string.Format("{0:d}", report.FromDate));
                    writer.WriteAttributeString("total-sum", report.Sum.ToString());
                    writer.WriteEndElement();
                }
            }
            writer.WriteEndElement();

            writer.WriteEndDocument();
        }
    }
示例#12
0
 public static void CreateXmlFile(string fileName, string rootElementName)
 {
     XmlTextWriter writer = new XmlTextWriter(fileName, System.Text.Encoding.UTF8);
     writer.WriteStartDocument();
     writer.Formatting = Formatting.Indented;
     writer.Indentation = 2;
     writer.WriteStartElement(rootElementName);
     writer.WriteEndElement();
     writer.WriteEndDocument();
     writer.Close();
 }
示例#13
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Cache.SetNoStore();
        Response.ContentType = "application/xml";
        DataTable dt = CreateBll.GetInfo(TABLE_NAME, 1, 100);

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

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

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

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

        CreateXMLContent(writer);

        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Close();
    }
    static void Main()
    {
        var albumsAuthors = new Dictionary<string, string>();
        string nameOfAlbum = string.Empty;
        string artistName = string.Empty;
        bool inAlbum = false;
        using (XmlReader reader = XmlReader.Create(@"..\..\..\catalogue.xml"))
        {
            while(reader.Read())
            {
                if(reader.Name == "album" && reader.NodeType == XmlNodeType.Element)
                {
                    inAlbum = true;
                }

                if(reader.Name == "album" && reader.NodeType == XmlNodeType.EndElement)
                {
                    albumsAuthors.Add(nameOfAlbum, artistName);
                    inAlbum = false;
                }

                if (inAlbum)
                {
                    if (reader.Name == "name")
                    {
                        nameOfAlbum = reader.ReadElementString();
                    }

                    if(reader.Name == "artist")
                    {
                        artistName = reader.ReadElementString();
                    }
                }
            }
        }

        string fileName = @"..\..\..\album.xml";
        Encoding encoding = Encoding.GetEncoding("utf-8");
        using (XmlTextWriter writer = new XmlTextWriter(fileName, encoding))
        {
            writer.Formatting = Formatting.Indented;
            writer.IndentChar = '\t';
            writer.Indentation = 1;

            writer.WriteStartDocument();
            writer.WriteStartElement("albums");
            foreach (var album in albumsAuthors)
            {
                WriteAlbum(writer, album.Key, album.Value);
            }
            writer.WriteEndDocument();
        }
    }
示例#17
0
    //===============================================================
    // Function: Page_Load
    //===============================================================
    protected void Page_Load(object sender, EventArgs e)
    {
        int userID = int.Parse(Request.QueryString["UID"].ToString());

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

        CreateXMLContent(writer, userID);

        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Close();
    }
示例#18
0
 protected void btnAdd_Click(object sender, EventArgs e)
 {
     XmlTextWriter xr = new XmlTextWriter(Server.MapPath("my.xml"), null);
     xr.WriteStartDocument();
     xr.WriteStartElement("Information");
     xr.WriteStartElement("infos");
     xr.WriteElementString("info", Editor1.Content);
     xr.WriteEndElement();
     xr.WriteEndElement();
     xr.WriteEndDocument();
     xr.Close();
     Fillinfos();
     Editor1.Content = "";
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        //Instantiate Action Stored Procedure object
        Blogic FetchData = new Blogic();

        int i = 0;

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

        //Get datatable
        IDataReader dr = FetchData.GetRSSMostPopularRecipe;

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

        dr.Close();

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

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

        FetchData = null;
    }
示例#20
0
 static void Main()
 {
     Console.WriteLine("Enter directory with escaping");
     string path = Console.ReadLine();
     StreamWriter textWriter = new StreamWriter("../../file-system.xml", false, Encoding.GetEncoding("utf-8"));
     XmlTextWriter writer = new XmlTextWriter(textWriter);
     using (writer)
     {
         writer.WriteStartDocument();
         writer.WriteStartElement("file-system");
         TraverseDFS(new DirectoryInfo(path), writer);
         writer.WriteEndElement();
         writer.WriteEndDocument();
     }
 }
示例#21
0
 public static void Main() {
 StringWriter w = new StringWriter();
 XmlTextWriter x = new XmlTextWriter(w);
 x.Formatting = Formatting.Indented;
 x.WriteStartDocument();
 x.WriteComment("a simple test");
 x.WriteStartElement("message");
 x.WriteStartAttribute("project", "");
 x.WriteString("Rotor");
 x.WriteEndAttribute();
 x.WriteString("Hello world!");
 x.WriteEndElement();
 x.WriteEndDocument();
 x.Flush();
 Console.WriteLine(w.ToString());
 }
	static void Main()
	{
		using (XmlTextWriter writer = new XmlTextWriter(
			"../../reviews-search-results.xml", Encoding.UTF8))
		{
			writer.Formatting = Formatting.Indented;
			writer.IndentChar = '\t';
			writer.Indentation = 1;

			writer.WriteStartDocument();
			writer.WriteStartElement("search-results");

			ProcessSearchQueries(writer);

			writer.WriteEndDocument();
		}			
	}
    static void Main()
    {
        using (XmlTextWriter writer = new XmlTextWriter(outputFile, Encoding.UTF8))
        {
            writer.Formatting = Formatting.Indented;
            writer.IndentChar = '\t';
            writer.Indentation = 1;

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

            TraverseDirectory(writer, rootDirectory);

            writer.WriteEndDocument();
            Console.WriteLine("XML file saved to {0}", outputFile);
        }
    }
示例#24
0
    static void Main()
    {
        using (var reader = XmlReader.Create(inputFile))
        {
            using (var writer = new XmlTextWriter(outputFile, Encoding.UTF8))
            {
                writer.Formatting = Formatting.Indented;
                writer.IndentChar = '\t';
                writer.Indentation = 1;

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

                bool openAlbum = false;

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.Name == "album")
                        {
                            if (openAlbum)
                            {
                                writer.WriteEndElement();
                            }

                            openAlbum = true;
                            writer.WriteStartElement("album");
                        }
                        else if (reader.Name == "name")
                        {
                            writer.WriteElementString("name", reader.ReadElementString());
                        }
                        else if (reader.Name == "artist")
                        {
                            writer.WriteElementString("artist", reader.ReadElementString());
                        }
                    }
                }

                writer.WriteEndDocument();
                Console.WriteLine("XML file saved to {0}", outputFile);
            }
        }
    }
示例#25
0
    //===============================================================
    // Function: Page_Load
    //===============================================================
    protected void Page_Load(object sender, EventArgs e)
    {
        string searchText = "";
        if (Request.QueryString["Search"] != null)
        {
            searchText = (string)Request.QueryString["Search"];
        }

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

        CreateXMLContent(writer, searchText);

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

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

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

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

        dr.Close();

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

        //Close the XmlTextWriter object
        objX.Flush();
        objX.Close();
        Response.End();
    }
示例#27
0
    static void Main()
    {
        List<string> autors = new List<string>();
        List<string> albums = new List<string>();

        using (XmlReader reader = XmlReader.Create("../../../catalog.xml"))
        {
            while (reader.Read())
            {
                if ((reader.NodeType == XmlNodeType.Element) &&
                    (reader.Name == "artist"))
                {
                    autors.Add(reader.ReadElementString());
                }
                if ((reader.NodeType == XmlNodeType.Element) &&
                    (reader.Name == "name"))
                {
                    albums.Add(reader.ReadElementString());
                }
            }
        }

        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");
            for (int i = 0; i < albums.Count; i++)
            {
                writer.WriteStartElement("album");
                writer.WriteElementString("name", albums[i]);
                writer.WriteElementString("author", autors[i]);
                writer.WriteEndElement();
            }

            writer.WriteEndDocument();
        }
    }
示例#28
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");

        VikkiSoft_BLL.Country cont = new VikkiSoft_BLL.Country();
        if (cont.LoadSiteMap())
        {
            string siteUrl = Request.Url.Scheme + Uri.SchemeDelimiter + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
            if (!Request.Url.IsDefaultPort)
            {
                siteUrl += ":" + Request.Url.Port;
            }
            siteUrl += "/";
            AddURL(writer, siteUrl, "Default.aspx", cont.DateUpdate);
            AddURL(writer, siteUrl, "Blogs.aspx", cont.DateUpdate);
            do
            {
                string url = "";
                if (cont.GetColumn("BlogPageID").ToString() != "0")
                {
                    url = Utils.GenerateFriendlyURL("page", new string[] { cont.GetColumn("BlogPageID").ToString(), cont.GetColumn("BlogPageName_en").ToString() }, false);
                }
                else if(cont.GetColumn("CityName").ToString() == "")
                {
                    url = Utils.GenerateFriendlyURL("country", new string[] { cont.GetColumn("CountryName").ToString() }, false);
                }
                else{
                    url = Utils.GenerateFriendlyURL("city", new string[] { cont.GetColumn("CountryName").ToString(), cont.GetColumn("CityName").ToString() }, false);
                }
                AddURL(writer, siteUrl, url, cont.DateUpdate);
            } while (cont.MoveNext());
        }

        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Flush();
        Response.End();
    }
示例#29
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int i = 0;

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

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

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

        dr.Close();

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

        //Close the XmlTextWriter object
        objX.Flush();
        objX.Close();
        Response.End();
    }
示例#30
0
    static void Main()
    {
        SimpleSearch();

        string fileName = Bookstore.Data.Settings.Default.complexSearchWriteFile;
        using (XmlTextWriter writer =
            new XmlTextWriter(fileName, Encoding.UTF8))
        {
            writer.Formatting = Formatting.Indented;
            writer.IndentChar = '\t';
            writer.Indentation = 1;

            writer.WriteStartDocument();
            writer.WriteStartElement("search-results");

            ComplexSearch(writer);

            writer.WriteEndDocument();
        }
    }
示例#31
0
        /// <summary>
        /// saves the current map into a file
        /// </summary>
        /// <param name="mapName">string</param>
        public virtual void saveMap(string mapName)
        {
            XmlTextWriter xml = new XmlTextWriter(mapName, null);

            try
            {
                //string json = JsonConvert.SerializeObject(this.accessPointsMap);
                //fileWriter.Write(json);

                xml.WriteStartDocument();
                xml.WriteStartElement("map");
                xml.WriteWhitespace("");

                int sectorCounter = 0;

                // cycle through map
                foreach (KeyValuePair <int, Sector> keyValPair in this.accessPointsMap)
                {
                    sectorCounter++;

                    int maxSectors = this.accessPointsMap.Count;

                    int    sectorNumber = keyValPair.Key;
                    Sector sector       = keyValPair.Value;

                    xml.WriteStartElement("sector");

                    xml.WriteStartElement("number");
                    xml.WriteString(sectorNumber.ToString());
                    xml.WriteEndElement();

                    xml.WriteStartElement("x");
                    xml.WriteString(sector.getX().ToString());
                    xml.WriteEndElement();

                    xml.WriteStartElement("y");
                    xml.WriteString(sector.getY().ToString());
                    xml.WriteEndElement();

                    Dictionary <string, AccessPoint> accessPointDictionary = sector.getAccessPoints();

                    int apCount = 0;
                    foreach (KeyValuePair <string, AccessPoint> entryPair in accessPointDictionary)
                    {
                        string      bssid       = entryPair.Key;
                        AccessPoint accessPoint = entryPair.Value;

                        xml.WriteStartElement("accesspoint");
                        xml.WriteStartElement("bssid");
                        xml.WriteString(accessPoint.getBssid());
                        xml.WriteEndElement();
                        xml.WriteStartElement("rssi");
                        xml.WriteString(accessPoint.getRssi().ToString());
                        xml.WriteEndElement();
                        xml.WriteEndElement();

                        apCount++;
                    }

                    xml.WriteStartElement("stop");
                    xml.WriteString("stop");
                    xml.WriteEndElement();

                    xml.WriteEndElement();
                }

                xml.WriteEndElement();
                xml.WriteEndDocument();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            finally
            {
                xml.Close();
            }
        }
示例#32
0
 public void Close()
 {
     writer.WriteEndDocument();
     writer.Close();
 }
示例#33
0
        public XmlNode GetScene(Scene scene, XmlDocument factory)
        {
            m_log.Debug("[DATASNAPSHOT]: Data requested for scene " + scene.RegionInfo.RegionName);

            if (!m_scenes.ContainsKey(scene))
            {
                m_scenes.Add(scene, true); //stale by default
            }

            XmlNode regionElement = null;

            if (!m_scenes[scene])
            {
                m_log.Info("[DATASNAPSHOT]: Attempting to retrieve snapshot from cache.");
                //get snapshot from cache
                String path = DataFileNameScene(scene);

                XmlDocument fragDocument = new XmlDocument();
                fragDocument.PreserveWhitespace = true;

                fragDocument.Load(path);

                foreach (XmlNode node in fragDocument)
                {
                    regionElement = factory.ImportNode(node, true);
                }

                m_log.Info("[DATASNAPSHOT]: Obtained snapshot from cache for " + scene.RegionInfo.RegionName);
            }
            else
            {
                m_log.Info("[DATASNAPSHOT]: Attempting to generate snapshot.");
                //make snapshot
                regionElement = MakeRegionNode(scene, factory);

                regionElement.AppendChild(GetGridSnapshotData(factory));
                XmlNode regionData = factory.CreateNode(XmlNodeType.Element, "data", "");

                foreach (IDataSnapshotProvider dataprovider in m_providers)
                {
                    if (dataprovider.GetParentScene == scene)
                    {
                        regionData.AppendChild(GetFragment(dataprovider, factory));
                    }
                }

                regionElement.AppendChild(regionData);

                factory.AppendChild(regionElement);

                //save snapshot
                String path = DataFileNameScene(scene);

                using (XmlTextWriter snapXWriter = new XmlTextWriter(path, Encoding.Default))
                {
                    snapXWriter.Formatting = Formatting.Indented;
                    snapXWriter.WriteStartDocument();
                    regionElement.WriteTo(snapXWriter);
                    snapXWriter.WriteEndDocument();
                }

                m_scenes[scene] = false;

                m_log.Info("[DATASNAPSHOT]: Generated new snapshot for " + scene.RegionInfo.RegionName);
            }

            return(regionElement);
        }
        void WriteProjectFile(TextWriter writer, IEnumerable <Tuple <string, string> > files, ModuleDefinition module)
        {
            const string ns           = "http://schemas.microsoft.com/developer/msbuild/2003";
            string       platformName = GetPlatformName(module);
            Guid         guid         = this.ProjectGuid ?? Guid.NewGuid();

            using (XmlTextWriter w = new XmlTextWriter(writer)) {
                w.Formatting = Formatting.Indented;
                w.WriteStartDocument();
                w.WriteStartElement("Project", ns);
                w.WriteAttributeString("ToolsVersion", "4.0");
                w.WriteAttributeString("DefaultTargets", "Build");

                w.WriteStartElement("PropertyGroup");
                w.WriteElementString("ProjectGuid", guid.ToString("B").ToUpperInvariant());

                w.WriteStartElement("Configuration");
                w.WriteAttributeString("Condition", " '$(Configuration)' == '' ");
                w.WriteValue("Debug");
                w.WriteEndElement();                 // </Configuration>

                w.WriteStartElement("Platform");
                w.WriteAttributeString("Condition", " '$(Platform)' == '' ");
                w.WriteValue(platformName);
                w.WriteEndElement();                 // </Platform>

                switch (module.Kind)
                {
                case ModuleKind.Windows:
                    w.WriteElementString("OutputType", "WinExe");
                    break;

                case ModuleKind.Console:
                    w.WriteElementString("OutputType", "Exe");
                    break;

                default:
                    w.WriteElementString("OutputType", "Library");
                    break;
                }

                w.WriteElementString("AssemblyName", module.Assembly.Name.Name);
                bool            useTargetFrameworkAttribute = false;
                LanguageTargets languageTargets             = LanguageTargets.None;
                var             targetFrameworkAttribute    = module.Assembly.CustomAttributes.FirstOrDefault(a => a.AttributeType.FullName == "System.Runtime.Versioning.TargetFrameworkAttribute");
                if (targetFrameworkAttribute != null && targetFrameworkAttribute.ConstructorArguments.Any())
                {
                    string   frameworkName       = (string)targetFrameworkAttribute.ConstructorArguments[0].Value;
                    string[] frameworkParts      = frameworkName.Split(',');
                    string   frameworkIdentifier = frameworkParts.FirstOrDefault(a => !a.StartsWith("Version=", StringComparison.OrdinalIgnoreCase) && !a.StartsWith("Profile=", StringComparison.OrdinalIgnoreCase));
                    if (frameworkIdentifier != null)
                    {
                        w.WriteElementString("TargetFrameworkIdentifier", frameworkIdentifier);
                        switch (frameworkIdentifier)
                        {
                        case ".NETPortable":
                            languageTargets = LanguageTargets.Portable;
                            break;
                        }
                    }
                    string frameworkVersion = frameworkParts.FirstOrDefault(a => a.StartsWith("Version=", StringComparison.OrdinalIgnoreCase));
                    if (frameworkVersion != null)
                    {
                        w.WriteElementString("TargetFrameworkVersion", frameworkVersion.Substring("Version=".Length));
                        useTargetFrameworkAttribute = true;
                    }
                    string frameworkProfile = frameworkParts.FirstOrDefault(a => a.StartsWith("Profile=", StringComparison.OrdinalIgnoreCase));
                    if (frameworkProfile != null)
                    {
                        w.WriteElementString("TargetFrameworkProfile", frameworkProfile.Substring("Profile=".Length));
                    }
                }
                if (!useTargetFrameworkAttribute)
                {
                    switch (module.Runtime)
                    {
                    case TargetRuntime.Net_1_0:
                        w.WriteElementString("TargetFrameworkVersion", "v1.0");
                        break;

                    case TargetRuntime.Net_1_1:
                        w.WriteElementString("TargetFrameworkVersion", "v1.1");
                        break;

                    case TargetRuntime.Net_2_0:
                        w.WriteElementString("TargetFrameworkVersion", "v2.0");
                        // TODO: Detect when .NET 3.0/3.5 is required
                        break;

                    default:
                        w.WriteElementString("TargetFrameworkVersion", "v4.0");
                        break;
                    }
                }
                w.WriteElementString("WarningLevel", "4");
                w.WriteElementString("AllowUnsafeBlocks", "True");

                w.WriteEndElement();                  // </PropertyGroup>

                w.WriteStartElement("PropertyGroup"); // platform-specific
                w.WriteAttributeString("Condition", " '$(Platform)' == '" + platformName + "' ");
                w.WriteElementString("PlatformTarget", platformName);
                w.WriteEndElement();                  // </PropertyGroup> (platform-specific)

                w.WriteStartElement("PropertyGroup"); // Debug
                w.WriteAttributeString("Condition", " '$(Configuration)' == 'Debug' ");
                w.WriteElementString("OutputPath", "bin\\Debug\\");
                w.WriteElementString("DebugSymbols", "true");
                w.WriteElementString("DebugType", "full");
                w.WriteElementString("Optimize", "false");
                w.WriteEndElement();                  // </PropertyGroup> (Debug)

                w.WriteStartElement("PropertyGroup"); // Release
                w.WriteAttributeString("Condition", " '$(Configuration)' == 'Release' ");
                w.WriteElementString("OutputPath", "bin\\Release\\");
                w.WriteElementString("DebugSymbols", "true");
                w.WriteElementString("DebugType", "pdbonly");
                w.WriteElementString("Optimize", "true");
                w.WriteEndElement();                 // </PropertyGroup> (Release)


                w.WriteStartElement("ItemGroup");                 // References
                foreach (AssemblyNameReference r in module.AssemblyReferences)
                {
                    if (r.Name != "mscorlib")
                    {
                        w.WriteStartElement("Reference");
                        w.WriteAttributeString("Include", r.Name);
                        var asm = module.AssemblyResolver.Resolve(r);
                        if (!IsGacAssembly(r, asm))
                        {
                            if (asm != null)
                            {
                                w.WriteElementString("HintPath", asm.MainModule.FileName);
                            }
                        }
                        w.WriteEndElement();
                    }
                }
                w.WriteEndElement();                 // </ItemGroup> (References)

                foreach (IGrouping <string, string> gr in (from f in files group f.Item2 by f.Item1 into g orderby g.Key select g))
                {
                    w.WriteStartElement("ItemGroup");
                    foreach (string file in gr.OrderBy(f => f, StringComparer.OrdinalIgnoreCase))
                    {
                        w.WriteStartElement(gr.Key);
                        w.WriteAttributeString("Include", file);
                        w.WriteEndElement();
                    }
                    w.WriteEndElement();
                }
                switch (languageTargets)
                {
                case LanguageTargets.Portable:
                    w.WriteStartElement("Import");
                    w.WriteAttributeString("Project", "$(MSBuildExtensionsPath32)\\Microsoft\\Portable\\$(TargetFrameworkVersion)\\Microsoft.Portable.CSharp.targets");
                    w.WriteEndElement();
                    break;

                default:
                    w.WriteStartElement("Import");
                    w.WriteAttributeString("Project", "$(MSBuildToolsPath)\\Microsoft.CSharp.targets");
                    w.WriteEndElement();
                    break;
                }

                w.WriteEndDocument();
            }
        }
示例#35
0
 protected void WriteEnd(XmlTextWriter xmlWriter)
 {
     xmlWriter.WriteEndDocument();
 }
示例#36
0
        private void SaveButton_Click(object sender, EventArgs e)
        {
            string Data1;
            string Data2;
            string Data3;
            string Data4;
            string Data5;
            string Data6;
            string Data7;
            string Data8;
            string Data9;
            string Data10;
            string Data11;
            string Data12;
            string Data13;
            string Data14;
            string Data15;
            string Data16;

            Data1  = TextBox11.Text;
            Data2  = TextBox12.Text;
            Data3  = TextBox7.Text;
            Data4  = TextBox3.Text;
            Data5  = TextBox4.Text;
            Data6  = TextBox5.Text;
            Data7  = TextBox2.Text;
            Data8  = TextBox8.Text;
            Data9  = TextBox6.Text;
            Data10 = TextBox14.Text;
            Data11 = textBox1.Text;
            Data12 = comboBox1.Text;
            Data13 = textBox15.Text;
            Data14 = textBox16.Text;
            Data16 = textBox9.Text;


            if (String.IsNullOrEmpty(textBox9.Text) || String.IsNullOrEmpty(textBox16.Text) || String.IsNullOrEmpty(textBox15.Text) ||
                String.IsNullOrEmpty(comboBox1.Text) || String.IsNullOrEmpty(textBox1.Text) || String.IsNullOrEmpty(TextBox14.Text) || String.IsNullOrEmpty(TextBox6.Text) ||
                String.IsNullOrEmpty(TextBox8.Text) || String.IsNullOrEmpty(TextBox2.Text) || String.IsNullOrEmpty(TextBox5.Text) || String.IsNullOrEmpty(TextBox4.Text) ||
                String.IsNullOrEmpty(TextBox3.Text) || String.IsNullOrEmpty(TextBox7.Text) || String.IsNullOrEmpty(TextBox12.Text) || String.IsNullOrEmpty(TextBox11.Text))
            {
                MessageBox.Show("Please don't leave any fields empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                if (TextBox3.Text.Length < 15)
                {
                    Data4 = TextBox3.Text.PadRight(TextBox3.Text.Length + (15 - TextBox3.Text.Length), ' ');
                }
                if (TextBox4.Text.Length < 15)
                {
                    Data5 = TextBox4.Text.PadRight(TextBox4.Text.Length + (15 - TextBox4.Text.Length), ' ');
                }
                string Year = DateTime.Now.Year.ToString();

                Random rnd     = new Random();
                int    num     = rnd.Next(0000000, 9999999);
                string license = "MH03 " + Year + Convert.ToString(num);
                Data15 = license;

                XmlTextWriter text1 = new XmlTextWriter("License.xml", System.Text.Encoding.UTF8);
                text1.WriteStartDocument(true);
                text1.Formatting  = Formatting.Indented;
                text1.Indentation = 2;
                text1.WriteStartElement("License");
                Generate(Data1, Data2, Data3, Data4, Data5, Data6, Data7, Data8, Data9, Data10, Data11, Data12, Data13, Data14, Data15, Data16, text1);
                text1.WriteEndElement();
                text1.WriteEndDocument();
                text1.Close();

                MessageBox.Show("License #: " + Data15 + " Generated", "License Number Generated", MessageBoxButtons.OK, MessageBoxIcon.None);
                Form3 See = new Form3();
                See.Show();
                this.Visible = false;
            }
        }
        /// <summary>
        /// This method first connects to the organization service. Afterwards,
        /// auditing is enabled on the organization, account entity, and a couple
        /// of attributes. Finally, display that information in Console, and creates
        /// an XML file.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            _sampleStartTime = DateTime.Now;
            using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
            {
                // This statement is required to enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

                // You can access the service through the proxy, but this sample uses the interface instead.
                _service = _serviceProxy;

                #region Enable Auditing for an Account

                Console.WriteLine("Enabling auditing on the organization and account entities.");

                // Enable auditing on the organization.
                // First, get the organization's ID from the system user record.
                Guid orgId = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).OrganizationId;

                // Next, retrieve the organization's record.
                Organization org = _service.Retrieve(Organization.EntityLogicalName, orgId,
                                                     new ColumnSet(new string[] { "organizationid", "isauditenabled" })) as Organization;

                // Finally, enable auditing on the organization.
                bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                bool usersAccessAuditingFlag  = org.IsUserAccessAuditEnabled.HasValue ?
                                                org.IsUserAccessAuditEnabled.Value : false;

                org.IsAuditEnabled           = true;
                org.IsUserAccessAuditEnabled = true;
                _service.Update(org);

                // Enable auditing on account entities.
                bool accountAuditingFlag = EnableEntityAuditing(Account.EntityLogicalName, true);

                #endregion Enable Auditing for an Account

                CreateRequiredRecords();

                #region Create and start XML file

                // Create the XML file
                String fileName = "auditReport.xml";
                textWriter = new XmlTextWriter(fileName, null);
                textWriter.WriteStartDocument();

                // Start Audit Node
                textWriter.WriteStartElement("auditReport", "");

                #endregion

                #region Retrieve user access audit records

                var query = new QueryExpression(Audit.EntityLogicalName)
                {
                    ColumnSet = new ColumnSet("createdon", "action", "operation", "objectid"),
                    Criteria  = new FilterExpression(LogicalOperator.And)
                };

                // Only retrieve audit records that track user access.
                query.Criteria.AddCondition("action", ConditionOperator.In,
                                            (int)AuditAction.UserAccessAuditStarted,
                                            (int)AuditAction.UserAccessAuditStopped,
                                            (int)AuditAction.UserAccessviaWebServices,
                                            (int)AuditAction.UserAccessviaWeb);

                // Change this to false in order to retrieve audit records for all users
                // when running the sample.
                var filterAuditsRetrievedByUser = true;
                if (filterAuditsRetrievedByUser)
                {
                    // Only retrieve audit records for the current user.
                    var userFilter = new FilterExpression(LogicalOperator.Or);
                    userFilter.AddCondition(
                        "userid", ConditionOperator.Equal, _serviceProxy.CallerId);
                }
                // Only retrieve records for this sample run, so that we don't get too
                // many results if auditing was enabled previously.
                query.Criteria.AddCondition(
                    "createdon", ConditionOperator.GreaterEqual, _sampleStartTime);

                var results = _serviceProxy.RetrieveMultiple(query);
                foreach (Audit audit in results.Entities)
                {
                    // Display results
                    DisplayAndAddToXMLFileUserAccessDetails(audit);
                }

                #endregion

                #region Retrieve the Audit History
                Console.WriteLine("Retrieving the account change history.\n");

                DateTime startTime = DateTime.Now;

                // Retrieve the audit records for accounts.
                RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
                changeRequest.Target = new EntityReference(Account.EntityLogicalName, _newAccountId);

                RetrieveRecordChangeHistoryResponse changeResponse =
                    (RetrieveRecordChangeHistoryResponse)_service.Execute(changeRequest);

                AuditDetailCollection details = changeResponse.AuditDetailCollection;

                foreach (AttributeAuditDetail detail in details.AuditDetails)
                {
                    // Write out some of the information in each audit record.
                    DisplayAndAddToXMLFileAuditDetails(detail);
                }
                #endregion Retrieve the Audit History

                #region RetrieveAttributeChangeHistoryRequest
                // How to use message: RetrieveAttributeChangeHistoryRequest

                // Update Telephone1 in account entity
                Account accountToUpdate = new Account();
                accountToUpdate.AccountId  = _newAccountId;
                accountToUpdate.Telephone1 = "123-555-5555";
                _serviceProxy.Update(accountToUpdate);
                Console.WriteLine("Updated Telephone1 field in Account entity.");

                Console.WriteLine("Retrieving attribute change history for Telephone1.");
                // Create RetrieveAttributeChangeHistoryRequest
                var attributeChangeHistoryRequest = new RetrieveAttributeChangeHistoryRequest
                {
                    Target = new EntityReference(
                        Account.EntityLogicalName, _newAccountId),
                    AttributeLogicalName = "telephone1"
                };

                // Execute RetrieveAttributeChangeHistoryRequest
                var attributeChangeHistoryResponse =
                    (RetrieveAttributeChangeHistoryResponse)_service.Execute(attributeChangeHistoryRequest);

                // Set AuditDetailCollection and output to console
                details = attributeChangeHistoryResponse.AuditDetailCollection;

                foreach (var detail in details.AuditDetails)
                {
                    DisplayAndAddToXMLFileAuditDetails(detail);
                }

                // Create an Audit record
                // to store a sample for use with RetrieveAuditDetailsRequest
                Guid auditSampleId = details.AuditDetails.First().AuditRecord.Id;
                #endregion RetrieveAttributeChangeHistoryRequest

                #region RetrieveAuditDetailsRequest
                // How to use message: RetrieveAuditDetailsRequest

                Console.WriteLine("Retrieving audit details for an audit record.");
                // Create RetrieveAuditDetailsRequest
                var auditDetailsRequest = new RetrieveAuditDetailsRequest
                {
                    AuditId = auditSampleId
                };

                // Execute RetrieveAuditDetailsRequest
                var auditDetailsResponse =
                    (RetrieveAuditDetailsResponse)_service.Execute(auditDetailsRequest);

                // Display results
                DisplayAndAddToXMLFileAuditDetails(auditDetailsResponse.AuditDetail);

                #endregion RetrieveAuditDetailsRequest

                #region Retrieve AuditExtension details

                Console.WriteLine("Simulating a user reading records");
                _service.Retrieve(Account.EntityLogicalName, _newAccountId, new ColumnSet("accountid"));

                // creating read records is an async process - wait until the records have been created
                // wait a max of 30 seconds
                Console.WriteLine("Fetching read audit records for accounts");
                for (int i = 0; i < 30; i++)
                {
                    query = new QueryExpression
                    {
                        EntityName = "sample_auditextension",
                        ColumnSet  = new ColumnSet("createdon", "sample_objectlogicalname",
                                                   "sample_objectid", "sample_userid", "sample_action", "sample_operation"),
                        Criteria = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression("sample_objectlogicalname", ConditionOperator.Equal, Account.EntityLogicalName),
                                new ConditionExpression("sample_objectid",          ConditionOperator.Equal,
                                                        _newAccountId.ToString().TrimStart('{').TrimEnd('}'))
                            }
                        }
                    };
                    results = _service.RetrieveMultiple(query);
                    if (results.Entities.Count > 0)
                    {
                        break;
                    }
                    else if (i == 29)
                    {
                        throw new Exception("Exceeded maximum wait time");
                    }
                    System.Threading.Thread.Sleep(1000);
                }

                foreach (var record in results.Entities)
                {
                    _auditExtensionRecordIds.Add(record.Id);
                    DisplayAndAddToXmlFileAuditExtension(record);
                }

                #endregion

                #region Finish and close XML file

                // End auditReport Xml Node
                textWriter.WriteEndElement();
                textWriter.WriteEndDocument();

                // Close xml writer.
                textWriter.Close();

                Console.WriteLine("File name: " + fileName);

                #endregion

                #region Revert auditing
                // Set the organization and account auditing flags back to the old values
                org.IsAuditEnabled           = organizationAuditingFlag;
                org.IsUserAccessAuditEnabled = usersAccessAuditingFlag;
                _service.Update(org);

                EnableEntityAuditing(Account.EntityLogicalName, accountAuditingFlag);

                #endregion Revert auditing

                DeleteRequiredRecords(promptforDelete);
            }
        }
示例#38
0
        public void SetUpXML(string ProcessName, string Folio)
        {
            //Gets the settings file


            if (!File.Exists(xmlFileName))
            {
                XmlTextWriter writer = new XmlTextWriter(xmlFileName, System.Text.Encoding.UTF8);
                writer.WriteStartDocument(true);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartElement("Settings");
                writer.WriteStartElement("ProcessName");
                writer.WriteString(ProcessName);
                writer.WriteEndElement();
                writer.WriteStartElement("Folio");
                writer.WriteString(Folio);
                writer.WriteEndElement();
                writer.WriteStartElement("ProcessInstanceId");
                writer.WriteString("0");
                writer.WriteEndElement();
                writer.WriteStartElement("StartStatus");
                writer.WriteString("Stop");
                writer.WriteEndElement();
                writer.WriteStartElement("TaskCount");
                writer.WriteAttributeString("Actual", "0");
                writer.WriteEndAttribute();
                writer.WriteString("0");
                writer.WriteEndElement();
                writer.WriteStartElement("SerialNumber");
                writer.WriteString("0");
                writer.WriteEndElement();
                writer.WriteStartElement("Destination");
                writer.WriteString("0");
                writer.WriteEndElement();
                writer.WriteStartElement("TaskActivity");
                writer.WriteString("0");
                writer.WriteEndElement();
                writer.WriteStartElement("Actions");
                writer.WriteStartElement("Action");
                writer.WriteString("0");
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteStartElement("ActionResult");
                writer.WriteString("0");
                writer.WriteEndElement();
                writer.WriteStartElement("Activities");

                writer.WriteStartElement("Activity");

                writer.WriteString("0");
                writer.WriteStartElement("Event");
                writer.WriteString("0");
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
            }
            else
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlFileName);
                xmlDoc.ChildNodes[1].ChildNodes[0].InnerXml = ProcessName;
                xmlDoc.ChildNodes[1].ChildNodes[1].InnerXml = Folio;
                xmlDoc.Save(xmlFileName);
            }
        }
        /// <summary>
        /// Get an XML Message to send in the email
        /// </summary>
        /// <returns></returns>
        public string GetXMLMessage()
        {
            //Write XML file to a memory stream
            MemoryStream  memStream  = new MemoryStream();
            XmlTextWriter textWriter = new XmlTextWriter(memStream, Encoding.ASCII);

            textWriter.Formatting = Formatting.Indented;

            // Opens the document
            textWriter.WriteStartDocument();

            // Write first element
            textWriter.WriteStartElement("Error");

            //Error XML Version
            textWriter.WriteStartElement("ErrorXMLVersion", "");
            textWriter.WriteString("1.0");
            textWriter.WriteEndElement();

            //Error Information
            textWriter.WriteStartElement("ProgramName", "");
            textWriter.WriteString(ProgramName);
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("AssemblyName", "");
            textWriter.WriteString(AssemblyName);
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("Class", "");
            textWriter.WriteString(ClassName);
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("Procedure", "");
            textWriter.WriteString(ProcedureName);
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("Version", "");
            textWriter.WriteString(Version);
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("ErrorMessage", "");
            textWriter.WriteString(GUIException.Message);
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("StackTrace", "");
            textWriter.WriteString(GUIException.StackTrace);
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("AdditionalInfo", "");
            textWriter.WriteString(AdditionalInfo);
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("Source", "");
            textWriter.WriteString(GUIException.Source);
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("Target", "");
            textWriter.WriteString(GUIException.TargetSite.ToString());
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("ExceptionType", "");
            textWriter.WriteString(GUIException.GetType().ToString());
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("ErrorDate", "");
            textWriter.WriteString(FormatUtil.FormatUSDateTime(DateTime.Now) + "  (" + SystemUtil.GetCurrentTimeZone() + ")");
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("Steps", "");
            textWriter.WriteString(Steps);
            textWriter.WriteEndElement();

            //System Information
            textWriter.WriteStartElement("UserName", "");
            textWriter.WriteString(UserName);
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("PCName", "");
            textWriter.WriteString(Environment.MachineName);
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("Culture", "");
            textWriter.WriteString(Culture);
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("OS", "");
            textWriter.WriteString(SystemInfo.GetOSVersion());
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("CPU", "");
            textWriter.WriteString(SystemInfo.GetCPUInfo());
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("RAM", "");
            textWriter.WriteString(SystemInfo.GetTotalRAM());
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("HD", "");
            textWriter.WriteString(SystemInfo.GetFreeSpace(Path.GetPathRoot(Environment.CurrentDirectory)));
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("Framework", "");
            textWriter.WriteString(Environment.Version.ToString());
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("SystemDirectory", "");
            textWriter.WriteString(Environment.SystemDirectory);
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("CurrentDirectory", "");
            textWriter.WriteString(FileUtil.GetCurrentDirectory());
            textWriter.WriteEndElement();

            //Write Final element
            textWriter.WriteEndElement();

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

            // close writer
            textWriter.Close();

            return(Encoding.ASCII.GetString(memStream.ToArray()));
        }
示例#40
0
        /// <summary>
        /// retrived parameter info from the net
        /// </summary>
        public static void GetParameterInformation(string urls, string file = null)
        {
            httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("User-Agent", Settings.Instance.UserAgent);
            httpClient.Timeout = TimeSpan.FromSeconds(30);

            var parameterLocationsString = urls;

            string XMLFileName =
                String.Format("{0}{1}", Settings.GetUserDataDirectory(), "ParameterMetaData.xml");

            if (file != null)
            {
                XMLFileName = String.Format("{0}{1}", Settings.GetUserDataDirectory(), file);
            }

            if (!String.IsNullOrEmpty(parameterLocationsString))
            {
                var parameterLocations = parameterLocationsString.Split(';').ToList();
                parameterLocations.RemoveAll(String.IsNullOrEmpty);

                ParallelOptions opt = new ParallelOptions()
                {
                    MaxDegreeOfParallelism = 3
                };

                // precache all the base urls
                Parallel.ForEach(parameterLocations, opt,
                                 parameterLocation =>
                {
                    // load the base urls
                    var dataFromAddress = ReadDataFromAddress(parameterLocation.Trim());
                    // load the group urls
                    ParseGroupInformation(dataFromAddress, null, parameterLocation.Trim(), string.Empty,
                                          string.Empty);
                });

                using (var objXmlTextWriter = new XmlTextWriter(XMLFileName, null))
                {
                    objXmlTextWriter.Formatting = Formatting.Indented;
                    objXmlTextWriter.WriteStartDocument();

                    objXmlTextWriter.WriteStartElement("Params");

                    parameterLocations.Sort((a, b) => GetVehicle(a).CompareTo(GetVehicle(b)));

                    var lastelement = "";
                    foreach (string parameterLocation in parameterLocations)
                    {
                        string element = GetVehicle(parameterLocation.ToLower());

                        // Read and parse the content.
                        string dataFromAddress = ReadDataFromAddress(parameterLocation.Trim());

                        if (String.IsNullOrEmpty(dataFromAddress)) // 404
                        {
                            continue;
                        }

                        if (dataFromAddress.Length < 200) // blank template file
                        {
                            continue;
                        }

                        // write start and end
                        if (lastelement != element)
                        {
                            // Write the end element for this parameter location
                            if (lastelement != "")
                            {
                                objXmlTextWriter.WriteEndElement();
                            }
                            // Write the start element for this parameter location
                            objXmlTextWriter.WriteStartElement(element);
                            lastelement = element;
                        }
                        ParseParameterInformation(dataFromAddress, objXmlTextWriter, string.Empty, string.Empty, element);
                        ParseGroupInformation(dataFromAddress, objXmlTextWriter, parameterLocation.Trim(), string.Empty, element);
                    }

                    objXmlTextWriter.WriteEndElement();

                    objXmlTextWriter.WriteEndElement();

                    // Clear the stream
                    objXmlTextWriter.WriteEndDocument();
                    objXmlTextWriter.Flush();
                    objXmlTextWriter.Close();
                }

                XElement root = XElement.Load(XMLFileName);
                foreach (var vech in root.Elements())
                {
                    var paramlist = vech.Elements().OrderBy(xt => xt.Name.ToString()).Distinct(new NameComparer()).ToArray();

                    vech.RemoveAll();

                    foreach (var item in paramlist)
                    {
                        vech.Add(item);
                    }
                }
                root.Save(XMLFileName);

                Console.WriteLine("Saved to " + XMLFileName);
            }
        }
示例#41
0
        //---------------------------------------------------------------------
        public static void Run()
        {
            string file = "index.html";
            string url  = "http://finance.i.ua/";

            Download(file, url);
            string buffer = GetBuffer(file);

            using StringReader reader = new StringReader(buffer);

            int countBank   = Regex.Matches(buffer, @"<option value=.\d+.").Count;
            var bankNames   = new Dictionary <int, string>(countBank);
            int bankNameMax = 0;

            Dictionary <int, (double buy, double sell)> bankRates = null;

            for (string s; true;)
            {
                s = reader.ReadLine();
                if (s.Contains("converter.rates"))
                {
                    var r = Regex.Matches(s, @".\d+.:{.*?}}");
                    bankRates = new Dictionary <int, (double buy, double sell)>(r.Count);

                    foreach (Match item in r)
                    {
                        int id = int.Parse(Regex.Match(item.Value, @".\d+.:{").Value.Trim('"', ':', '{'));

                        string tmp  = Regex.Match(item.Value, @".USD.*?}").Value;
                        double buy  = double.Parse(Regex.Match(tmp, @"\d*\.\d*,").Value.TrimEnd(',').Replace('.', ','));
                        double sell = double.Parse(Regex.Match(tmp, @"\d*\.\d*}").Value.TrimEnd('}').Replace('.', ','));

                        bankRates.Add(id, (Math.Round(buy, 2), Math.Round(sell, 2)));
                    }
                }
                else if (Regex.IsMatch(s, @"<option value=.\d+."))
                {
                    string tmp  = Regex.Match(s, @".\d+.>.*?<").Value;
                    string name = Regex.Match(tmp, @">.*?<").Value.Trim('>', '<');
                    int    id   = int.Parse(Regex.Match(tmp, @".\d+.").Value.Trim('"', '"'));

                    bankNames.Add(id, name);

                    if (name.Length > bankNameMax)
                    {
                        bankNameMax = name.Length;
                    }
                    if (bankNames.Count == countBank)
                    {
                        break;
                    }
                }
            }

            var bankArray = new List <(string Name, double buy, double sell)>(bankNames.Count);

            foreach (var bankName in bankNames)
            {
                bankArray.Add
                (
                    (bankName.Value
                     , bankRates[bankName.Key].buy
                     , bankRates[bankName.Key].sell)
                );
            }

            Console.WriteLine(" Bank:".PadRight(bankNameMax + 2)
                              + "buy:".PadRight(6)
                              + "sell:" + "\n ".PadRight(bankNameMax + 14, '\''));


            using XmlTextWriter xmlW = new XmlTextWriter("output.xml", Encoding.Unicode);
            xmlW.WriteStartDocument();
            xmlW.WriteStartElement("Banks");

            foreach (var bank in bankArray)
            {
                xmlW.WriteStartElement("Bank");
                xmlW.WriteAttributeString("Name", bank.Name);
                xmlW.WriteElementString("buy", bank.buy.ToString());
                xmlW.WriteElementString("sell", bank.sell.ToString());
                xmlW.WriteEndElement();

                Console.WriteLine($" {bank.Name}".PadRight(bankNameMax + 2)
                                  + $"{bank.buy}".PadRight(6)
                                  + $"{bank.sell}");
            }

            xmlW.WriteEndElement();
            xmlW.WriteEndDocument();
        }
示例#42
0
        void WriteProjectFile(DnSpyFileList dnSpyFileList, TextWriter writer, IEnumerable <Tuple <string, string> > files, DnSpyFile assembly, DecompilationOptions options)
        {
            var          module       = assembly.ModuleDef;
            const string ns           = "http://schemas.microsoft.com/developer/msbuild/2003";
            string       platformName = CSharpLanguage.GetPlatformName(module);
            Guid         guid         = (App.CommandLineArguments == null ? null : App.CommandLineArguments.FixedGuid) ?? Guid.NewGuid();

            using (XmlTextWriter w = new XmlTextWriter(writer)) {
                var asmRefs = CSharpLanguage.GetAssemblyRefs(dnSpyFileList, options, assembly);

                w.Formatting = Formatting.Indented;
                w.WriteStartDocument();
                w.WriteStartElement("Project", ns);
                w.WriteAttributeString("ToolsVersion", "4.0");
                w.WriteAttributeString("DefaultTargets", "Build");

                w.WriteStartElement("PropertyGroup");
                w.WriteElementString("ProjectGuid", (options.ProjectGuid ?? guid).ToString("B").ToUpperInvariant());

                w.WriteStartElement("Configuration");
                w.WriteAttributeString("Condition", " '$(Configuration)' == '' ");
                w.WriteValue("Debug");
                w.WriteEndElement();                 // </Configuration>

                w.WriteStartElement("Platform");
                w.WriteAttributeString("Condition", " '$(Platform)' == '' ");
                w.WriteValue(platformName);
                w.WriteEndElement();                 // </Platform>

                switch (module.Kind)
                {
                case ModuleKind.Windows:
                    w.WriteElementString("OutputType", "WinExe");
                    break;

                case ModuleKind.Console:
                    w.WriteElementString("OutputType", "Exe");
                    break;

                default:
                    w.WriteElementString("OutputType", "Library");
                    break;
                }

                if (module.Assembly != null)
                {
                    w.WriteElementString("AssemblyName", IdentifierEscaper.Escape(module.Assembly.Name));
                }
                bool useTargetFrameworkAttribute = false;
                var  targetFrameworkAttribute    = module.Assembly == null ? null : module.Assembly.CustomAttributes.FirstOrDefault(a => a.TypeFullName == "System.Runtime.Versioning.TargetFrameworkAttribute");
                if (targetFrameworkAttribute != null && targetFrameworkAttribute.ConstructorArguments.Any())
                {
                    string   frameworkName    = (targetFrameworkAttribute.ConstructorArguments[0].Value as UTF8String) ?? string.Empty;
                    string[] frameworkParts   = frameworkName.Split(',');
                    string   frameworkVersion = frameworkParts.FirstOrDefault(a => a.StartsWith("Version="));
                    if (frameworkVersion != null)
                    {
                        w.WriteElementString("TargetFrameworkVersion", frameworkVersion.Substring("Version=".Length));
                        useTargetFrameworkAttribute = true;
                    }
                    string frameworkProfile = frameworkParts.FirstOrDefault(a => a.StartsWith("Profile="));
                    if (frameworkProfile != null)
                    {
                        w.WriteElementString("TargetFrameworkProfile", frameworkProfile.Substring("Profile=".Length));
                    }
                }
                if (!useTargetFrameworkAttribute)
                {
                    if (module.IsClr10)
                    {
                        w.WriteElementString("TargetFrameworkVersion", "v1.0");
                    }
                    else if (module.IsClr11)
                    {
                        w.WriteElementString("TargetFrameworkVersion", "v1.1");
                    }
                    else if (module.IsClr20)
                    {
                        w.WriteElementString("TargetFrameworkVersion", "v2.0");
                        // TODO: Detect when .NET 3.0/3.5 is required
                    }
                    else
                    {
                        w.WriteElementString("TargetFrameworkVersion", "v4.0");
                    }
                }
                w.WriteElementString("WarningLevel", "4");

                w.WriteEndElement();                  // </PropertyGroup>

                w.WriteStartElement("PropertyGroup"); // platform-specific
                w.WriteAttributeString("Condition", " '$(Platform)' == '" + platformName + "' ");
                w.WriteElementString("PlatformTarget", platformName);
                w.WriteEndElement();                  // </PropertyGroup> (platform-specific)

                w.WriteStartElement("PropertyGroup"); // Debug
                w.WriteAttributeString("Condition", " '$(Configuration)' == 'Debug' ");
                w.WriteElementString("OutputPath", "bin\\Debug\\");
                w.WriteElementString("DebugSymbols", "true");
                w.WriteElementString("DebugType", "full");
                w.WriteElementString("Optimize", "false");
                if (options.DontReferenceStdLib)
                {
                    w.WriteStartElement("NoStdLib");
                    w.WriteString("true");
                    w.WriteEndElement();
                }
                w.WriteEndElement();                  // </PropertyGroup> (Debug)

                w.WriteStartElement("PropertyGroup"); // Release
                w.WriteAttributeString("Condition", " '$(Configuration)' == 'Release' ");
                w.WriteElementString("OutputPath", "bin\\Release\\");
                w.WriteElementString("DebugSymbols", "true");
                w.WriteElementString("DebugType", "pdbonly");
                w.WriteElementString("Optimize", "true");
                if (options.DontReferenceStdLib)
                {
                    w.WriteStartElement("NoStdLib");
                    w.WriteString("true");
                    w.WriteEndElement();
                }
                w.WriteEndElement();                 // </PropertyGroup> (Release)


                w.WriteStartElement("ItemGroup");                 // References
                foreach (var r in asmRefs)
                {
                    if (r.Name != "mscorlib")
                    {
                        var asm = dnSpyFileList.AssemblyResolver.Resolve(r, module);
                        if (asm != null && CSharpLanguage.ExistsInProject(options, asm.Filename))
                        {
                            continue;
                        }
                        w.WriteStartElement("Reference");
                        w.WriteAttributeString("Include", IdentifierEscaper.Escape(r.Name));
                        var hintPath = CSharpLanguage.GetHintPath(options, asm);
                        if (hintPath != null)
                        {
                            w.WriteStartElement("HintPath");
                            w.WriteString(hintPath);
                            w.WriteEndElement();
                        }
                        w.WriteEndElement();
                    }
                }
                w.WriteEndElement();                 // </ItemGroup> (References)

                foreach (IGrouping <string, string> gr in (from f in files group f.Item2 by f.Item1 into g orderby g.Key select g))
                {
                    w.WriteStartElement("ItemGroup");
                    foreach (string file in gr.OrderBy(f => f, StringComparer.OrdinalIgnoreCase))
                    {
                        w.WriteStartElement(gr.Key);
                        w.WriteAttributeString("Include", file);
                        w.WriteEndElement();
                    }
                    w.WriteEndElement();
                }

                w.WriteStartElement("ItemGroup");                 // ProjectReference
                foreach (var r in asmRefs)
                {
                    var asm = dnSpyFileList.AssemblyResolver.Resolve(r, module);
                    if (asm == null)
                    {
                        continue;
                    }
                    var otherProj = CSharpLanguage.FindOtherProject(options, asm.Filename);
                    if (otherProj != null)
                    {
                        var relPath = CSharpLanguage.GetRelativePath(options.SaveAsProjectDirectory, otherProj.ProjectFileName);
                        w.WriteStartElement("ProjectReference");
                        w.WriteAttributeString("Include", relPath);
                        w.WriteStartElement("Project");
                        w.WriteString(otherProj.ProjectGuid.ToString("B").ToUpperInvariant());
                        w.WriteEndElement();
                        w.WriteStartElement("Name");
                        w.WriteString(IdentifierEscaper.Escape(otherProj.AssemblySimpleName));
                        w.WriteEndElement();
                        w.WriteEndElement();
                    }
                }
                w.WriteEndElement();                 // </ItemGroup> (ProjectReference)

                w.WriteStartElement("ItemGroup");    // Imports
                foreach (var import in projectImports.OrderBy(x => x))
                {
                    w.WriteStartElement("Import");
                    w.WriteAttributeString("Include", import);
                    w.WriteEndElement();
                }
                w.WriteEndElement();                 // </ItemGroup> (Imports)

                w.WriteStartElement("Import");
                w.WriteAttributeString("Project", "$(MSBuildToolsPath)\\Microsoft.VisualBasic.targets");
                w.WriteEndElement();

                w.WriteEndDocument();
            }
        }
示例#43
0
        protected void Page_Load(object sender, EventArgs e)
        {
            #region XMLWriter

            using (XmlTextWriter Writer = new XmlTextWriter("C:\\Users\\August\\Documents\\MIXML.xml", Encoding.Unicode))
            {
                Writer.WriteStartDocument();
                Writer.Formatting  = Formatting.Indented;
                Writer.Indentation = 12;

                Writer.WriteStartElement("data");

                Writer.WriteStartElement("Questionnaire");
                Writer.WriteElementString("Name", "OES");
                Writer.WriteElementString("ExtendedName", "Oxford Elbow Score");
                Writer.WriteElementString("DateFormat", "DDMMYYYY");
                Writer.WriteEndElement();

                Writer.WriteStartElement("Header");

                Writer.WriteElementString("InitialQuestion", "On which side of your body is the affected joint, for which you are receiving treatment");

                Writer.WriteStartElement("InitialQuestionAnswers");
                Writer.WriteElementString("Answer", "Left");
                Writer.WriteElementString("Answer", "Right");
                Writer.WriteElementString("Answer", "Both");
                Writer.WriteEndElement();

                Writer.WriteStartElement("QuestionsHeader");
                Writer.WriteElementString("QuestionTitle", "Problems with your Elbow");
                Writer.WriteElementString("Instruction", "If you said 'both', please complete the first questionnaire thinking about the right side. A second questionnaire, for the left side, will follow.");
                Writer.WriteElementString("PerQuestionInstruction", "During the past 4 weeks...");
                Writer.WriteEndElement();

                Writer.WriteEndElement();

                Writer.WriteStartElement("Questions");

                Writer.WriteStartElement("Question");
                Writer.WriteElementString("Text", "Have you had difficulty lifting things in your home, such as putting the rubbish, because of your elbow problem?");
                Writer.WriteStartElement("Answers");
                Writer.WriteElementString("Answer", "No difficulty");
                Writer.WriteElementString("Answer", "A little bit of difficulty");
                Writer.WriteElementString("Answer", "Moderate Difficulty");
                Writer.WriteElementString("Answer", "Extreme Difficulty");
                Writer.WriteElementString("Answer", "Impossible to do");
                Writer.WriteEndElement();
                Writer.WriteEndElement();

                Writer.WriteStartElement("Question");
                Writer.WriteElementString("Text", "Have you had difficulty carrying bags of shopping,  because of your elbow problem?");
                Writer.WriteStartElement("Answers");
                Writer.WriteElementString("Answer", "No difficulty");
                Writer.WriteElementString("Answer", "A little bit of difficulty");
                Writer.WriteElementString("Answer", "Moderate Difficulty");
                Writer.WriteElementString("Answer", "Extreme Difficulty");
                Writer.WriteElementString("Answer", "Impossible to do");
                Writer.WriteEndElement();
                Writer.WriteEndElement();

                Writer.WriteStartElement("Question");
                Writer.WriteElementString("Text", "Have you had any difficulty washing yourself all over,  because of your elbow problem?");
                Writer.WriteStartElement("Answers");
                Writer.WriteElementString("Answer", "No difficulty");
                Writer.WriteElementString("Answer", "A little bit of difficulty");
                Writer.WriteElementString("Answer", "Moderate Difficulty");
                Writer.WriteElementString("Answer", "Extreme Difficulty");
                Writer.WriteElementString("Answer", "Impossible to do");
                Writer.WriteEndElement();
                Writer.WriteEndElement();

                Writer.WriteStartElement("Question");
                Writer.WriteElementString("Text", "Have you had any difficulty dressing yourself,  because of your elbow problem?");
                Writer.WriteStartElement("Answers");
                Writer.WriteElementString("Answer", "No difficulty");
                Writer.WriteElementString("Answer", "A little bit of difficulty");
                Writer.WriteElementString("Answer", "Moderate Difficulty");
                Writer.WriteElementString("Answer", "Extreme Difficulty");
                Writer.WriteElementString("Answer", "Impossible to do");
                Writer.WriteEndElement();
                Writer.WriteEndElement();

                Writer.WriteStartElement("Question");
                Writer.WriteElementString("Text", "Have you felt your elbow problem is 'controlling your life'?");
                Writer.WriteStartElement("Answers");
                Writer.WriteElementString("Answer", "No, not at all");
                Writer.WriteElementString("Answer", "Ocassionally");
                Writer.WriteElementString("Answer", "Some Days");
                Writer.WriteElementString("Answer", "Most Days");
                Writer.WriteElementString("Answer", "Every Day");
                Writer.WriteEndElement();
                Writer.WriteEndElement();

                Writer.WriteStartElement("Question");
                Writer.WriteElementString("Text", "How much has your elbow problem been 'on your mind'?");
                Writer.WriteStartElement("Answers");
                Writer.WriteElementString("Answer", "No, no at all");
                Writer.WriteElementString("Answer", "A little bit of the time");
                Writer.WriteElementString("Answer", "Some of the time");
                Writer.WriteElementString("Answer", "Most of the time");
                Writer.WriteElementString("Answer", "All of the time");
                Writer.WriteEndElement();
                Writer.WriteEndElement();

                Writer.WriteStartElement("Question");
                Writer.WriteElementString("Text", "Have you been troubled by pain from your elbow problem in bed at night?");
                Writer.WriteStartElement("Answers");
                Writer.WriteElementString("Answer", "Not at all");
                Writer.WriteElementString("Answer", "1 or 2 nights");
                Writer.WriteElementString("Answer", "Some nights");
                Writer.WriteElementString("Answer", "Most nights");
                Writer.WriteElementString("Answer", "Every night");
                Writer.WriteEndElement();
                Writer.WriteEndElement();

                Writer.WriteStartElement("Question");
                Writer.WriteElementString("Text", "How often has your elbow pain interfered with your sleeping?");
                Writer.WriteStartElement("Answers");
                Writer.WriteElementString("Answer", "No, not at all");
                Writer.WriteElementString("Answer", "Ocassionally");
                Writer.WriteElementString("Answer", "Some of the time");
                Writer.WriteElementString("Answer", "Most of the time");
                Writer.WriteElementString("Answer", "All of the time");
                Writer.WriteEndElement();
                Writer.WriteEndElement();

                Writer.WriteStartElement("Question");
                Writer.WriteElementString("Text", "How much has your elbow problem interfered with your usual work or every day activities?");
                Writer.WriteStartElement("Answers");
                Writer.WriteElementString("Answer", "Not at all");
                Writer.WriteElementString("Answer", "A little bit");
                Writer.WriteElementString("Answer", "Moderately");
                Writer.WriteElementString("Answer", "Greatly");
                Writer.WriteElementString("Answer", "Totally");
                Writer.WriteEndElement();
                Writer.WriteEndElement();

                Writer.WriteStartElement("Question");
                Writer.WriteElementString("Text", "Has your elbow problem limited your ability to take part in leisure activities that you enjoy doing?");
                Writer.WriteStartElement("Answers");
                Writer.WriteElementString("Answer", "No, not at all");
                Writer.WriteElementString("Answer", "Ocassionally");
                Writer.WriteElementString("Answer", "Some of the time");
                Writer.WriteElementString("Answer", "Most of the time");
                Writer.WriteElementString("Answer", "All of the time");
                Writer.WriteEndElement();
                Writer.WriteEndElement();

                Writer.WriteStartElement("Question");
                Writer.WriteElementString("Text", "How would you describe the worst pain you have from your elbow?");

                Writer.WriteStartElement("Answers");
                Writer.WriteElementString("Answer", "No Pain");
                Writer.WriteElementString("Answer", "Mild Pain");
                Writer.WriteElementString("Answer", "Moderate Pain");
                Writer.WriteElementString("Answer", "Severe Pain");
                Writer.WriteElementString("Answer", "Unbearable");
                Writer.WriteEndElement();

                Writer.WriteEndElement();

                Writer.WriteStartElement("Question");
                Writer.WriteElementString("Text", "How would you describe the pain you usually have from your elbow");

                Writer.WriteStartElement("Answers");
                Writer.WriteElementString("Answer", "No Pain");
                Writer.WriteElementString("Answer", "Mild Pain");
                Writer.WriteElementString("Answer", "Moderate Pain");
                Writer.WriteElementString("Answer", "Severe Pain");
                Writer.WriteElementString("Answer", "Unbearable");
                Writer.WriteEndElement();

                Writer.WriteEndElement();

                Writer.WriteEndElement();

                Writer.WriteStartElement("Scores");

                Writer.WriteElementString("MetricScore", "(100 / Maximum Possible Domain Score) * Actual Score");

                Writer.WriteStartElement("Score");
                Writer.WriteElementString("Min", "0");
                Writer.WriteElementString("Max", "19");
                Writer.WriteElementString("Message", "May indicate severe elbow arthritis. It is highly likely that you may well require some form of surgical intervention, contact your family physician for a consult with an Orthopaedic Surgeon");
                Writer.WriteEndElement();

                Writer.WriteStartElement("Score");
                Writer.WriteElementString("Min", "20");
                Writer.WriteElementString("Max", "29");
                Writer.WriteElementString("Message", "May indicate moderate to severe elbow arthritis. See your family physician for an assessment and x-ray. Consider a consult with an Orthopaedic Surgeon");
                Writer.WriteEndElement();

                Writer.WriteStartElement("Score");
                Writer.WriteElementString("Min", "30");
                Writer.WriteElementString("Max", "39");
                Writer.WriteElementString("Message", "May indicate mild to moderate elbow arthritis. Consider seeing your family physician for an assessment and possible x-ray. You may benefit from non surgical treatment, such as excercise, weight loss, and/or anti-inflammatory medication.");
                Writer.WriteEndElement();

                Writer.WriteStartElement("Score");
                Writer.WriteElementString("Min", "40");
                Writer.WriteElementString("Max", "49");
                Writer.WriteElementString("Message", "May indicate satisfactory joint function. May not require any formal treatment.");
                Writer.WriteEndElement();

                Writer.WriteEndElement();

                Writer.WriteStartElement("Domains");

                Writer.WriteStartElement("Domain");
                Writer.WriteElementString("Name", "Pain Domain");
                Writer.WriteElementString("Question", "7");
                Writer.WriteElementString("Question", "8");
                Writer.WriteElementString("Question", "12");
                Writer.WriteElementString("Question", "11");
                Writer.WriteElementString("MaximumScoreDomain", "16");
                Writer.WriteEndElement();

                Writer.WriteStartElement("Domain");
                Writer.WriteElementString("Name", "Elbow Function");
                Writer.WriteElementString("Question", "4");
                Writer.WriteElementString("Question", "3");
                Writer.WriteElementString("Question", "1");
                Writer.WriteElementString("Question", "2");
                Writer.WriteElementString("MaximumScoreDomain", "16");
                Writer.WriteEndElement();

                Writer.WriteStartElement("Domain");
                Writer.WriteElementString("Name", "Social Psychological");
                Writer.WriteElementString("Question", "10");
                Writer.WriteElementString("Question", "6");
                Writer.WriteElementString("Question", "5");
                Writer.WriteElementString("Question", "9");
                Writer.WriteElementString("MaximumScoreDomain", "16");
                Writer.WriteEndElement();

                Writer.WriteEndElement();

                Writer.WriteStartElement("Footer");
                Writer.WriteElementString("Note", "Have you had difficulty lifting things in your home, such as putting the rubbish, because of your elbow problem?");
                Writer.WriteEndElement();

                Writer.WriteEndDocument();
                Writer.Flush();
            }
            #endregion

            // Leer XML
            #region Leer XML

            #region Questionnaire
            XmlDocument reader = new XmlDocument();
            reader.Load("C:\\Users\\August\\Documents\\csharp\\MIXML.xml");

            XmlNodeList listaNodos = reader.SelectNodes("data/Questionnaire");
            XmlNode     Questionnaire;

            for (int i = 0; i < listaNodos.Count; i++)
            {
                Questionnaire = listaNodos.Item(i);

                string Name = Questionnaire.SelectSingleNode("Name").InnerText;

                string ExtendedName = Questionnaire.SelectSingleNode("ExtendedName").InnerText;
                string DateFormat   = Questionnaire.SelectSingleNode("DateFormat").InnerText;
                Label1.Text = Label1.Text + "<br/>" + Name + "<br/>" + ExtendedName + "<br/>" + DateFormat + "<br/>";
            }
            #endregion
            #region Header

            listaNodos = reader.SelectNodes("data/Header");
            XmlNode Header;

            for (int i = 0; i < listaNodos.Count; i++)
            {
                Header = listaNodos.Item(i);

                string InitialQuestion = Header.SelectSingleNode("InitialQuestion").InnerText;
                Label1.Text = Label1.Text + InitialQuestion + "<br/>";
                XmlNodeList InitialQuestionAnswers = Header.SelectSingleNode("InitialQuestionAnswers").SelectNodes("Answer");
                XmlNode     Answer;

                for (int f = 0; f < InitialQuestionAnswers.Count; f++)
                {
                    Answer = InitialQuestionAnswers.Item(f);

                    string CurrentAnswer = Answer.InnerText;
                    Label1.Text = Label1.Text + CurrentAnswer + "<br/>";
                }
            }
            #endregion
            #region QuestionsHeader
            XmlNodeList listaQuestionsHeader = reader.SelectNodes("data/QuestionsHeader");
            XmlNode     QuestionsHeader;

            for (int i = 0; i < listaQuestionsHeader.Count; i++)
            {
                QuestionsHeader = listaQuestionsHeader.Item(i);

                string QuestionTitle = QuestionsHeader.SelectSingleNode("QuestionTitle").InnerText;

                string Instruction            = QuestionsHeader.SelectSingleNode("Instruction").InnerText;
                string PerQuestionInstruction = QuestionsHeader.SelectSingleNode("PerQuestionInstruction").InnerText;
                Label1.Text = Label1.Text + QuestionTitle + "<br/>" + Instruction + "<br/>" + PerQuestionInstruction + "<br/>";
            }
            #endregion
            #region Questions

            listaNodos = reader.SelectNodes("data/Questions");
            XmlNode QQuestion;

            // Label1.Text = listaNodos.Count.ToString();
            for (int i = 0; i < listaNodos.Count; i++)
            {
                QQuestion = listaNodos.Item(i);

                XmlNodeList Questions = QQuestion.SelectNodes("Question");

                XmlNode Question;
                XmlNode Answer;

                for (int f = 0; f < Questions.Count; f++)
                {
                    Question = Questions.Item(f);

                    string CurrentQuestion = Question.SelectSingleNode("Text").InnerText;
                    Label1.Text = Label1.Text + CurrentQuestion + "<br/>";
                    XmlNodeList CurrentQuestionAnswers = Question.SelectSingleNode("Answers").SelectNodes("Answer");

                    for (int g = 0; g < CurrentQuestionAnswers.Count; g++)
                    {
                        Answer = CurrentQuestionAnswers.Item(g);
                        string CurrentAnswer = Answer.InnerText;
                        Label1.Text = Label1.Text + CurrentAnswer + "<br/>";
                    }
                }
            }
            #endregion
            #region Scores
            listaNodos = reader.SelectNodes("data/Scores");
            XmlNode Scores;

            for (int i = 0; i < listaNodos.Count; i++)
            {
                Scores = listaNodos.Item(i);

                string MetricScore = Scores.SelectSingleNode("MetricScore").InnerText;
                Label1.Text = Label1.Text + MetricScore + "<br/>";
                XmlNodeList SScores = Scores.SelectNodes("Score");
                XmlNode     Score;

                for (int f = 0; f < SScores.Count; f++)
                {
                    Score = SScores.Item(f);

                    string Min     = Score.SelectSingleNode("Min").InnerText;
                    string Max     = Score.SelectSingleNode("Max").InnerText;
                    string Message = Score.SelectSingleNode("Message").InnerText;
                    Label1.Text = Label1.Text + Min + "<br/>" + Max + "<br/>" + Message + "<br/>";
                }
            }
            #endregion

            #region Domains
            listaNodos = reader.SelectNodes("data/Domains");
            XmlNode Domain;

            for (int i = 0; i < listaNodos.Count; i++)
            {
                Domain = listaNodos.Item(i);

                XmlNodeList DomainName = Domain.SelectSingleNode("Domain").SelectNodes("Name");
                XmlNode     DName;
                for (int f = 0; f < DomainName.Count; f++)
                {
                    DName = DomainName.Item(f);
                    string CurrentDomain = DName.InnerText;
                    Label1.Text = Label1.Text + CurrentDomain + "<br/>";
                }

                XmlNodeList DQuestion = Domain.SelectSingleNode("Domain").SelectNodes("Question");
                XmlNode     DomainQuestion;

                for (int f = 0; f < DQuestion.Count; f++)
                {
                    DomainQuestion = DQuestion.Item(f);

                    string CurrentDomainQuestion = DomainQuestion.InnerText;
                    Label1.Text = Label1.Text + CurrentDomainQuestion + "<br/>";
                }

                XmlNodeList MaximumScoreDomain = Domain.SelectSingleNode("Domain").SelectNodes("MaximumScoreDomain");
                XmlNode     MaxScoreDomain;

                for (int f = 0; f < MaximumScoreDomain.Count; f++)
                {
                    MaxScoreDomain = MaximumScoreDomain.Item(f);

                    string CurrentMaxScoreDomain = MaxScoreDomain.InnerText;
                    Label1.Text = Label1.Text + CurrentMaxScoreDomain + "<br/>";
                }
            }
            #endregion

            #region Footer
            listaNodos = reader.SelectNodes("data/Footer");
            XmlNode Footer;

            for (int i = 0; i < listaNodos.Count; i++)
            {
                Footer = listaNodos.Item(i);

                string CurrentFooterNode = Footer.SelectSingleNode("Note").InnerText;
                Label1.Text = Label1.Text + CurrentFooterNode + "<br/>";
            }
            #endregion

            #endregion
        }
    protected void btnOk_Click(object sender, EventArgs e)
    {
        btnSuggest.Visible = true;
        int[] r  = new int[5]; //用于存放学习建议
        int[] j  = new int[4];
        int[] b  = new int[3];
        int[] rr = new int[6];  //用于存放错题的学习建议,有1~5中类型,数字长度选6
        //int []jj = new int[6];
        //int []bb = new int[6];
        btnOk.Enabled   = false;
        btnSave.Enabled = false;
        correct         = TestHighManager.JudgingRadio(rdolistS1, r1, lblS1A, btnS1E);
        if (correct == false)
        {
            r[0] = r1.suggestion;
            WrongRadioManager.addRadioToWrongTotal(Session["stuId"].ToString(), r1.Id, "High", "WrongRadio");
        }
        correct = TestHighManager.JudgingRadio(rdolistS2, r2, lblS2A, btnS2E);
        if (correct == false)
        {
            r[1] = r2.suggestion;
            WrongRadioManager.addRadioToWrongTotal(Session["stuId"].ToString(), r2.Id, "High", "WrongRadio");
        }
        correct = TestHighManager.JudgingRadio(rdolistS3, r3, lblS3A, btnS3E);
        if (correct == false)
        {
            r[2] = r3.suggestion;
            WrongRadioManager.addRadioToWrongTotal(Session["stuId"].ToString(), r3.Id, "High", "WrongRadio");
        }
        correct = TestHighManager.JudgingRadio(rdolistS4, r4, lblS4A, btnS4E);
        if (correct == false)
        {
            r[3] = r4.suggestion;
            WrongRadioManager.addRadioToWrongTotal(Session["stuId"].ToString(), r4.Id, "High", "WrongRadio");
        }
        correct = TestHighManager.JudgingRadio(rdolistS5, r5, lblS5A, btnS5E);
        if (correct == false)
        {
            r[4] = r5.suggestion;
            WrongRadioManager.addRadioToWrongTotal(Session["stuId"].ToString(), r5.Id, "High", "WrongRadio");
        }
        correct = TestHighManager.JudgingJudge(rdolistJ1, j1, lblJ1A, btnJ1E);
        if (correct == false)
        {
            j[0] = j1.suggestion;
            WrongRadioManager.addRadioToWrongTotal(Session["stuId"].ToString(), j1.Id, "High", "WrongJudge");
        }
        correct = TestHighManager.JudgingJudge(rdolistJ2, j2, lblJ2A, btnJ2E);
        if (correct == false)
        {
            j[1] = j2.suggestion;
            WrongRadioManager.addRadioToWrongTotal(Session["stuId"].ToString(), j2.Id, "High", "WrongJudge");
        }
        correct = TestHighManager.JudgingJudge(rdolistJ3, j3, lblJ3A, btnJ3E);
        if (correct == false)
        {
            j[2] = j3.suggestion;
            WrongRadioManager.addRadioToWrongTotal(Session["stuId"].ToString(), j3.Id, "High", "WrongJudge");
        }
        correct = TestHighManager.JudgingJudge(rdolistJ4, j4, lblJ4A, btnJ4E);
        if (correct == false)
        {
            j[3] = j4.suggestion;
            WrongRadioManager.addRadioToWrongTotal(Session["stuId"].ToString(), j4.Id, "High", "WrongJudge");
        }
        correct = TestHighManager.JudgingBlank(b1, txtB11, lblB11A, btnB11E);
        if (correct == false)
        {
            b[0] = b1.suggestion;
            WrongRadioManager.addRadioToWrongTotal(Session["stuId"].ToString(), b1.Id, "High", "WrongBlank");
        }
        correct = TestHighManager.JudgingBlank(b2, txtB21, lblB21A, btnB21E);
        if (correct == false)
        {
            b[1] = b2.suggestion;
            WrongRadioManager.addRadioToWrongTotal(Session["stuId"].ToString(), b2.Id, "High", "WrongBlank");
        }
        correct = TestHighManager.JudgingBlank(b3, txtB21, lblB31A, btnB31E);
        if (correct == false)
        {
            b[2] = b3.suggestion;
            WrongRadioManager.addRadioToWrongTotal(Session["stuId"].ToString(), b3.Id, "High", "WrongBlank");
        }
        correct = TestHighManager.JudgingDesignRadio(rdolistD1S1, rdolistD1S2, d1, lblD1S1A, lblD1S2A);
        if (correct == false)
        {
            WrongRadioManager.addRadioToWrongTotal(Session["stuId"].ToString(), d1.Id, "High", "WrongDesign");
        }

        //判断单选错题的学习建议是否重复,同时生成XML文件
        System.Xml.XmlTextWriter xmlWriter = new XmlTextWriter(Server.MapPath("./XML/" + Session["stuId"].ToString() + ".xml"), System.Text.Encoding.UTF8);
        xmlWriter.Formatting = Formatting.Indented;
        xmlWriter.WriteStartDocument();
        xmlWriter.WriteStartElement("学习建议");
        for (int i = 0; i <= 4; i++)
        {
            if (r[i] != 0)
            {
                rr[r[i]] = r[i];   //如果r[i]不为0,表明为错题,就把建议编号放到相应的rr数组中
            }
        }

        //判断判断错题的学习建议是否重复
        for (int i = 0; i <= 3; i++)
        {
            if (j[i] != 0)
            {
                rr[j[i]] = j[i];   //如果j[i]不为0,表明为错题,就把建议编号放到相应的rr数组中
            }
        }

        //判断填空错题的学习建议是否重复
        for (int i = 0; i <= 2; i++)
        {
            if (b[i] != 0)
            {
                rr[b[i]] = b[i];   //如果b[i]不为0,表明为错题,就把建议编号放到相应的rr数组中
            }
        }
        for (int i = 0; i <= 5; i++)
        {
            if (rr[i] != 0)
            {
                //Msg = Msg + rr[i].ToString() + ",";
                //写入XML文件
                xmlWriter.WriteStartElement("错题");
                xmlWriter.WriteAttributeString("类型", rr[i].ToString());
                xmlWriter.WriteEndElement();
            }
        }
        //写文档结束,调用WriteEndDocument方法
        xmlWriter.WriteEndDocument();
        //关闭textWriter
        xmlWriter.Close();

        string stuId = Session["stuId"].ToString();

        bool scoreJudge = TestHighManager.Score(TestHighManager.radioScore(r1, r2, r3, r4, r5, rdolistS1, rdolistS2, rdolistS3, rdolistS4, rdolistS5), TestHighManager.judgeScore(j1, j2, j3, j4, rdolistJ1, rdolistJ2, rdolistJ3, rdolistJ4),
                                                TestHighManager.blankScore(b1, b2, b3, txtB11, txtB21, txtB31), TestHighManager.designScore(d1, rdolistD1S1, rdolistD1S2));

        if (scoreJudge == true)
        {
            //实现设计题上传
            Boolean fileOK = false;
            // 指定路径
            String path = Server.MapPath("~/");
            // 文件上传控件中如果已经包含文件
            if (FUDesignHigh.HasFile)
            {
                // 得到文件的后缀
                String fileExtension =
                    System.IO.Path.GetExtension(FUDesignHigh.FileName).ToLower();
                // 允许的文件后缀
                String[] allowedExtensions = { ".cs" };
                // 看包含的文件是否是被允许的文件后缀
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        // 如果是,标志位置为真
                        fileOK = true;
                    }
                }
            }

            if (fileOK)
            {
                try
                {
                    // 文件另存在服务器指定目录下

                    FUDesignHigh.PostedFile.SaveAs(Server.MapPath("./DesignWorks/high/") + FUDesignHigh.FileName);
                    lbText.Text = "文件上传成功!";
                    path        = "~/DesignWorks/high/" + FUDesignHigh.FileName;
                }
                catch (Exception ex)
                {
                    lbText.Text = "文件上传失败!";
                }
            }
            else
            {
                lbText.Text = "注意:只能上传*.cs文件,并以“学号.cs”命名!";
            }
            //将上传地址写入数据库

            DateTime createTime = DateTime.Now;
            string   fileName   = FUDesignHigh.FileName;
            int      n          = TestHighManager.AddDesignUpload(stuId, learningLevel, createTime, path, fileName);
        }
        //将分数写入ClassUnit表中

        TestHighManager.UpdateStudyingScore(stuId, learningLevel, TestHighManager.radioScore(r1, r2, r3, r4, r5, rdolistS1, rdolistS2, rdolistS3, rdolistS4, rdolistS5)
                                            + TestHighManager.judgeScore(j1, j2, j3, j4, rdolistJ1, rdolistJ2, rdolistJ3, rdolistJ4) + TestHighManager.blankScore(b1, b2, b3, txtB11, txtB21, txtB31)
                                            + TestHighManager.designScore(d1, rdolistD1S1, rdolistD1S2));


        string str = null;

        str = TestHighManager.ShowScoreString(TestHighManager.radioScore(r1, r2, r3, r4, r5, rdolistS1, rdolistS2, rdolistS3, rdolistS4, rdolistS5), TestHighManager.judgeScore(j1, j2, j3, j4, rdolistJ1, rdolistJ2, rdolistJ3, rdolistJ4), TestHighManager.blankScore(b1, b2, b3, txtB11, txtB21, txtB31), TestHighManager.designScore(d1, rdolistD1S1, rdolistD1S2), scoreJudge);
        //Response.Write(string.Format("<script type = 'text/javascript'> alert('{0}'); </script>", str));
        RegisterClientScriptBlock("", string.Format("<script type = 'text/javascript'> alert('{0}'); </script>", str));
    }
示例#45
0
        private void button_Excel_Click(object sender, EventArgs e)
        {
            if (path != null && extension.Equals(".xls"))
            {
                try
                {
                    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                    saveFileDialog1.Filter           = "xml files (*.xml)|*.xml";
                    saveFileDialog1.FilterIndex      = 2;
                    saveFileDialog1.RestoreDirectory = true;
                    ExcelHandler.ReadExcel(path);

                    string pathfile = System.IO.Directory.GetCurrentDirectory() + "\\XLMS";

                    if (Directory.Exists(pathfile))
                    {
                        MessageBox.Show("Directoria já existe", "Directoria", MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                    else
                    {
                        // Tenta criar a directoria
                        Directory.CreateDirectory(pathfile);
                    }
                    saveFileDialog1.InitialDirectory = pathfile;

                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        XmlTextWriter writer =
                            new XmlTextWriter(saveFileDialog1.FileName,
                                              System.Text.Encoding.UTF8);

                        pathrestaurante = saveFileDialog1.FileName;

                        writer.WriteStartDocument(true);
                        writer.Formatting  = Formatting.Indented;
                        writer.Indentation = 2;
                        writer.WriteStartElement("restaurantes");

                        for (int i = 0; i <= ExcelHandler.Restaurante.Count - 1; i++)
                        {
                            createNode(ExcelHandler.Restaurante[i], ExcelHandler.Item[i], ExcelHandler.Quantidade[i],
                                       ExcelHandler.Calorias[i], writer);
                        }
                        writer.WriteEndElement();
                        writer.WriteEndDocument();
                        writer.Close();
                        MessageBox.Show("O ficheiro XML foi criado com sucesso ! ");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Erro, " + ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Essa extensão não é suportada neste botão", "Erro", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }
示例#46
0
        private byte[] BuildRatesRequestMessage()
        {
            Encoding utf8   = new UTF8Encoding(false);
            var      writer = new XmlTextWriter(new MemoryStream(2000), utf8);

            writer.WriteStartDocument();
            writer.WriteStartElement("AccessRequest");
            writer.WriteAttributeString("lang", "en-US");
            writer.WriteElementString("AccessLicenseNumber", _licenseNumber);
            writer.WriteElementString("UserId", _userId);
            writer.WriteElementString("Password", _password);
            writer.WriteEndDocument();
            writer.WriteStartDocument();
            writer.WriteStartElement("RatingServiceSelectionRequest");
            writer.WriteAttributeString("lang", "en-US");
            writer.WriteStartElement("Request");
            writer.WriteStartElement("TransactionReference");
            writer.WriteElementString("CustomerContext", "Rating and Service");
            writer.WriteElementString("XpciVersion", "1.0");
            writer.WriteEndElement(); // </TransactionReference>
            writer.WriteElementString("RequestAction", "Rate");
            writer.WriteElementString("RequestOption", string.IsNullOrWhiteSpace(_serviceDescription) ? "Shop" : _serviceDescription);
            writer.WriteEndElement(); // </Request>
            writer.WriteStartElement("PickupType");
            writer.WriteElementString("Code", "03");
            writer.WriteEndElement();                                                                   // </PickupType>
            writer.WriteStartElement("CustomerClassification");
            writer.WriteElementString("Code", string.IsNullOrWhiteSpace(_shipperNumber) ? "01" : "00"); // 00 gets shipper number rates, 01 for daily rates
            writer.WriteEndElement();                                                                   // </CustomerClassification
            writer.WriteStartElement("Shipment");
            writer.WriteStartElement("Shipper");
            if (!string.IsNullOrWhiteSpace(_shipperNumber))
            {
                writer.WriteElementString("ShipperNumber", _shipperNumber);
            }
            writer.WriteStartElement("Address");
            writer.WriteElementString("PostalCode", Shipment.OriginAddress.PostalCode);
            writer.WriteEndElement(); // </Address>
            writer.WriteEndElement(); // </Shipper>
            writer.WriteStartElement("ShipTo");
            writer.WriteStartElement("Address");
            if (!string.IsNullOrWhiteSpace(Shipment.DestinationAddress.State))
            {
                writer.WriteElementString("StateProvinceCode", Shipment.DestinationAddress.State);
            }
            if (Shipment.DestinationAddress.IsUnitedStatesAddress() || Shipment.DestinationAddress.IsCanadaAddress())
            {
                writer.WriteElementString("PostalCode", Shipment.DestinationAddress.PostalCode);
            }
            writer.WriteElementString("CountryCode", Shipment.DestinationAddress.CountryCode);
            writer.WriteEndElement(); // </Address>
            writer.WriteEndElement(); // </ShipTo>
            if (!string.IsNullOrWhiteSpace(_serviceDescription))
            {
                writer.WriteStartElement("Service");
                writer.WriteElementString("Code", _serviceDescription.ToUpsShipCode());
                writer.WriteEndElement(); //</Service>
            }
            if (_useNegotiatedRates)
            {
                writer.WriteStartElement("RateInformation");
                writer.WriteElementString("NegotiatedRatesIndicator", "");
                writer.WriteEndElement();// </RateInformation>
            }
            for (var i = 0; i < Shipment.Packages.Count; i++)
            {
                writer.WriteStartElement("Package");
                writer.WriteStartElement("PackagingType");
                writer.WriteElementString("Code", "02");
                writer.WriteEndElement(); //</PackagingType>
                writer.WriteStartElement("PackageWeight");
                writer.WriteElementString("Weight", Shipment.Packages[i].RoundedWeight.ToString());
                writer.WriteEndElement(); // </PackageWeight>
                writer.WriteStartElement("Dimensions");
                writer.WriteElementString("Length", Shipment.Packages[i].RoundedLength.ToString());
                writer.WriteElementString("Width", Shipment.Packages[i].RoundedWidth.ToString());
                writer.WriteElementString("Height", Shipment.Packages[i].RoundedHeight.ToString());
                writer.WriteEndElement(); // </Dimensions>
                writer.WriteStartElement("PackageServiceOptions");
                writer.WriteStartElement("InsuredValue");
                writer.WriteElementString("CurrencyCode", "USD");
                writer.WriteElementString("MonetaryValue", Shipment.Packages[i].InsuredValue.ToString());
                writer.WriteEndElement(); // </InsuredValue>
                writer.WriteEndElement(); // </PackageServiceOptions>
                writer.WriteEndElement(); // </Package>
            }
            writer.WriteEndDocument();
            writer.Flush();
            var buffer = new byte[writer.BaseStream.Length];

            writer.BaseStream.Position = 0;
            writer.BaseStream.Read(buffer, 0, buffer.Length);
            writer.Close();

            return(buffer);
        }
示例#47
0
        /// <summary>
        /// Update the internal XML of the Viewer window.
        /// </summary>
        private void AsyncRefresh(object sender, DoWorkEventArgs e)
        {
            _blnQueueRefresherRun = false;
            // Write the Character information to a MemoryStream so we don't need to create any files.
            using (MemoryStream objStream = new MemoryStream())
            {
                using (XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.UTF8))
                {
                    // Begin the document.
                    objWriter.WriteStartDocument();

                    // </characters>
                    objWriter.WriteStartElement("characters");

                    foreach (Character objCharacter in _lstCharacters)
                    {
                        if (_workerRefresher.CancellationPending)
                        {
                            e.Cancel = true;
                            return;
                        }
#if DEBUG
                        objCharacter.PrintToStream(objStream, objWriter, _objPrintCulture, _strPrintLanguage);
#else
                        objCharacter.PrintToStream(objWriter, _objPrintCulture, _strPrintLanguage);
#endif
                    }

                    // </characters>
                    objWriter.WriteEndElement();
                    if (_workerRefresher.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    // Finish the document and flush the Writer and Stream.
                    objWriter.WriteEndDocument();
                    objWriter.Flush();

                    objStream.Position = 0;

                    // Read the stream.
                    XmlDocument objCharacterXml = new XmlDocument
                    {
                        XmlResolver = null
                    };
                    // Read it back in as an XmlDocument.
                    using (StreamReader objReader = new StreamReader(objStream, Encoding.UTF8, true))
                    {
                        using (XmlReader objXmlReader = XmlReader.Create(objReader, new XmlReaderSettings {
                            XmlResolver = null
                        }))
                        {
                            if (_workerRefresher.CancellationPending)
                            {
                                e.Cancel = true;
                                return;
                            }

                            // Put the stream into an XmlDocument and send it off to the Viewer.
                            objCharacterXml.Load(objXmlReader);
                        }
                    }

                    if (_workerRefresher.CancellationPending)
                    {
                        e.Cancel = true;
                    }
                    else
                    {
                        _objCharacterXml = objCharacterXml;
                    }
                }
            }
        }
示例#48
0
        private void read_configuration()
        {
            //XmlDocument _iniFile = new XmlDocument();
            string _fileName = "ini.xml";

            try
            {
                XmlReaderSettings _settings = new XmlReaderSettings();
                _settings.IgnoreWhitespace = true;
                XmlReader _reader = XmlReader.Create(inputUri: _fileName, _settings);

                List <XmlNodeType> _nodes     = new List <XmlNodeType>();
                List <string>      _nodeNames = new List <string>();

                while (_reader.Read())
                {
                    _nodes.Add(_reader.NodeType);
                    _nodeNames.Add(_reader.Name);

                    if (_reader.IsStartElement("COM") && !_reader.IsEmptyElement)
                    {
                        try
                        {
                            string _com = _reader.ReadElementContentAsString();
                            cmbPort.SelectedValue = _com;
                        }
                        catch
                        {
                        }
                    }
                    if (_reader.IsStartElement("Baud") && !_reader.IsEmptyElement)
                    {
                        try
                        {
                            string _baud = _reader.ReadElementContentAsString();
                            cmbBaud.SelectedValue = _baud;
                        }
                        catch
                        {
                        }
                    }
                }
                _reader.Close();
            }
            catch (Exception e)
            {
                //XmlWriter _writer = XmlWriter.Create(_fileName);
                //_writer.

                XmlTextWriter _writer = new XmlTextWriter(_fileName, Encoding.GetEncoding(1251));
                _writer.Formatting = Formatting.Indented;
                _writer.WriteStartDocument();

                _writer.WriteStartElement("Data");

                _writer.WriteStartElement("COM");
                _writer.WriteString(cmbPort.SelectedItem.ToString());
                _writer.WriteEndElement();

                _writer.WriteStartElement("Baud");
                _writer.WriteString(cmbBaud.Text);
                _writer.WriteEndElement();

                _writer.WriteEndElement();

                _writer.WriteEndDocument();
                _writer.Flush();
                _writer.Close();
            }
        }
示例#49
0
        /// <summary>
        /// パラメータファイル保存
        /// </summary>
        /// <param name="filePath">パラメータファイルパス</param>
        public void save(string filePath)
        {
            XmlTextWriter writer = new XmlTextWriter(filePath, Encoding.UTF8);

            writer.Formatting = Formatting.Indented;

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

            writer.WriteStartElement("FormatVersion"); writer.WriteValue(_CURRENT_PARAMETER_FORMAT_VERSION); writer.WriteEndElement();

            writer.WriteStartElement("TotalOptions");
            writer.WriteStartElement("SizeProportionX"); writer.WriteValue(_fileData.SizeProportionX); writer.WriteEndElement();
            writer.WriteStartElement("SizeProportionY"); writer.WriteValue(_fileData.SizeProportionY); writer.WriteEndElement();
            writer.WriteStartElement("SizeProportionZ"); writer.WriteValue(_fileData.SizeProportionZ); writer.WriteEndElement();
            writer.WriteStartElement("CenterX"); writer.WriteValue(_fileData.CenterX); writer.WriteEndElement();
            writer.WriteStartElement("CenterY"); writer.WriteValue(_fileData.CenterY); writer.WriteEndElement();
            writer.WriteStartElement("CenterZ"); writer.WriteValue(_fileData.CenterZ); writer.WriteEndElement();
            writer.WriteStartElement("Mirror"); writer.WriteValue(_fileData.Mirror); writer.WriteEndElement();
            writer.WriteEndElement();

            writer.WriteStartElement("CameraOptions");
            writer.WriteStartElement("KinectElevationAngle"); writer.WriteValue(_fileData.KinectElevationAngle); writer.WriteEndElement();
            writer.WriteStartElement("ColorDrawEnable"); writer.WriteValue(_fileData.ColorDrawEnable); writer.WriteEndElement();
            writer.WriteStartElement("DepthDrawEnable"); writer.WriteValue(_fileData.DepthDrawEnable); writer.WriteEndElement();
            writer.WriteStartElement("SkeletonDrawEnable"); writer.WriteValue(_fileData.SkeletonDrawEnable); writer.WriteEndElement();
            writer.WriteEndElement();

            writer.WriteStartElement("DetailOptions");
            writer.WriteStartElement("HeadName"); writer.WriteValue(_fileData.HeadName); writer.WriteEndElement();
            writer.WriteStartElement("ShoulderCenterName"); writer.WriteValue(_fileData.ShoulderCenterName); writer.WriteEndElement();
            writer.WriteStartElement("ShoulderRightName"); writer.WriteValue(_fileData.ShoulderRightName); writer.WriteEndElement();
            writer.WriteStartElement("ElbowRightName"); writer.WriteValue(_fileData.ElbowRightName); writer.WriteEndElement();
            writer.WriteStartElement("WristRightName"); writer.WriteValue(_fileData.WristRightName); writer.WriteEndElement();
            writer.WriteStartElement("HandRightName"); writer.WriteValue(_fileData.HandRightName); writer.WriteEndElement();
            writer.WriteStartElement("ShoulderLeftName"); writer.WriteValue(_fileData.ShoulderLeftName); writer.WriteEndElement();
            writer.WriteStartElement("ElbowLeftName"); writer.WriteValue(_fileData.ElbowLeftName); writer.WriteEndElement();
            writer.WriteStartElement("WristLeftName"); writer.WriteValue(_fileData.WristLeftName); writer.WriteEndElement();
            writer.WriteStartElement("HandLeftName"); writer.WriteValue(_fileData.HandLeftName); writer.WriteEndElement();
            writer.WriteStartElement("SpineName"); writer.WriteValue(_fileData.SpineName); writer.WriteEndElement();
            writer.WriteStartElement("HipCenterName"); writer.WriteValue(_fileData.HipCenterName); writer.WriteEndElement();
            writer.WriteStartElement("HipRightName"); writer.WriteValue(_fileData.HipRightName); writer.WriteEndElement();
            writer.WriteStartElement("KneeRightName"); writer.WriteValue(_fileData.KneeRightName); writer.WriteEndElement();
            writer.WriteStartElement("AnkleRightName"); writer.WriteValue(_fileData.AnkleRightName); writer.WriteEndElement();
            writer.WriteStartElement("FootRightName"); writer.WriteValue(_fileData.FootRightName); writer.WriteEndElement();
            writer.WriteStartElement("HipLeftName"); writer.WriteValue(_fileData.HipLeftName); writer.WriteEndElement();
            writer.WriteStartElement("KneeLeftName"); writer.WriteValue(_fileData.KneeLeftName); writer.WriteEndElement();
            writer.WriteStartElement("AnkleLeftName"); writer.WriteValue(_fileData.AnkleLeftName); writer.WriteEndElement();
            writer.WriteStartElement("FootLeftName"); writer.WriteValue(_fileData.FootLeftName); writer.WriteEndElement();

            writer.WriteStartElement("HeadEnable"); writer.WriteValue(_fileData.HeadEnable); writer.WriteEndElement();
            writer.WriteStartElement("ShoulderCenterEnable"); writer.WriteValue(_fileData.ShoulderCenterEnable); writer.WriteEndElement();
            writer.WriteStartElement("ShoulderRightEnable"); writer.WriteValue(_fileData.ShoulderRightEnable); writer.WriteEndElement();
            writer.WriteStartElement("ElbowRightEnable"); writer.WriteValue(_fileData.ElbowRightEnable); writer.WriteEndElement();
            writer.WriteStartElement("WristRightEnable"); writer.WriteValue(_fileData.WristRightEnable); writer.WriteEndElement();
            writer.WriteStartElement("HandRightEnable"); writer.WriteValue(_fileData.HandRightEnable); writer.WriteEndElement();
            writer.WriteStartElement("ShoulderLeftEnable"); writer.WriteValue(_fileData.ShoulderLeftEnable); writer.WriteEndElement();
            writer.WriteStartElement("ElbowLeftEnable"); writer.WriteValue(_fileData.ElbowLeftEnable); writer.WriteEndElement();
            writer.WriteStartElement("WristLeftEnable"); writer.WriteValue(_fileData.WristLeftEnable); writer.WriteEndElement();
            writer.WriteStartElement("HandLeftEnable"); writer.WriteValue(_fileData.HandLeftEnable); writer.WriteEndElement();
            writer.WriteStartElement("SpineEnable"); writer.WriteValue(_fileData.SpineEnable); writer.WriteEndElement();
            writer.WriteStartElement("HipCenterEnable"); writer.WriteValue(_fileData.HipCenterEnable); writer.WriteEndElement();
            writer.WriteStartElement("HipRightEnable"); writer.WriteValue(_fileData.HipRightEnable); writer.WriteEndElement();
            writer.WriteStartElement("KneeRightEnable"); writer.WriteValue(_fileData.KneeRightEnable); writer.WriteEndElement();
            writer.WriteStartElement("AnkleRightEnable"); writer.WriteValue(_fileData.AnkleRightEnable); writer.WriteEndElement();
            writer.WriteStartElement("FootRightEnable"); writer.WriteValue(_fileData.FootRightEnable); writer.WriteEndElement();
            writer.WriteStartElement("HipLeftEnable"); writer.WriteValue(_fileData.HipLeftEnable); writer.WriteEndElement();
            writer.WriteStartElement("KneeLeftEnable"); writer.WriteValue(_fileData.KneeLeftEnable); writer.WriteEndElement();
            writer.WriteStartElement("AnkleLeftEnable"); writer.WriteValue(_fileData.AnkleLeftEnable); writer.WriteEndElement();
            writer.WriteStartElement("FootLeftEnable"); writer.WriteValue(_fileData.FootLeftEnable); writer.WriteEndElement();
            writer.WriteEndElement();

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

            writer.Flush();
            writer.Close();
        }
示例#50
0
 public void Terminate()
 {
     xtwriter.WriteEndDocument();
     xtwriter.Close();
 }
示例#51
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);
        }
示例#52
0
        /// <summary>
        /// Calculate percentage of well written file names
        /// according to the coding standard rules.
        /// </summary>
        /// <param name="resultDirXML">Output directory</param>
        private static void CalculatePercentage(string resultDirXML)
        {
            string currDir        = Directory.GetCurrentDirectory();
            string dictionaryFile = currDir + "\\" + "FileNamingDictionary.txt";
            string dirToScanFile  = currDir + "\\" + "DirToScan.txt";
            string reportFile     = resultDirXML + "\\" + "FileNamingReport.xml";
            bool   matchDict      = false;

            try
            {
                // Read file related t the list of directory to scan for file naming convention
                StreamReader srDirToScan = new StreamReader(dirToScanFile);
                string       dir         = srDirToScan.ReadLine();
                while (!srDirToScan.EndOfStream)
                {
                    dir += " ";
                    dir += srDirToScan.ReadLine();
                }
                string[] dirList = dir.Split(' ');
                srDirToScan.Close();

                // Read dictionary file
                StreamReader srDic = new StreamReader(dictionaryFile);
                string       dic   = srDic.ReadLine();
                while (!srDic.EndOfStream)
                {
                    dic += " ";
                    dic += srDic.ReadLine();
                }
                string[] dictionaryAndInherit = dic.Split(' ');
                srDic.Close();
                String sep          = "<--ExternalInherit-->";
                int    separatorIdx = Array.IndexOf(dictionaryAndInherit, sep);
                if (separatorIdx > 0)
                {
                    dictionary      = (string[])Array.CreateInstance(typeof(String), separatorIdx);
                    externalInherit = (string[])Array.CreateInstance(typeof(String), dictionaryAndInherit.Length - separatorIdx - 1);
                    Array.Copy(dictionaryAndInherit, dictionary, separatorIdx);
                    Array.Copy(dictionaryAndInherit, separatorIdx + 1, externalInherit, 0, externalInherit.Length);
                }
                else if (separatorIdx == 0)
                {
                    throw new Exception("No dictionary elements are presents.");
                }
                else
                {
                    // no default inherited classes are defined!!
                    dictionary = (string[])dictionaryAndInherit.Clone();
                }

                QueryPerfCounter myTimer = new QueryPerfCounter();
                myTimer.Start();

                // Write report file
                XmlTextWriter xwriter = new XmlTextWriter(reportFile, Encoding.UTF8);
                xwriter.WriteStartDocument(true);
                xwriter.WriteStartElement("root");
                xwriter.WriteElementString("ReportDate", DateTime.Now.ToString());

                string nodeDir;
                foreach (string d in dirList)
                {
                    nodeDir = d.Substring(d.LastIndexOf('\\') + 1);
                    xwriter.WriteStartElement("Directory");
                    xwriter.WriteAttributeString("DirName", nodeDir);
                    string   absoluteDir     = currDir + "\\" + d;
                    string[] filesHeader     = Directory.GetFiles(absoluteDir, "*.h");
                    string[] filesHeader_in  = Directory.GetFiles(absoluteDir, "*.h.in");
                    string[] filesImplem_cpp = Directory.GetFiles(absoluteDir, "*.cpp");
                    string[] filesImplem_cxx = Directory.GetFiles(absoluteDir, "*.cxx");
                    string[] files           = (string[])Array.CreateInstance(typeof(String), filesHeader.Length + filesHeader_in.Length + filesImplem_cpp.Length + filesImplem_cxx.Length);
                    filesHeader.CopyTo(files, 0);
                    filesHeader_in.CopyTo(files, filesHeader.Length);
                    filesImplem_cpp.CopyTo(files, filesHeader.Length + filesHeader_in.Length);
                    filesImplem_cxx.CopyTo(files, filesHeader.Length + filesHeader_in.Length + filesImplem_cpp.Length);
                    Array.Sort(files);
                    int    totalFiles       = files.Length;
                    int    wellWrittenFiles = 0;
                    string baseName;
                    string wrongFiles = "";
                    string goodFiles  = "";
                    foreach (string f in files)
                    {
                        bool wrong = true;
                        baseName = f.Substring(f.LastIndexOf('\\') + 1);
                        foreach (string k in dictionary)
                        {
                            string name = baseName.Substring(0, baseName.LastIndexOf('.'));
                            if (name.Equals(k))
                            {
                                // This is a base class; don't check inheritance.
                                wrong = false;
                                wellWrittenFiles++;
                                break;
                            }
                            matchDict = baseName.Contains(k);
                            if (matchDict)
                            {
                                // classes inherited from base classes;
                                // check inheritance according to the second rule of the naming convention:
                                // e.g. mafView -> mafViewVTK
                                if (CheckInheritance(f, k))
                                {
                                    wrong = false;
                                    wellWrittenFiles++;
                                    goodFiles += " " + baseName;
                                }
                                break;
                            }
                        }
                        if (wrong)
                        {
                            wrongFiles += " " + baseName;
                        }
                    }
                    double percentage = (wellWrittenFiles / Convert.ToDouble(totalFiles));
                    xwriter.WriteAttributeString("Percentage", percentage.ToString("P"));
                    string[] wfilesList = wrongFiles.Split(' ');
                    foreach (string f in wfilesList)
                    {
                        if (f == "")
                        {
                            continue;
                        }
                        xwriter.WriteStartElement("WrongFiles");
                        xwriter.WriteAttributeString("FileName", f);
                        xwriter.WriteEndElement();
                    }
                    string[] gfilesList = goodFiles.Split(' ');
                    foreach (string f in gfilesList)
                    {
                        if (f == "")
                        {
                            continue;
                        }
                        xwriter.WriteStartElement("GoodFiles");
                        xwriter.WriteAttributeString("FileName", f);
                        xwriter.WriteEndElement();
                    }

                    //End the nodeDir element.
                    xwriter.WriteEndElement();
                    Array.Clear(files, 0, files.Length);
                }
                myTimer.Stop();

                // Calculate time per iteration in seconds
                myTimer.SetMultiplier(1.0);
                double result = myTimer.Duration();
                xwriter.WriteElementString("ComputationTime", result.ToString("F") + " s");

                //End the "root" element.
                xwriter.WriteEndElement();

                //End the document
                xwriter.WriteEndDocument();
                xwriter.Close();

                // Load the style sheet.
                XslCompiledTransform xslt = new XslCompiledTransform();
                xslt.Load("resultTransform.xslt");

                // Execute the transform and output the results to a file.
                string reportHTMLFile = resultDirXML + "\\" + "..\\HTML\\FileNamingReport.html";
                xslt.Transform(reportFile, reportHTMLFile);

                XslCompiledTransform xsltWrongFiles = new XslCompiledTransform();
                xsltWrongFiles.Load("wrongFileList.xslt");

                string           dirResultFile;
                XsltArgumentList xslArg = new XsltArgumentList();
                foreach (string d in dirList)
                {
                    nodeDir       = d.Substring(d.LastIndexOf('\\') + 1);
                    dirResultFile = resultDirXML + "\\" + "..\\HTML\\" + nodeDir + ".html";
                    xslArg.AddParam("dir", "", nodeDir);
                    StreamWriter sw = new StreamWriter(dirResultFile);
                    xsltWrongFiles.Transform(reportFile, xslArg, sw);
                    sw.Close();
                    xslArg.Clear();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
示例#53
0
        /// <summary>
        /// The page_ load.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
        {
            // Put user code to initialize the page here
            if (!(this.Get <YafBoardSettings>().ShowRSSLink || this.Get <YafBoardSettings>().ShowAtomLink))
            {
                YafBuildLink.RedirectInfoPage(InfoMessage.AccessDenied);
            }

            // Atom feed as variable
            var atomFeedByVar = this.Request.QueryString.GetFirstOrDefault("ft")
                                == YafSyndicationFormats.Atom.ToInt().ToString();

            YafSyndicationFeed feed = null;

            // var syndicationItems = new List<SyndicationItem>();
            var lastPostIcon = string.Empty;
            var lastPostName = this.GetText("DEFAULT", "GO_LAST_POST");

            YafRssFeeds feedType;

            try
            {
                feedType = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("pg").ToEnum <YafRssFeeds>(true);
            }
            catch
            {
                // default to Forum Feed.
                feedType = YafRssFeeds.Forum;
            }

            switch (feedType)
            {
            // Latest posts feed
            case YafRssFeeds.LatestPosts:
                if (
                    !(this.Get <YafBoardSettings>().ShowActiveDiscussions &&
                      this.Get <IPermissions>().Check(this.Get <YafBoardSettings>().PostLatestFeedAccess)))
                {
                    YafBuildLink.AccessDenied();
                }

                this.GetPostLatestFeed(ref feed, feedType, atomFeedByVar, lastPostIcon, lastPostName);
                break;

            // Latest Announcements feed
            case YafRssFeeds.LatestAnnouncements:
                if (!this.Get <IPermissions>().Check(this.Get <YafBoardSettings>().ForumFeedAccess))
                {
                    YafBuildLink.AccessDenied();
                }

                this.GetLatestAnnouncementsFeed(ref feed, feedType, atomFeedByVar);
                break;

            // Posts Feed
            case YafRssFeeds.Posts:
                if (
                    !(this.PageContext.ForumReadAccess &&
                      this.Get <IPermissions>().Check(this.Get <YafBoardSettings>().PostsFeedAccess)))
                {
                    YafBuildLink.AccessDenied();
                }

                if (this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("t") != null)
                {
                    int topicId;
                    if (int.TryParse(this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("t"), out topicId))
                    {
                        this.GetPostsFeed(ref feed, feedType, atomFeedByVar, topicId);
                    }
                }

                break;

            // Forum Feed
            case YafRssFeeds.Forum:
                if (!this.Get <IPermissions>().Check(this.Get <YafBoardSettings>().ForumFeedAccess))
                {
                    YafBuildLink.AccessDenied();
                }

                int?categoryId = null;

                if (this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("c") != null)
                {
                    int icategoryId;
                    if (int.TryParse(
                            this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("c"), out icategoryId))
                    {
                        categoryId = icategoryId;
                    }
                }

                this.GetForumFeed(ref feed, feedType, atomFeedByVar, categoryId);
                break;

            // Topics Feed
            case YafRssFeeds.Topics:
                if (
                    !(this.PageContext.ForumReadAccess &&
                      this.Get <IPermissions>().Check(this.Get <YafBoardSettings>().TopicsFeedAccess)))
                {
                    YafBuildLink.AccessDenied();
                }

                if (this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("f") != null)
                {
                    int forumId;
                    if (int.TryParse(this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("f"), out forumId))
                    {
                        this.GetTopicsFeed(ref feed, feedType, atomFeedByVar, lastPostIcon, lastPostName, forumId);
                    }
                }

                break;

            // Active Topics
            case YafRssFeeds.Active:
                if (!this.Get <IPermissions>().Check(this.Get <YafBoardSettings>().ActiveTopicFeedAccess))
                {
                    YafBuildLink.AccessDenied();
                }

                int    categoryActiveIntId;
                object categoryActiveId = null;
                if (this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("f") != null
                    &&
                    int.TryParse(
                        this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("f"), out categoryActiveIntId))
                {
                    categoryActiveId = categoryActiveIntId;
                }

                this.GetActiveFeed(ref feed, feedType, atomFeedByVar, lastPostIcon, lastPostName, categoryActiveId);

                break;

            case YafRssFeeds.Favorite:
                if (!this.Get <IPermissions>().Check(this.Get <YafBoardSettings>().FavoriteTopicFeedAccess))
                {
                    YafBuildLink.AccessDenied();
                }

                int    categoryFavIntId;
                object categoryFavId = null;
                if (this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("f") != null
                    &&
                    int.TryParse(
                        this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("f"), out categoryFavIntId))
                {
                    categoryFavId = categoryFavIntId;
                }

                this.GetFavoriteFeed(ref feed, feedType, atomFeedByVar, lastPostIcon, lastPostName, categoryFavId);
                break;

            default:
                YafBuildLink.AccessDenied();
                break;
            }

            // update the feed with the item list...
            // the list should be added after all other feed properties are set
            if (feed != null)
            {
                var writer = new XmlTextWriter(this.Response.OutputStream, Encoding.UTF8);
                writer.WriteStartDocument();

                // write the feed to the response writer);
                if (!atomFeedByVar)
                {
                    var rssFormatter = new Rss20FeedFormatter(feed);
                    rssFormatter.WriteTo(writer);
                    this.Response.ContentType = "application/rss+xml";
                }
                else
                {
                    var atomFormatter = new Atom10FeedFormatter(feed);
                    atomFormatter.WriteTo(writer);

                    this.Response.ContentType = "application/atom+xml";
                }

                writer.WriteEndDocument();
                writer.Close();

                this.Response.ContentEncoding = Encoding.UTF8;
                this.Response.Cache.SetCacheability(HttpCacheability.Public);

                this.Response.End();
            }
            else
            {
                YafBuildLink.RedirectInfoPage(InfoMessage.AccessDenied);
            }
        }
示例#54
0
        /// <summary>
        /// Runs the solutions to all problems
        /// </summary>
        public static void Main()
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(PathToXmlFile);
            XmlNode root = doc.DocumentElement ?? doc.CreateElement("root");

            // Problem 2: Write program that extracts all different artists which are found in the catalog.xml.
            //  For each author you should print the number of albums in the catalogue.
            //  Use the DOM parser and a hash - table.
            PrintNumbersOfAlbumsForEachArtist(root);

            // Problem 3: Implement the previous using XPath.
            PrintArtistsNumberOfAlbumsUsingXPath(root);

            // Problem 4: Using the DOM parser write a program to delete from catalog.xml all albums having price > 20.
            DeleteAlbumsByPrice(root, 20.0);

            // Check that albums are deleted:
            PrintNumbersOfAlbumsForEachArtist(root);

            // Problem 5: Write a program, which using XmlReader extracts all song titles from catalog.xml.
            var songTitles = ExtractSongTitlesFromCatalogue(PathToXmlFile);

            Console.WriteLine("Song titles: " + string.Join(", ", (songTitles as List <string>).ToArray()));

            // Problem 6: Rewrite the same using XDocument and LINQ query.
            XDocument xDoc = XDocument.Load(PathToXmlFile);
            var       songTitlesUsingLinq = from songs in xDoc.Descendants("title") select songs.Value.Trim();

            Console.WriteLine("Song titles (using LINQ): " + string.Join(", ", songTitlesUsingLinq));

            // Problem 7: In a text file we are given the name, address and phone number of given person (each at a single line).
            // Write a program, which creates new XML document, which contains these data in structured XML format.
            CreateXmlPhonebook("../../phonebook.txt");

            // Problem 8: 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.
            CreateAlbumsXml(PathToXmlFile);

            // Problem 9: Write a program to traverse given directory and write to a XML file its contents together with all subdirectories and files.
            // Use tags < file > and < dir > with appropriate attributes.
            // For the generation of the XML document use the class XmlWriter.
            using (var writer = new XmlTextWriter("../../traverseWithXmlWriter.xml", Encoding.UTF8))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("DirectoriesRoot");
                CreateFileSystemXmlTreeUsingXmlWriter("../../..", writer);
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
            }

            // Problem 10: Rewrite the last exercises using XDocument, XElement and XAttribute.
            var xDocument = new XDocument();

            xDocument.Add(CreateFileSystemXmlTree("../../../"));
            xDocument.Save("../../traverseWithXElement.xml");

            // Problem 11: Write a program, which extract from the file catalog.xml the prices for all albums, published 5 years ago or earlier.
            // Use XPath query.
            doc.Load(PathToXmlFile);
            root = doc.DocumentElement;

            // returns all (no albums in the catalogue are newer...)
            var oldAlbumsPrices = root.SelectNodes("album/price[../year/text() < 2010]");

            //// var oldAlbumsPrices = root.SelectNodes("album/price[../year/text() < 1980]"); // returns 2 albums' prices
            Console.WriteLine(new string('-', 50));
            Console.WriteLine("Prices of the albums, published before 2010: ");
            foreach (var price in oldAlbumsPrices)
            {
                Console.WriteLine((price as XmlElement).InnerXml.Trim());
            }

            // Problem 12: Rewrite the previous using LINQ query.
            Console.WriteLine(new string('-', 50));
            Console.WriteLine("Prices of the albums, published before 2010 (using LINQ): ");
            var oldAlbumsPricesUsingLinq = from album in xDoc.Descendants("album")
                                           where int.Parse(album.Element("year").Value) < 2010
                                           select album.Descendants("price").FirstOrDefault();

            foreach (var price in oldAlbumsPricesUsingLinq)
            {
                Console.WriteLine(price.Value.Trim());
            }

            // Problem 13: Create an XSL stylesheet, which transforms the file catalog.xml into HTML document,
            // formatted for viewing in a standard Web-browser.
            // Problem 14: Write a C# program to apply the XSLT stylesheet transformation on the file catalog.xml
            // using the class XslTransform.
            XslCompiledTransform catalogueXslt = new XslCompiledTransform();

            catalogueXslt.Load("../../catalogue.xslt");
            catalogueXslt.Transform(PathToXmlFile, "../../catalogue.html");

            // Problem 15:
            // *Read some tutorial about the XQuery language.
            // Implement the XML to HTML transformation with XQuery (instead of XSLT).
            // Download some open source XQuery library for .NET and execute the XQuery to transform the catalog.xml to HTML.
            XQueryNavigatorCollection col = new XQueryNavigatorCollection();

            // Add the XML document catalogue.xml to the collection using cat as the name to reference.
            col.AddNavigator("../../catalogue.xml", "cat");
            var expr = new XQueryExpression(
                "<html><body><head><title>Catalogue</title></head>" +
                "<h1>Catalogue generated using XQuery</h1>" +
                "{For $a IN document(\"cat\")/catalogue/album " +
                "RETURN <div><strong>Title:</strong> {$a/name/text()}<br />" +
                "<strong>Artist:</strong> {$a/artist/text()}<br />" +
                "<strong>Year:</strong> {$a/year/text()}<br />" +
                "<strong>Producer:</strong> {$a/producer/text()}<br />" +
                "<strong>Price:</strong> {$a/price/text()}<br />" +
                "<strong>Songs:</strong><ol>{For $s IN $a/songs/song RETURN <li>{$s/title/text()}</li>}</ol>" +
                "</div><hr />}</body></html>");
            StreamWriter    str = new StreamWriter("../../catalogueUsingXQuery.html");
            XQueryNavigator nav = expr.Execute(col);

            nav.ToXml(str);
            str.Close();

            // Problem 16:
            // Using Visual Studio generate an XSD schema for the file catalog.xml.
            // Write a C# program that takes an XML file and an XSD file (schema) and validates the XML file against the schema.
            // Test it with valid XML catalogs and invalid XML catalogs.
            string       xsdMarkup = File.ReadAllText("../../catalogue.xsd");
            XmlSchemaSet schemas   = new XmlSchemaSet();

            schemas.Add(string.Empty, XmlReader.Create(new StringReader(xsdMarkup)));
            XDocument valid   = XDocument.Load(PathToXmlFile);
            XDocument invalid = new XDocument(
                new XElement(
                    "Root",
                    new XElement("Child1", "content1"),
                    new XElement("Child2", "content2")));

            Console.WriteLine(new string('-', 50));
            Console.WriteLine("Validating valid document:");
            bool errors = false;

            valid.Validate(schemas, (o, e) =>
            {
                Console.WriteLine("{0}", e.Message);
                errors = true;
            });
            Console.WriteLine("Valid {0}", errors ? "did not validate" : "validated");
            Console.WriteLine();
            Console.WriteLine("Validating invalid document:");
            errors = false;
            invalid.Validate(schemas, (o, e) =>
            {
                Console.WriteLine("{0}", e.Message);
                errors = true;
            });
            Console.WriteLine("doc2 {0}", errors ? "did not validate" : "validated");
        }
示例#55
0
            public static void SaveAsXml(DockPanel dockPanel, Stream stream, Encoding encoding, bool upstream)
            {
                XmlTextWriter xmlOut = new XmlTextWriter(stream, encoding);

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

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

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

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

                if (!Win32Helper.IsRunningOnMono)
                {
                    xmlOut.WriteAttributeString("ActiveDocumentPane", dockPanel.Panes.IndexOf(dockPanel.ActiveDocumentPane).ToString(CultureInfo.InvariantCulture));
                    xmlOut.WriteAttributeString("ActivePane", dockPanel.Panes.IndexOf(dockPanel.ActivePane).ToString(CultureInfo.InvariantCulture));
                }

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

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

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

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

                // FloatWindows
                RectangleConverter rectConverter = new RectangleConverter();

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

                xmlOut.WriteEndElement();

                if (!upstream)
                {
                    xmlOut.WriteEndDocument();
                    xmlOut.Close();
                }
                else
                {
                    xmlOut.Flush();
                }
            }
示例#56
0
        public static void ConvertToXml(IEnumerable <ParserForUrl> urls, string path)
        {
            var writer = new XmlTextWriter(path, Encoding.UTF8);

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

            foreach (var url in urls)
            {
                WriteURL(url);
            }

            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            return;

            void WriteURL(ParserForUrl url)
            {
                writer.WriteStartElement("urlAddress");
                writer.WriteAttributeString("scheme", url.Scheme);
                WriteHost();
                WritePath();
                WriteParameters();
                writer.WriteEndElement();
                return;

                void WriteHost()
                {
                    writer.WriteStartElement("host");
                    writer.WriteAttributeString("name", url.Host);
                    writer.WriteEndElement();
                }

                void WritePath()
                {
                    if (url.Segments?.Length > 0)
                    {
                        writer.WriteStartElement("uri");
                        foreach (var segment in url.Segments)
                        {
                            writer.WriteElementString("segment", segment);
                        }

                        writer.WriteEndElement();
                    }
                }

                void WriteParameters()
                {
                    if (url.Parameters?.Length > 0)
                    {
                        writer.WriteStartElement("parameters");
                        foreach (var param in url.Parameters)
                        {
                            writer.WriteStartElement("parameter");
                            writer.WriteAttributeString("key", param.Key);
                            writer.WriteAttributeString("value", param.Value);
                            writer.WriteEndElement();
                        }

                        writer.WriteEndElement();
                    }
                }
            }
        }
        private string BuildRatesRequestMessage()
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var writer = new XmlTextWriter(memoryStream, Encoding.UTF8))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("AccessRequest");
                    writer.WriteAttributeString("lang", "en-US");
                    writer.WriteElementString("AccessLicenseNumber", _licenseNumber);
                    writer.WriteElementString("UserId", _userId);
                    writer.WriteElementString("Password", _password);
                    writer.WriteEndDocument();

                    writer.WriteStartDocument();
                    writer.WriteStartElement("RatingServiceSelectionRequest");
                    writer.WriteAttributeString("lang", "en-US");

                    writer.WriteStartElement("Request");
                    writer.WriteElementString("RequestAction", "Rate");
                    writer.WriteElementString("RequestOption", string.IsNullOrWhiteSpace(_serviceDescription) ? "Shop" : _serviceDescription);
                    writer.WriteElementString("SubVersion", "1801");
                    writer.WriteEndElement(); // </Request>

                    writer.WriteStartElement("PickupType");
                    writer.WriteElementString("Code", "03");
                    writer.WriteEndElement(); // </PickupType>

                    writer.WriteStartElement("CustomerClassification");
                    if (UseRetailRates)
                    {
                        writer.WriteElementString("Code", "04"); //04 gets retail rates
                    }
                    else
                    {
                        writer.WriteElementString("Code", string.IsNullOrWhiteSpace(_shipperNumber) ? "01" : "00"); // 00 gets shipper number rates, 01 for daily rates
                    }
                    writer.WriteEndElement();                                                                       // </CustomerClassification

                    writer.WriteStartElement("Shipment");
                    writer.WriteStartElement("Shipper");
                    if (!string.IsNullOrWhiteSpace(_shipperNumber))
                    {
                        writer.WriteElementString("ShipperNumber", _shipperNumber);
                    }
                    writer.WriteStartElement("Address");
                    writer.WriteElementString("PostalCode", Shipment.OriginAddress.PostalCode);
                    writer.WriteElementString("CountryCode", Shipment.OriginAddress.CountryCode);
                    writer.WriteEndElement(); // </Address>
                    writer.WriteEndElement(); // </Shipper>

                    writer.WriteStartElement("ShipTo");
                    writer.WriteStartElement("Address");
                    if (!string.IsNullOrWhiteSpace(Shipment.DestinationAddress.State))
                    {
                        writer.WriteElementString("StateProvinceCode", Shipment.DestinationAddress.State);
                    }
                    if (!string.IsNullOrWhiteSpace(Shipment.DestinationAddress.PostalCode))
                    {
                        writer.WriteElementString("PostalCode", Shipment.DestinationAddress.PostalCode);
                    }
                    writer.WriteElementString("CountryCode", Shipment.DestinationAddress.CountryCode);
                    if (Shipment.DestinationAddress.IsResidential)
                    {
                        writer.WriteElementString("ResidentialAddressIndicator", "true");
                    }
                    writer.WriteEndElement(); // </Address>
                    writer.WriteEndElement(); // </ShipTo>

                    if (!string.IsNullOrWhiteSpace(_serviceDescription))
                    {
                        writer.WriteStartElement("Service");
                        writer.WriteElementString("Code", _serviceDescription.ToUpsShipCode());
                        writer.WriteEndElement(); //</Service>
                    }
                    if (UseNegotiatedRates)
                    {
                        writer.WriteStartElement("RateInformation");
                        writer.WriteElementString("NegotiatedRatesIndicator", "");
                        writer.WriteEndElement();// </RateInformation>
                    }
                    if (Shipment.Options.ShippingDate != null)
                    {
                        writer.WriteStartElement("DeliveryTimeInformation");
                        writer.WriteElementString("PackageBillType", "03");
                        writer.WriteStartElement("Pickup");
                        writer.WriteElementString("Date", Shipment.Options.ShippingDate.Value.ToString("yyyyMMdd"));
                        writer.WriteElementString("Time", "1000");
                        writer.WriteEndElement(); // </Pickup>
                        writer.WriteEndElement(); // </DeliveryTimeInformation>
                    }
                    if (Shipment.Options.SaturdayDelivery)
                    {
                        writer.WriteStartElement("ShipmentServiceOptions");
                        writer.WriteElementString("SaturdayDelivery", "");
                        writer.WriteEndElement();// </ShipmentServiceOptions>
                    }

                    for (var i = 0; i < Shipment.Packages.Count; i++)
                    {
                        writer.WriteStartElement("Package");
                        writer.WriteStartElement("PackagingType");
                        writer.WriteElementString("Code", "02");
                        writer.WriteEndElement(); //</PackagingType>
                        writer.WriteStartElement("PackageWeight");
                        writer.WriteElementString("Weight", Shipment.Packages[i].RoundedWeight.ToString());
                        writer.WriteEndElement(); // </PackageWeight>
                        writer.WriteStartElement("Dimensions");
                        writer.WriteElementString("Length", Shipment.Packages[i].RoundedLength.ToString());
                        writer.WriteElementString("Width", Shipment.Packages[i].RoundedWidth.ToString());
                        writer.WriteElementString("Height", Shipment.Packages[i].RoundedHeight.ToString());
                        writer.WriteEndElement(); // </Dimensions>
                        writer.WriteStartElement("PackageServiceOptions");
                        writer.WriteStartElement("InsuredValue");
                        writer.WriteElementString("CurrencyCode", "USD");
                        writer.WriteElementString("MonetaryValue", Shipment.Packages[i].InsuredValue.ToString());
                        writer.WriteEndElement(); // </InsuredValue>

                        if (Shipment.Packages[i].SignatureRequiredOnDelivery)
                        {
                            writer.WriteStartElement("DeliveryConfirmation");
                            writer.WriteElementString("DCISType", "2"); // 2 represents Delivery Confirmation Signature Required
                            writer.WriteEndElement();                   // </DeliveryConfirmation>
                        }

                        writer.WriteEndElement(); // </PackageServiceOptions>
                        writer.WriteEndElement(); // </Package>
                    }
                    writer.WriteEndElement();     // </Shipment>
                    writer.WriteEndElement();     // </RatingServiceSelectionRequest>

                    writer.WriteEndDocument();
                    writer.Flush();
                    writer.Close();
                }
                return(Encoding.UTF8.GetString(memoryStream.ToArray()));
            }
        }
示例#58
0
        //------------------------------------------------------------

        private void button1_Click(object sender, EventArgs e)
        {
            string isOk = testaCamposViewInsert();

            if (isOk == "Campos Válidos")
            {
                Service1 sv = new Service1();
                try
                {
                    using (DataSet Resultado = new DataSet())
                    {
                        //Leitura nos arquivos em XML
                        Resultado.ReadXml(DadosXML(caminho) + @"Dados\Clientes.xml");


                        //Instanciamento das classes

                        Cliente cliente = new Cliente()
                        {
                            Nome           = nome,
                            Email          = email,
                            DataNascimento = dataNascimento,
                            Cpf            = cpf,
                            Senha          = senha
                        };

                        if (Resultado.Tables.Count == 0)
                        {
                            //Atribuindo valores propriedade
                            XmlTextWriter writer = new XmlTextWriter(DadosXML(caminho) + @"Dados\Clientes.xml", System.Text.Encoding.UTF8);
                            writer.WriteStartDocument(true);
                            writer.Formatting  = Formatting.Indented;
                            writer.Indentation = 2;
                            writer.WriteStartElement("Clientes");

                            writer.WriteStartElement("Cliente");

                            writer.WriteStartElement("Nome");
                            writer.WriteString(cliente.Nome.ToString());
                            writer.WriteEndElement();

                            writer.WriteStartElement("Cpf");
                            writer.WriteString(cliente.Cpf.ToString());
                            writer.WriteEndElement();

                            writer.WriteStartElement("Nascimento");
                            writer.WriteValue(cliente.DataNascimento.ToString());
                            writer.WriteEndElement();

                            writer.WriteStartElement("Email");
                            writer.WriteString(cliente.Email.ToString());
                            writer.WriteEndElement();

                            writer.WriteEndElement();
                            writer.WriteEndDocument();
                            writer.Close();

                            Resultado.ReadXml(DadosXML(caminho) + @"Dados\Clientes.xml");
                        }
                        else
                        {
                            //inclui os dados no DataSet
                            Resultado.Tables[0].Rows.Add(Resultado.Tables[0].NewRow());
                            Resultado.Tables[0].Rows[Resultado.Tables[0].Rows.Count - 1]["Nome"]       = nome.ToString();
                            Resultado.Tables[0].Rows[Resultado.Tables[0].Rows.Count - 1]["Cpf"]        = cpf.ToString();
                            Resultado.Tables[0].Rows[Resultado.Tables[0].Rows.Count - 1]["Nascimento"] = dataNascimento.ToString();
                            Resultado.Tables[0].Rows[Resultado.Tables[0].Rows.Count - 1]["Email"]      = email.ToString();
                            Resultado.AcceptChanges();
                            //--  Escreve para o arquivo XML final usando o método Write
                            Resultado.WriteXml(DadosXML(caminho) + @"Dados\Clientes.xml", XmlWriteMode.IgnoreSchema);
                        }
                        string result = sv.InsertClient(cliente);
                        MessageBox.Show(result);
                        LimparTextBox(this);

                        Conta clienteConta = new Conta();
                        clienteConta.EmailCliente = email;
                        sv.InsertConta(clienteConta);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Erro " + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show(isOk);
            }
        }
        /*
         * <Page id="" pageName="" docID="" entry="" />
         *
         * <Activity activityID="" activityName="" activityValue="" x="" y="" width="" height="" docID="">
         *  <EntryNode id="" />
         *  <Node id="" />
         *  <Node id="" />
         *  <Node id="" />
         *  <Node id="" />
         *  <Node id="" />
         * </Activity>
         *
         * <Node id="" docID="" lineNodeX="" lineNodeY="" allowDrop="" allowDraw="" LabelText="" />
         * <Link key="" val="" />
         *
         *
         *
         *
         *  MemoryStream ms = new MemoryStream();
         *  TextWriter w = new StreamWriter(ms);
         *  TextReader r = new StreamReader(ms);
         *
         *  w.WriteLine("12345");
         *  w.WriteLine("67890");
         *  w.Flush();
         *
         *  ms.Seek(0, SeekOrigin.Begin);
         *
         *
         *  string r1 = r.ReadLine();
         *  string r2 = r.ReadLine();
         *
         */

        /*
         * public bool SaveFile(string strFile)
         * {
         *  bool ret = false;
         *  FileStream fs = null;
         *  XmlTextWriter w = null;
         *
         *  try
         *  {
         *      if (File.Exists(strFile))
         *      {
         *          fs = new FileStream(strFile, FileMode.Truncate);
         *      }
         *      else
         *      {
         *          fs = new FileStream(strFile, FileMode.CreateNew);
         *      }
         *      w = new XmlTextWriter(fs, Encoding.UTF8);
         *
         *      w.WriteStartDocument();
         *      w.WriteStartElement("CallFlow");
         *      w.WriteAttributeString("Project", strProject);
         *      w.WriteAttributeString("Description", strDesc);
         *      w.WriteAttributeString("Version", strVersion);
         *      w.WriteAttributeString("Extension", strExtension);
         *
         *      w.WriteAttributeString("Start", startActivity.ActivityID);
         *
         *      //Page
         *      Dictionary<string, Page>.Enumerator pEnum = mapPage.GetEnumerator();
         *      while (pEnum.MoveNext())
         *      {
         *          KeyValuePair<string, Page> val = pEnum.Current;
         *          w.WriteStartElement("Page");
         *          w.WriteAttributeString("flowName", val.Value.FlowName);
         *          w.WriteAttributeString("docID", val.Value.DocID);
         *          w.WriteAttributeString("entry", val.Value.Entry.ActivityID);
         *          w.WriteEndElement();
         *      }
         *
         *      //Activities
         *      foreach (IActivity activity in activitiess)
         *      {
         *          w.WriteStartElement("Activity");
         *          w.WriteAttributeString("activityID", activity.ActivityID);
         *          w.WriteAttributeString("activityName", activity.ActivityName);
         *          w.WriteAttributeString("activityValue", activity.ActivityValue);
         *          w.WriteAttributeString("activityDesc", activity.Description);
         *          w.WriteAttributeString("x", Convert.ToString(activity.Position.X));
         *          w.WriteAttributeString("y", Convert.ToString(activity.Position.Y));
         *          w.WriteAttributeString("width", Convert.ToString(activity.Width));
         *          w.WriteAttributeString("height", Convert.ToString(activity.Height));
         *          w.WriteAttributeString("docID", activity.DocID);
         *
         *          w.WriteStartElement("EntryNode");
         *          w.WriteAttributeString("id", activity.EntryNode.NodeName);
         *          w.WriteEndElement(); //EntryNode
         *
         *          if (activity.PrimaryNode != null)
         *          {
         *              w.WriteStartElement("PrimaryNode");
         *              w.WriteAttributeString("id", activity.PrimaryNode.NodeName);
         *              w.WriteEndElement(); //PrimaryNode
         *          }
         *
         *          //Node in activity
         *          foreach (Node n in activity.Nodes)
         *          {
         *              w.WriteStartElement("Node");
         *              w.WriteAttributeString("id", n.NodeName);
         *              w.WriteEndElement(); //Node
         *          }
         *
         *          Dictionary<string, string>.Enumerator pValues = activity.Values().GetEnumerator();
         *
         *          while (pValues.MoveNext())
         *          {
         *              KeyValuePair<string, string> val = pValues.Current;
         *
         *              w.WriteStartElement("Attrs");
         *              w.WriteAttributeString("key", val.Key);
         *              w.WriteAttributeString("val", val.Value);
         *              w.WriteEndElement();
         *          }
         *
         *          w.WriteEndElement(); //Activity
         *      }
         *
         *      //Node
         *      Dictionary<string, Node>.Enumerator pNode = mapNodes.GetEnumerator();
         *      while (pNode.MoveNext())
         *      {
         *          KeyValuePair<string, Node> val = pNode.Current;
         *
         *          w.WriteStartElement("Node");
         *          w.WriteAttributeString("id", val.Value.NodeName);
         *          w.WriteAttributeString("docID", val.Value.DocID);
         *          w.WriteAttributeString("lineNodeX", Convert.ToString(val.Value.Label.Location.X));
         *          w.WriteAttributeString("lineNodeY", Convert.ToString(val.Value.Label.Location.Y));
         *          w.WriteAttributeString("allowDrop", Convert.ToString(val.Value.AllowDrop));
         *          w.WriteAttributeString("allowDraw", Convert.ToString(val.Value.AllowDraw));
         *          w.WriteAttributeString("LabelText", val.Value.Text);
         *          w.WriteAttributeString("NodeValue", val.Value.NodeValue);
         *          w.WriteEndElement();
         *      }
         *
         *      //Link
         *      Dictionary<Node, Node>.Enumerator pNodes = mapNodeRelationship.GetEnumerator();
         *      while (pNodes.MoveNext())
         *      {
         *          KeyValuePair<Node, Node> val = pNodes.Current;
         *
         *          w.WriteStartElement("Link");
         *          w.WriteAttributeString("key", val.Key.NodeName);
         *          w.WriteAttributeString("val", val.Value.NodeName);
         *          w.WriteEndElement();
         *      }
         *
         *      foreach (string strVar in variableList)
         *      {
         *          w.WriteStartElement("Variable");
         *          w.WriteAttributeString("val", strVar);
         *          w.WriteEndElement();
         *      }
         *
         *      w.WriteEndElement(); //Call Flow
         *      w.WriteEndDocument();
         *
         *      w.Flush();
         *      w.Close();
         *
         *      w = null;
         *
         *      fs.Close();
         *      fs = null;
         *
         *      ret = true;
         *  }
         *  catch (Exception ex)
         *  {
         *      throw ex;
         *  }
         *  finally
         *  {
         *      if (w != null)
         *          w.Close();
         *
         *      if (fs != null)
         *          fs.Close();
         *  }
         *
         *  return ret;
         * }
         */

        public bool SaveFile(string strFile)
        {
            bool          ret = false;
            XmlTextWriter w   = null;

            try
            {
                ms = new MemoryStream();
                w  = new XmlTextWriter(ms, Encoding.UTF8);

                w.WriteStartDocument();
                w.WriteStartElement("CallFlow");
                w.WriteAttributeString("Project", strProject);
                w.WriteAttributeString("Description", strDesc);
                w.WriteAttributeString("Version", strVersion);
                w.WriteAttributeString("Extension", strExtension);
                w.WriteAttributeString("Host", strHost);
                w.WriteAttributeString("Port", strPort);
                w.WriteAttributeString("Path", strPath);
                w.WriteAttributeString("Command", strCmd);
                w.WriteAttributeString("UserName", strUserName);
                w.WriteAttributeString("Password", strPwd);
                w.WriteAttributeString("RemoteConnection", Convert.ToString(remoteConnection));
                if (startActivity != null)
                {
                    w.WriteAttributeString("Start", startActivity.ActivityID);
                }
                else
                {
                    w.WriteAttributeString("Start", "");
                }


                //Page
                Dictionary <string, Page> .Enumerator pEnum = mapPage.GetEnumerator();
                while (pEnum.MoveNext())
                {
                    KeyValuePair <string, Page> val = pEnum.Current;
                    w.WriteStartElement("Page");
                    w.WriteAttributeString("flowName", val.Value.FlowName);
                    w.WriteAttributeString("docID", val.Value.DocID);
                    w.WriteAttributeString("entry", val.Value.Entry.ActivityID);
                    w.WriteEndElement();
                }

                //Activities
                foreach (IActivity activity in activitiess)
                {
                    w.WriteStartElement("Activity");
                    w.WriteAttributeString("activityID", activity.ActivityID);
                    w.WriteAttributeString("activityName", activity.ActivityName);
                    w.WriteAttributeString("activityValue", activity.ActivityValue);
                    w.WriteAttributeString("activityDesc", activity.Description);
                    w.WriteAttributeString("x", Convert.ToString(activity.Position.X));
                    w.WriteAttributeString("y", Convert.ToString(activity.Position.Y));
                    w.WriteAttributeString("width", Convert.ToString(activity.Width));
                    w.WriteAttributeString("height", Convert.ToString(activity.Height));
                    w.WriteAttributeString("docID", activity.DocID);

                    w.WriteStartElement("EntryNode");
                    w.WriteAttributeString("id", activity.EntryNode.NodeName);
                    w.WriteEndElement(); //EntryNode

                    if (activity.PrimaryNode != null)
                    {
                        w.WriteStartElement("PrimaryNode");
                        w.WriteAttributeString("id", activity.PrimaryNode.NodeName);
                        w.WriteEndElement(); //PrimaryNode
                    }

                    //Node in activity
                    foreach (Node n in activity.Nodes)
                    {
                        w.WriteStartElement("Node");
                        w.WriteAttributeString("id", n.NodeName);
                        w.WriteEndElement(); //Node
                    }

                    Dictionary <string, string> .Enumerator pValues = activity.Values().GetEnumerator();

                    while (pValues.MoveNext())
                    {
                        KeyValuePair <string, string> val = pValues.Current;

                        w.WriteStartElement("Attrs");
                        w.WriteAttributeString("key", val.Key);
                        w.WriteAttributeString("val", val.Value);
                        w.WriteEndElement();
                    }

                    w.WriteEndElement(); //Activity
                }

                //Node
                Dictionary <string, Node> .Enumerator pNode = mapNodes.GetEnumerator();
                while (pNode.MoveNext())
                {
                    KeyValuePair <string, Node> val = pNode.Current;

                    w.WriteStartElement("Node");
                    w.WriteAttributeString("id", val.Value.NodeName);
                    w.WriteAttributeString("docID", val.Value.DocID);
                    w.WriteAttributeString("lineNodeX", Convert.ToString(val.Value.Label.Location.X));
                    w.WriteAttributeString("lineNodeY", Convert.ToString(val.Value.Label.Location.Y));
                    w.WriteAttributeString("allowDrop", Convert.ToString(val.Value.AllowDrop));
                    w.WriteAttributeString("allowDraw", Convert.ToString(val.Value.AllowDraw));
                    w.WriteAttributeString("LabelText", val.Value.Text);
                    w.WriteAttributeString("NodeValue", val.Value.NodeValue);
                    w.WriteEndElement();
                }

                //Link
                Dictionary <Node, Node> .Enumerator pNodes = mapNodeRelationship.GetEnumerator();
                while (pNodes.MoveNext())
                {
                    KeyValuePair <Node, Node> val = pNodes.Current;

                    w.WriteStartElement("Link");
                    w.WriteAttributeString("key", val.Key.NodeName);
                    w.WriteAttributeString("val", val.Value.NodeName);
                    w.WriteEndElement();
                }

                foreach (string strVar in variableList)
                {
                    w.WriteStartElement("Variable");
                    w.WriteAttributeString("val", strVar);
                    w.WriteEndElement();
                }

                w.WriteEndElement(); //Call Flow
                w.WriteEndDocument();

                w.Flush();

                ret = SaveFileImp(strFile);

                w.Close();
                w = null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (w != null)
                {
                    w.Close();
                }

                if (ms != null)
                {
                    ms.Close();
                }

                ms = null;
            }

            return(ret);
        }
示例#60
0
        /// <summary>
        /// retrived parameter info from the net
        /// </summary>
        /// <param name="ap">xml name for arduplane</param>
        /// <param name="ac">xml name for arducopter</param>
        /// <param name="ar">xml name for ardurover</param>
        public static void GetParameterInformation()
        {
            string parameterLocationsString = ConfigurationManager.AppSettings["ParameterLocations"];

            if (MissionPlanner.Utilities.Update.dobeta)
            {
                parameterLocationsString = ConfigurationManager.AppSettings["ParameterLocationsBleeding"];
            }

            if (!String.IsNullOrEmpty(parameterLocationsString))
            {
                var parameterLocations = parameterLocationsString.Split(';').ToList();
                parameterLocations.RemoveAll(String.IsNullOrEmpty);

                string sStartupPath = Application.StartupPath;
                using (
                    var objXmlTextWriter =
                        new XmlTextWriter(
                            String.Format("{0}{1}{2}", Application.StartupPath, Path.DirectorySeparatorChar,
                                          ConfigurationManager.AppSettings["ParameterMetaDataXMLFileName"]), null))
                {
                    objXmlTextWriter.Formatting = Formatting.Indented;
                    objXmlTextWriter.WriteStartDocument();

                    objXmlTextWriter.WriteStartElement("Params");

                    foreach (string parameterLocation in parameterLocations)
                    {
                        string element = "none";

                        if (parameterLocation.ToLower().Contains("arducopter"))
                        {
                            element = MainV2.Firmwares.ArduCopter2.ToString();
                        }
                        else if (parameterLocation.ToLower().Contains("arduplane"))
                        {
                            element = MainV2.Firmwares.ArduPlane.ToString();
                        }
                        else if (parameterLocation.ToLower().Contains("rover"))
                        {
                            element = MainV2.Firmwares.ArduRover.ToString();
                        }
                        else if (parameterLocation.ToLower().Contains("tracker"))
                        {
                            element = MainV2.Firmwares.ArduTracker.ToString();
                        }

                        // Read and parse the content.
                        string dataFromAddress = ReadDataFromAddress(parameterLocation.Trim());

                        if (String.IsNullOrEmpty(dataFromAddress)) // 404
                        {
                            continue;
                        }

                        if (dataFromAddress.Length < 200) // blank template file
                        {
                            continue;
                        }

                        // Write the start element for this parameter location
                        objXmlTextWriter.WriteStartElement(element);
                        ParseGroupInformation(dataFromAddress, objXmlTextWriter, parameterLocation.Trim());
                        ParseParameterInformation(dataFromAddress, objXmlTextWriter);

                        // Write the end element for this parameter location
                        objXmlTextWriter.WriteEndElement();
                    }

                    objXmlTextWriter.WriteEndElement();

                    // Clear the stream
                    objXmlTextWriter.WriteEndDocument();
                    objXmlTextWriter.Flush();
                    objXmlTextWriter.Close();
                }
            }
        }