private static void TreverseDirectories(XmlTextWriter writer, DirectoryInfo dir)
    {
        var folders = dir.GetDirectories();
        var files = dir.GetFiles();
        writer.WriteStartElement("folder");
        writer.WriteElementString("name", dir.Name);

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

                writer.WriteEndElement();
            }

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

            writer.WriteEndElement();
        }
        catch (Exception)
        {
            Console.WriteLine("Access denied! ");
        }
    }
Exemplo n.º 2
0
    public static int Main(string[] args)
    {
        if (args.Length < 1) {
            Console.Error.WriteLine("Usage: RunMorphoCli tagger_file");
            return 1;
        }

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

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

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

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

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

                for (int i = 0; i < lemmas.Count; i++) {
                    TaggedLemma lemma = lemmas[i];
                    int token_start = (int)tokens[i].start, token_length = (int)tokens[i].length;
                    xmlOut.WriteString(text.Substring(t, token_start - t));
                    if (i == 0) xmlOut.WriteStartElement("sentence");
                    xmlOut.WriteStartElement("token");
                    xmlOut.WriteAttributeString("lemma", lemma.lemma);
                    xmlOut.WriteAttributeString("tag", lemma.tag);
                    xmlOut.WriteString(text.Substring(token_start, token_length));
                    xmlOut.WriteEndElement();
                    if (i + 1 == lemmas.Count) xmlOut.WriteEndElement();
                    t = token_start + token_length;
                }
            }
            xmlOut.WriteString(text.Substring(t));
        }
        return 0;
    }
    private void GetRssFeedContens(AspxCommonInfo aspxCommonObj, string pageURL, int count)
    {
        try
        {
            string[] path = pageURL.Split('?');
            string pagepath = path[0];
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "text/xml";
            XmlTextWriter rssXml = new XmlTextWriter(HttpContext.Current.Response.OutputStream, Encoding.UTF8);

            rssXml.WriteStartDocument();

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

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Exemplo n.º 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();

    }
            public void WriteGestureLog(Dictionary<String, Point3D> gestureDict, string timeStamp)
            {
                using (StringWriter sw = new StringWriter(_sBuilder))
                {
                    using (XmlWriter xmlWriter = new XmlTextWriter(sw))
                    {
                        //START MOVEMENT
                        xmlWriter.WriteStartElement("mov");
                        xmlWriter.WriteStartAttribute("time_stamp");
                        xmlWriter.WriteValue(timeStamp);
                        xmlWriter.WriteEndAttribute();
                        //PRINT ALL JOINTS
                        foreach (var point in gestureDict)
                        {
                            xmlWriter.WriteStartElement(point.Key);//START JOINT
                            xmlWriter.WriteStartElement("x");
                            xmlWriter.WriteValue(point.Value.X);
                            xmlWriter.WriteEndElement();
                            xmlWriter.WriteStartElement("Y");
                            xmlWriter.WriteValue(point.Value.Y);
                            xmlWriter.WriteEndElement();
                            xmlWriter.WriteStartElement("Z");
                            xmlWriter.WriteValue(point.Value.Z);
                            xmlWriter.WriteEndElement();
                            xmlWriter.WriteEndElement();//END JOINT
                        }
                        xmlWriter.WriteEndElement();//END MOV
                    }

                }
                WriteToXMLLogFile();
            }
Exemplo n.º 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 static void WriteBookmarks(
		XmlTextWriter writer, IList<Bookmark> bookmarks)
	{
		writer.WriteStartElement("result-set");
		foreach (var bookmark in bookmarks)
		{
			writer.WriteStartElement("bookmark");
			if (bookmark.User.Username != null)
			{
				writer.WriteElementString("username", bookmark.User.Username);
			}
			if (bookmark.Title != null)
			{
				writer.WriteElementString("title", bookmark.Title);
			}
			if (bookmark.URL != null)
			{
				writer.WriteElementString("url", bookmark.URL);
			}
			if (bookmark.Tags.Count > 0)
			{
				string tags = string.Join(", ",
					bookmark.Tags.Select(t => t.Name).OrderBy(t => t));
				writer.WriteElementString("tags", tags);
			}
			if (bookmark.Notes != null)
			{
				writer.WriteElementString("notes", bookmark.Notes);
			}
			writer.WriteEndElement();
		}
		writer.WriteEndElement();
	}
Exemplo n.º 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();
            }
        }
    }
Exemplo n.º 9
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();
    }
    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();
    }
Exemplo n.º 11
0
    public XmlTextWriter WriteRSSClosing(XmlTextWriter writer)
    {
        writer.WriteEndElement();
           writer.WriteEndElement();
           writer.WriteEndDocument();

           return writer;
    }
    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();
        }
    }
Exemplo n.º 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();
    }
Exemplo n.º 14
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;
    }
 private static void WriteAlbum(XmlTextWriter writer, string name, string artist)
 {
     writer.WriteStartElement("album");
     writer.WriteElementString("name", name);
     writer.WriteElementString("artist", artist);
     writer.WriteEndElement();
 }
Exemplo n.º 17
0
 private void AddURL(XmlTextWriter writer, string siteUrl, string url, DateTime dateUpdate)
 {
     writer.WriteStartElement("url");
     writer.WriteElementString("loc", siteUrl + url);
     writer.WriteElementString("lastmod", String.Format("{0:yyyy-MM-dd}", dateUpdate));
     writer.WriteEndElement();
 }
Exemplo n.º 18
0
 void Create()
 {
     XmlTextWriter writer = new XmlTextWriter ("todo.xml", System.Text.Encoding.UTF8);
     writer.WriteStartDocument ();
     writer.WriteStartElement ("tasks");
     writer.WriteEndElement ();
     writer.Close ();
 }
Exemplo n.º 19
0
    /// <summary>
    /// This method is used for creating a new employee information in XML file
    /// </summary>
    /// <param name="employee">employee object</param>
    /// <returns>True - Success, False - Failure</returns>
    public bool Create(BLAutot auto)
    {
        try
        {
            // Checking if the file exist
            if (!File.Exists(strFileName))
            {
                // If file does not exist in the database path, create and store an empty Autot node
                XmlTextWriter textWritter = new XmlTextWriter(strFileName, null);
                textWritter.WriteStartDocument();
                textWritter.WriteStartElement("Wanhatautot");
                textWritter.WriteEndElement();
                textWritter.Close();
            }

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

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

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

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

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

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

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

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

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

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

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

            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private static void collapseAll(XmlTextWriter writer, string directory)
    {
        foreach (var dir in Directory.GetDirectories(directory))
        {
            writer.WriteStartElement("dir");
            writer.WriteAttributeString("path", directory.TrimStart('.', '\\'));
            collapseAll(writer, dir);     // using recursion to expand and search in all subfolders
            writer.WriteEndElement();
        }

        foreach (var file in Directory.GetFiles(directory))
        {
            writer.WriteStartElement("file");
            writer.WriteAttributeString("name", file.Substring(file.LastIndexOf('\\') + 1)); //using the Substring() method
            writer.WriteEndElement();                                                        //to remove the file path and
                                                                                             //write only the name of the file
        }
    }
Exemplo n.º 21
0
 private void ObjectToElement(XmlTextWriter xml)
 {
     // data element
     xml.WriteStartElement("player");
     xml.WriteElementString("name", _name);
     string scoreString = "" + _score; // make _score a string
     xml.WriteElementString("score", scoreString);
     xml.WriteEndElement();
 }
Exemplo n.º 22
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();
    }
Exemplo n.º 23
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();
    }
 public void WriteLog(String element, String value)
 {
     using (StringWriter sw = new StringWriter(_sBuilder))
     {
         using (XmlWriter xmlWritter = new XmlTextWriter(sw))
         {
             xmlWritter.WriteStartElement(element);
             xmlWritter.WriteEndElement();
         }
     }
 }
Exemplo n.º 25
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();
 }
Exemplo n.º 26
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();
    }
Exemplo n.º 27
0
    private void AddRequestXml(string url, HttpWebRequest req)
    {
        Stream stream = (Stream)req.GetRequestStream();
        using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
        {
            writer.WriteStartDocument(true);
            writer.WriteStartElement("methodCall");
            writer.WriteElementString("methodName", "pingback.ping");
            writer.WriteStartElement("params");

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

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

            writer.WriteEndElement();
            writer.WriteEndElement();
        }
    }
Exemplo n.º 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;
            }
            do
            {
                string url = "";
                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);
                }
                writer.WriteStartElement("url");
                writer.WriteElementString("loc", siteUrl + url);
                writer.WriteElementString("lastmod", String.Format("{0:yyyy-MM-dd}", cont.DateUpdate));
                writer.WriteEndElement();
            } while (cont.MoveNext());
        }

        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Flush();
        Response.End();
    }
Exemplo n.º 29
0
    /// <summary>
    /// This method is used for creating a new employee information in XML file
    /// </summary>
    /// <param name="employee">employee object</param>
    /// <returns>True - Success, False - Failure</returns>
    public bool Create(BLTunnit tunti)
    {
        try
        {
            // Checking if the file exist
            if (!File.Exists(strFileName))
            {
                // If file does not exist in the database path, create and store an empty tuntit node
                XmlTextWriter textWritter = new XmlTextWriter(strFileName, null);
                textWritter.WriteStartDocument();
                textWritter.WriteStartElement("Tunnit");
                textWritter.WriteEndElement();
                textWritter.Close();
            }

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

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

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

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

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

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

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

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

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

            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Exemplo n.º 30
0
 public XmlTextWriter AddRSSItem(XmlTextWriter writer, string sItemTitle, string sItemLink, string sItemDescription, string datetime)
 {
     string itemname = System.IO.Path.GetFileName(sItemLink);
       writer.WriteStartElement("item");
            writer.WriteElementString("title",       sItemTitle);
            writer.WriteElementString("link",        "http://www.weavver.com/?redirect=" + itemname);
            writer.WriteElementString("description", "");
            writer.WriteElementString("author",      "Jane Doe");
            writer.WriteElementString("contact",     "tel://17148531212");
            writer.WriteElementString("pubDate",     datetime);
            writer.WriteElementString("tags",        "Unheard,Work");
            writer.WriteStartElement("enclosure");
                 writer.WriteAttributeString("url",                 "http://www.weavver.com/messages/" + itemname);
                 writer.WriteAttributeString("length",              "572345");
                 writer.WriteAttributeString("type",                "audio/wav");
                 writer.WriteStartElement("transcription");
                      writer.WriteAttributeString("confidence", "1.0");
                      writer.WriteValue("THIS IS THE TRANSCRIPTION.");
                 writer.WriteEndElement();
            writer.WriteEndElement();
       writer.WriteEndElement();
       return writer;
 }
Exemplo n.º 31
0
        public IRequest Marshall(CreateCloudFrontOriginAccessIdentityRequest createCloudFrontOriginAccessIdentityRequest)
        {
            IRequest request = new DefaultRequest(createCloudFrontOriginAccessIdentityRequest, "AmazonCloudFront");



            request.HttpMethod = "POST";

            string uriResourcePath = "2013-08-26/origin-access-identity/cloudfront";

            if (uriResourcePath.Contains("?"))
            {
                string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
                uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            StringWriter  stringWriter = new StringWriter();
            XmlTextWriter xmlWriter    = new XmlTextWriter(stringWriter);

            xmlWriter.Namespaces = true;

            if (createCloudFrontOriginAccessIdentityRequest != null)
            {
                CloudFrontOriginAccessIdentityConfig cloudFrontOriginAccessIdentityConfigCloudFrontOriginAccessIdentityConfig = createCloudFrontOriginAccessIdentityRequest.CloudFrontOriginAccessIdentityConfig;
                if (cloudFrontOriginAccessIdentityConfigCloudFrontOriginAccessIdentityConfig != null)
                {
                    xmlWriter.WriteStartElement("CloudFrontOriginAccessIdentityConfig", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
                    if (cloudFrontOriginAccessIdentityConfigCloudFrontOriginAccessIdentityConfig.IsSetCallerReference())
                    {
                        xmlWriter.WriteElementString("CallerReference", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cloudFrontOriginAccessIdentityConfigCloudFrontOriginAccessIdentityConfig.CallerReference.ToString());
                    }
                    if (cloudFrontOriginAccessIdentityConfigCloudFrontOriginAccessIdentityConfig.IsSetComment())
                    {
                        xmlWriter.WriteElementString("Comment", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cloudFrontOriginAccessIdentityConfigCloudFrontOriginAccessIdentityConfig.Comment.ToString());
                    }
                    xmlWriter.WriteEndElement();
                }
            }


            try
            {
                request.Content = System.Text.Encoding.UTF8.GetBytes(stringWriter.ToString());
                request.Headers.Add("Content-Type", "application/xml");
            }
            catch (EncoderFallbackException e)
            {
                throw new AmazonServiceException("Unable to marshall request to XML", e);
            }


            return(request);
        }
Exemplo n.º 32
0
        public static void WriteXml(string fileName, string basePathDir, Setting.Setting setting)
        {
            XmlTextWriter xmlWriter = null;
            string        filename  = string.Format(basePathDir + "{0}", fileName);

            try
            {
                xmlWriter            = new XmlTextWriter(filename, Encoding.UTF8);
                xmlWriter.Formatting = Formatting.Indented;
                xmlWriter.WriteStartDocument();

                xmlWriter.WriteStartElement("AltmanSetting");
                {
                    //UserAgent
                    xmlWriter.WriteStartElement("UserAgent");
                    {
                        xmlWriter.WriteStartElement("type");
                        xmlWriter.WriteString(Convert.ToInt32(setting.GetUserAgentStruct.IsRandom).ToString());
                        xmlWriter.WriteEndElement();

                        foreach (var i in setting.GetUserAgentStruct.UserAgentList)
                        {
                            xmlWriter.WriteStartElement("option");
                            {
                                //添加name属性
                                xmlWriter.WriteStartAttribute("name");
                                xmlWriter.WriteString(i.Key);
                                xmlWriter.WriteEndAttribute();

                                //如果name和selected中保存的一致,则添加selected属性
                                if (i.Key == setting.GetUserAgentStruct.Selected.Key)
                                {
                                    xmlWriter.WriteStartAttribute("selected");
                                    xmlWriter.WriteString("True");
                                    xmlWriter.WriteEndAttribute();
                                }
                                //添加value
                                xmlWriter.WriteString(i.Value);
                            }
                            xmlWriter.WriteEndElement();
                        }
                    }
                    xmlWriter.WriteEndElement();

                    //HttpHeader
                    xmlWriter.WriteStartElement("HttpHeader");
                    {
                        foreach (var i in setting.GetHttpHeaderStruct.HttpHeaderList)
                        {
                            xmlWriter.WriteStartElement("key");
                            {
                                //添加name属性
                                xmlWriter.WriteStartAttribute("name");
                                xmlWriter.WriteString(i.Key);
                                xmlWriter.WriteEndAttribute();

                                //添加value
                                xmlWriter.WriteString(i.Value);
                            }
                            xmlWriter.WriteEndElement();
                        }
                    }
                    xmlWriter.WriteEndElement();

                    //Policy
                    xmlWriter.WriteStartElement("Policy");
                    {
                        xmlWriter.WriteStartElement("isParamRandom");
                        xmlWriter.WriteString(Convert.ToInt32(setting.GetPolicyStruct.IsParamRandom).ToString());
                        xmlWriter.WriteEndElement();

                        xmlWriter.WriteStartElement("isShowDisclaimer");
                        xmlWriter.WriteString(Convert.ToInt32(setting.GetPolicyStruct.IsShowDisclaimer).ToString());
                        xmlWriter.WriteEndElement();
                    }
                    xmlWriter.WriteEndElement();

                    //Proxy
                    xmlWriter.WriteStartElement("Proxy");
                    {
                        xmlWriter.WriteStartElement("type");
                        xmlWriter.WriteString(setting.GetProxyStruct.IsNoOrIeOrCustomProxy.ToString());
                        xmlWriter.WriteEndElement();

                        xmlWriter.WriteStartElement("customProxy");
                        {
                            //添加address属性
                            xmlWriter.WriteStartAttribute("address");
                            xmlWriter.WriteString(setting.GetProxyStruct.ProxyAddr);
                            xmlWriter.WriteEndAttribute();

                            //添加port属性
                            xmlWriter.WriteStartAttribute("port");
                            xmlWriter.WriteString(setting.GetProxyStruct.ProxyPort);
                            xmlWriter.WriteEndAttribute();

                            //添加user属性
                            xmlWriter.WriteStartAttribute("user");
                            xmlWriter.WriteString(setting.GetProxyStruct.ProxyUser);
                            xmlWriter.WriteEndAttribute();

                            //添加password属性
                            xmlWriter.WriteStartAttribute("password");
                            xmlWriter.WriteString(setting.GetProxyStruct.ProxyPassword);
                            xmlWriter.WriteEndAttribute();

                            //添加domain属性
                            xmlWriter.WriteStartAttribute("domain");
                            xmlWriter.WriteString(setting.GetProxyStruct.ProxyDomain);
                            xmlWriter.WriteEndAttribute();
                        }
                        xmlWriter.WriteEndElement();
                    }
                    xmlWriter.WriteEndElement();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                xmlWriter.Close();
            }
        }
Exemplo n.º 33
0
        internal override void WriteXml(XmlTextWriter xmlWriter)
        {
            xmlWriter.WriteStartElement("coupon"); // Start: coupon

            xmlWriter.WriteElementString("coupon_code", CouponCode);
            xmlWriter.WriteElementString("name", Name);
            xmlWriter.WriteElementString("hosted_description", HostedDescription);
            xmlWriter.WriteElementString("invoice_description", InvoiceDescription);

            if (RedeemByDate.HasValue)
            {
                xmlWriter.WriteElementString("redeem_by_date", RedeemByDate.Value.ToString("s"));
            }

            if (SingleUse.HasValue)
            {
                xmlWriter.WriteElementString("single_use", SingleUse.Value.AsString());
            }

            if (AppliesForMonths.HasValue)
            {
                xmlWriter.WriteElementString("applies_for_months", AppliesForMonths.Value.AsString());
            }
            if (Duration != null)
            {
                xmlWriter.WriteElementString("duration", Duration.ToString().EnumNameToTransportCase());
            }
            if (TemporalUnit != null)
            {
                xmlWriter.WriteElementString("temporal_unit", TemporalUnit.ToString().EnumNameToTransportCase());
            }
            if (TemporalAmount.HasValue)
            {
                xmlWriter.WriteElementString("temporal_amount", TemporalAmount.Value.ToString());
            }

            if (AppliesToAllPlans.HasValue)
            {
                xmlWriter.WriteElementString("applies_to_all_plans", AppliesToAllPlans.Value.AsString());
            }

            if (MaxRedemptions.HasValue)
            {
                xmlWriter.WriteElementString("max_redemptions", MaxRedemptions.Value.AsString());
            }

            xmlWriter.WriteElementString("discount_type", DiscountType.ToString().EnumNameToTransportCase());

            if (CouponDiscountType.Percent == DiscountType && DiscountPercent.HasValue)
            {
                xmlWriter.WriteElementString("discount_percent", DiscountPercent.Value.AsString());
            }

            if (CouponDiscountType.Dollars == DiscountType)
            {
                xmlWriter.WriteIfCollectionHasAny("discount_in_cents", DiscountInCents, pair => pair.Key,
                                                  pair => pair.Value.AsString());
            }

            xmlWriter.WriteIfCollectionHasAny("plan_codes", Plans, s => "plan_code", s => s);

            xmlWriter.WriteEndElement(); // End: coupon
        }
Exemplo n.º 34
0
        private void button1_Click(object sender, EventArgs e)
        {
            //SAVE FILE
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "*.xml|*.xml";
            
            //LOAD FILE
            if (dialog.ShowDialog() == DialogResult.OK)
            using( FileStream fs = new FileStream(dialog.FileName, FileMode.Create, FileAccess.Write))
            using (XmlTextWriter writer = new XmlTextWriter(fs, Encoding.Unicode))
            {

                writer.Indentation = 1;
                writer.IndentChar = '\t';
                writer.Formatting = Formatting.Indented;

                writer.WriteStartDocument();

                writer.WriteStartElement("Inventory");

                MySqlCommand command = new MySqlCommand("SELECT `ContainerMaxStorage`,`Container` FROM `inventory` WHERE `CharId`=?CharId", conn);
                command.Parameters.AddWithValue("CharId", uint.Parse(textBox1.Text, NumberFormatInfo.InvariantInfo));

                MySqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess);
                while (reader.Read())
                {

                    byte MaxInventoryStorage = reader.GetByte(0);
                    byte[] buffer2 = new byte[4];
                    reader.GetBytes(1, 0, buffer2, 0, 4);
                    uint count = BitConverter.ToUInt32(buffer2, 0);

                    byte[] buffer = new byte[67];
                    int offset = 4;
                    for (int i = 0; i < count; i++)
                    {
                        //READ IT CHUNKED
                        reader.GetBytes(1, offset, buffer, 0, 67);
                        writer.WriteStartElement("Item");

                        //WRITES THE ITEM ID
                        writer.WriteStartElement("ItemId");
                        writer.WriteValue(BitConverter.ToUInt32(buffer, 0));
                        writer.WriteEndElement();

                        //WRITES THE DURABILITY OF THE ITEM
                        writer.WriteStartElement("Durability");
                        writer.WriteValue(BitConverter.ToUInt16(buffer, 51));
                        writer.WriteEndElement();

                        writer.WriteEndElement();
                        offset += 67;
                    }
                }

                reader.Close();

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
        }
Exemplo n.º 35
0
        private void WriteSingleUPSPackage(ref XmlTextWriter xw, IShippable pak, bool ignoreDimensions)
        {
            decimal dGirth  = 0;
            decimal dLength = 0;
            decimal dHeight = 0;
            decimal dwidth  = 0;

            var dimensions = new List <DimensionAmount>();

            if (pak.BoxLengthType == LengthType.Centimeters)
            {
                dimensions.Add(new DimensionAmount(Conversions.CentimetersToInches(pak.BoxLength)));
                dimensions.Add(new DimensionAmount(Conversions.CentimetersToInches(pak.BoxWidth)));
                dimensions.Add(new DimensionAmount(Conversions.CentimetersToInches(pak.BoxHeight)));
            }
            else
            {
                dimensions.Add(new DimensionAmount(pak.BoxLength));
                dimensions.Add(new DimensionAmount(pak.BoxWidth));
                dimensions.Add(new DimensionAmount(pak.BoxWidth));
            }

            var sorted = (from d in dimensions
                          orderby d.Amount descending
                          select d.Amount).ToList();

            dLength = sorted[0];
            dwidth  = sorted[1];
            dHeight = sorted[2];

            dGirth = dwidth + dwidth + dHeight + dHeight;

            //--------------------------------------------
            // Package
            xw.WriteStartElement("Package");

            xw.WriteStartElement("PackagingType");

            var packageType = "02";

            if (GlobalSettings.DefaultPackaging != (int)PackagingType.Unknown)
            {
                packageType = ((int)GlobalSettings.DefaultPackaging).ToString();
                if (packageType.Trim().Length < 2)
                {
                    packageType = "0" + packageType;
                }
            }

            xw.WriteElementString("Code", packageType);
            xw.WriteElementString("Description", "Package");
            xw.WriteEndElement();

            //Dimensions can be skipped in latest UPS specs
            if (!ignoreDimensions)
            {
                if (dLength > 0 | dHeight > 0 | dwidth > 0)
                {
                    xw.WriteStartElement("Dimensions");
                    xw.WriteStartElement("UnitOfMeasure");
                    xw.WriteElementString("Code", "IN");
                    xw.WriteEndElement();
                    xw.WriteElementString("Length", Math.Round(dLength, 2).ToString(CultureInfo.InvariantCulture));
                    xw.WriteElementString("Width", Math.Round(dwidth, 2).ToString(CultureInfo.InvariantCulture));
                    xw.WriteElementString("Height", Math.Round(dHeight, 2).ToString(CultureInfo.InvariantCulture));
                    xw.WriteEndElement();
                }
            }

            if (pak.BoxWeight > 0)
            {
                xw.WriteStartElement("PackageWeight");
                xw.WriteStartElement("UnitOfMeasure");

                xw.WriteElementString("Code", pak.BoxWeightType == WeightType.Pounds ? "LBS" : "KGS");

                xw.WriteEndElement();
                xw.WriteElementString("Weight", Math.Round(pak.BoxWeight, 1).ToString(CultureInfo.InvariantCulture));
                xw.WriteEndElement();
            }
            else
            {
                xw.WriteStartElement("PackageWeight");
                xw.WriteStartElement("UnitOfMeasure");

                if (pak.BoxWeightType == WeightType.Pounds)
                {
                    xw.WriteElementString("Code", "LBS");
                }
                else
                {
                    xw.WriteElementString("Code", "KGS");
                }

                xw.WriteEndElement();
                xw.WriteElementString("Weight", Math.Round(0.1, 1).ToString(CultureInfo.InvariantCulture));
                xw.WriteEndElement();
            }

            if (ignoreDimensions == false)
            {
                // Oversize Checks
                var oversizeCheck = dGirth + dLength;
                if (oversizeCheck > 84)
                {
                    if (oversizeCheck < 108 & pak.BoxWeight < 30)
                    {
                        xw.WriteElementString("OversizePackage", "1");
                    }
                    else
                    {
                        if (pak.BoxWeight < 70)
                        {
                            xw.WriteElementString("OversizePackage", "2");
                        }
                        else
                        {
                            xw.WriteElementString("OversizePackage", "0");
                        }
                    }
                }
            }

            xw.WriteEndElement();
            // End Package
            //--------------------------------------------
        }
 private void WriteEndDocument()
 {
     writer.WriteEndElement();
     writer.WriteEndDocument();
 }
Exemplo n.º 37
0
        private void btnGO_Click(object sender, EventArgs e)
        {
            Dictionary <string, List <IntVect> > chipRes = new Dictionary <string, List <IntVect> >();
            List <IntVect> vectList = new List <IntVect>();

            string input = textBox1.Text;

            XmlDocument xDoc = new XmlDocument();

            try
            {
                xDoc.LoadXml(input);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
                return;
            }

            XmlElement docEle = xDoc.DocumentElement;

            foreach (XmlElement vectEle in docEle.GetElementsByTagName("tr"))
            {
                string newVectName = "";
                string oldVectName = "";
                string desc        = "";
                string allParts    = "";

                try
                {
                    newVectName = vectEle.GetElementsByTagName("td")[0].InnerText;
                    oldVectName = vectEle.GetElementsByTagName("td")[1].InnerText;
                    desc        = vectEle.GetElementsByTagName("td")[2].InnerText;
                    allParts    = vectEle.GetElementsByTagName("td")[3].InnerText;
                }
                catch { continue; }

                IntVect v = new IntVect(newVectName, oldVectName, desc);

                string[] parts = allParts.Split(new char[] { ',', ' ', '\r', '\n', '\t', });
                foreach (string part_ in parts)
                {
                    string part = part_.ToLowerInvariant().Trim();

                    if (string.IsNullOrEmpty(part))
                    {
                        continue;
                    }

                    if (chipRes.ContainsKey(part) == false)
                    {
                        chipRes.Add(part, new List <IntVect>());
                    }

                    if (chipRes[part].Contains(v) == false)
                    {
                        chipRes[part].Add(v);
                    }

                    if (vectList.Contains(v) == false)
                    {
                        vectList.Add(v);
                    }
                }
            }

            string filePath = Directory.GetCurrentDirectory().Trim(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar + "interruptvectors.xml";

            XmlTextWriter writer = new XmlTextWriter(filePath, new ASCIIEncoding());

            writer.Formatting  = Formatting.Indented;
            writer.Indentation = 1;
            writer.IndentChar  = '\t';

            writer.WriteStartDocument();

            writer.WriteStartElement("InterruptVectors");

            writer.WriteStartElement("ListOfVectors");
            {
                foreach (IntVect i in vectList)
                {
                    writer.WriteStartElement("Vector");
                    writer.WriteAttributeString("Text", i.Description);
                    writer.WriteElementString("NewName", i.NewName);
                    writer.WriteElementString("OldName", i.OldName);
                    writer.WriteElementString("Desc", i.Description);
                    writer.WriteEndElement();
                }
            }
            writer.WriteEndElement();

            writer.WriteStartElement("ListOfChips");
            {
                foreach (KeyValuePair <string, List <IntVect> > i in chipRes)
                {
                    writer.WriteStartElement("Chip");
                    writer.WriteAttributeString("Name", i.Key);
                    foreach (IntVect j in i.Value)
                    {
                        writer.WriteStartElement("HasVector");
                        writer.WriteAttributeString("NewName", j.NewName);
                        writer.WriteAttributeString("OldName", j.OldName);
                        writer.WriteString(j.Description);
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                }
            }
            writer.WriteEndElement();

            writer.WriteEndDocument();

            writer.Close();

            textBox1.Text     = File.ReadAllText(filePath);
            textBox1.ReadOnly = true;
            btnGO.Enabled     = false;
            btnGO.Visible     = false;
        }
Exemplo n.º 38
0
 /// <summary>
 /// Save the object's XML to the XmlWriter.
 /// </summary>
 /// <param name="objWriter">XmlTextWriter to write with.</param>
 public void Save(XmlTextWriter objWriter)
 {
     objWriter.WriteStartElement("accessory");
     objWriter.WriteElementString("guid", _guiID.ToString());
     objWriter.WriteElementString("name", _strName);
     objWriter.WriteElementString("mount", _strMount);
     objWriter.WriteElementString("extramount", _strExtraMount);
     objWriter.WriteElementString("rc", _strRC);
     objWriter.WriteElementString("rating", _intRating.ToString());
     objWriter.WriteElementString("rcgroup", _intRCGroup.ToString());
     objWriter.WriteElementString("rcdeployable", _blnDeployable.ToString());
     objWriter.WriteElementString("conceal", _strConceal);
     if (_strDicePool != "")
     {
         objWriter.WriteElementString("dicepool", _strDicePool);
     }
     objWriter.WriteElementString("avail", _strAvail);
     objWriter.WriteElementString("cost", _strCost);
     objWriter.WriteElementString("included", _blnIncludedInWeapon.ToString());
     objWriter.WriteElementString("installed", _blnInstalled.ToString());
     if (_nodAllowGear != null)
     {
         objWriter.WriteRaw(_nodAllowGear.OuterXml);
     }
     objWriter.WriteElementString("source", _strSource);
     objWriter.WriteElementString("page", _strPage);
     objWriter.WriteElementString("accuracy", _intAccuracy.ToString());
     if (_lstGear.Count > 0)
     {
         objWriter.WriteStartElement("gears");
         foreach (Gear objGear in _lstGear)
         {
             // Use the Gear's SubClass if applicable.
             if (objGear.GetType() == typeof(Commlink))
             {
                 Commlink objCommlink = new Commlink(_objCharacter);
                 objCommlink = (Commlink)objGear;
                 objCommlink.Save(objWriter);
             }
             else
             {
                 objGear.Save(objWriter);
             }
         }
         objWriter.WriteEndElement();
     }
     objWriter.WriteElementString("ammoslots", _intAmmoSlots.ToString());
     objWriter.WriteElementString("damagetype", _strDamageType);
     objWriter.WriteElementString("damage", _strDamage);
     objWriter.WriteElementString("damagereplace", _strDamageReplace);
     objWriter.WriteElementString("firemode", _strFireMode);
     objWriter.WriteElementString("firemodereplace", _strFireModeReplace);
     objWriter.WriteElementString("ap", _strAP);
     objWriter.WriteElementString("apreplace", _strAPReplace);
     objWriter.WriteElementString("notes", _strNotes);
     objWriter.WriteElementString("discountedcost", DiscountCost.ToString());
     objWriter.WriteElementString("addmode", _strAddMode);
     objWriter.WriteElementString("fullburst", _intFullBurst.ToString());
     objWriter.WriteElementString("suppressive", _intSuppressive.ToString());
     objWriter.WriteElementString("rangebonus", _intRangeBonus.ToString());
     objWriter.WriteElementString("extra", _strExtra);
     objWriter.WriteElementString("ammobonus", _intAmmoBonus.ToString());
     objWriter.WriteEndElement();
     _objCharacter.SourceProcess(_strSource);
 }
Exemplo n.º 39
0
        private void cmdOK_Click(object sender, EventArgs e)
        {
            // Make sure the kit and file name fields are populated.
            if (string.IsNullOrEmpty(txtName.Text))
            {
                MessageBox.Show(LanguageManager.GetString("Message_CreatePACKSKit_KitName"), LanguageManager.GetString("MessageTitle_CreatePACKSKit_KitName"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (string.IsNullOrEmpty(txtFileName.Text))
            {
                MessageBox.Show(LanguageManager.GetString("Message_CreatePACKSKit_FileName"), LanguageManager.GetString("MessageTitle_CreatePACKSKit_FileName"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // Make sure the file name starts with custom and ends with _packs.xml.
            if (!txtFileName.Text.StartsWith("custom") || !txtFileName.Text.EndsWith("_packs.xml"))
            {
                MessageBox.Show(LanguageManager.GetString("Message_CreatePACKSKit_InvalidFileName"), LanguageManager.GetString("MessageTitle_CreatePACKSKit_InvalidFileName"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // See if a Kit with this name already exists for the Custom category. This is done without the XmlManager since we need to check each file individually.
            XmlDocument objXmlDocument = new XmlDocument();
            string      strCustomPath  = Path.Combine(Application.StartupPath, "data");

            foreach (string strFile in Directory.GetFiles(strCustomPath, "custom*_packs.xml"))
            {
                objXmlDocument.Load(strFile);
                XmlNodeList objXmlPACKSList = objXmlDocument.SelectNodes("/chummer/packs/pack[name = \"" + txtName.Text + "\" and category = \"Custom\"]");
                if (objXmlPACKSList.Count > 0)
                {
                    MessageBox.Show(LanguageManager.GetString("Message_CreatePACKSKit_DuplicateName").Replace("{0}", txtName.Text).Replace("{1}", strFile.Replace(strCustomPath + Path.DirectorySeparatorChar, string.Empty)), LanguageManager.GetString("MessageTitle_CreatePACKSKit_DuplicateName"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }

            string strPath    = Path.Combine(strCustomPath, txtFileName.Text);
            bool   blnNewFile = !File.Exists(strPath);

            // If this is not a new file, read in the existing contents.
            XmlDocument objXmlCurrentDocument = new XmlDocument();

            if (!blnNewFile)
            {
                objXmlCurrentDocument.Load(strPath);
            }

            FileStream    objStream = new FileStream(strPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.Unicode);

            objWriter.Formatting  = Formatting.Indented;
            objWriter.Indentation = 1;
            objWriter.IndentChar  = '\t';
            objWriter.WriteStartDocument();

            // <chummer>
            objWriter.WriteStartElement("chummer");
            // <packs>
            objWriter.WriteStartElement("packs");

            // If this is not a new file, write out the current contents.
            if (!blnNewFile)
            {
                XmlNodeList objXmlNodeList = objXmlCurrentDocument.SelectNodes("/chummer/*");
                foreach (XmlNode objXmlNode in objXmlNodeList)
                {
                    objXmlNode.WriteContentTo(objWriter);
                }
            }

            // <pack>
            objWriter.WriteStartElement("pack");
            // <name />
            objWriter.WriteElementString("name", txtName.Text);
            // <category />
            objWriter.WriteElementString("category", "Custom");

            // Export Attributes.
            if (chkAttributes.Checked)
            {
                int intBOD      = _objCharacter.BOD.Value - (_objCharacter.BOD.MetatypeMinimum - 1);
                int intAGI      = _objCharacter.AGI.Value - (_objCharacter.AGI.MetatypeMinimum - 1);
                int intREA      = _objCharacter.REA.Value - (_objCharacter.REA.MetatypeMinimum - 1);
                int intSTR      = _objCharacter.STR.Value - (_objCharacter.STR.MetatypeMinimum - 1);
                int intCHA      = _objCharacter.CHA.Value - (_objCharacter.CHA.MetatypeMinimum - 1);
                int intINT      = _objCharacter.INT.Value - (_objCharacter.INT.MetatypeMinimum - 1);
                int intLOG      = _objCharacter.LOG.Value - (_objCharacter.LOG.MetatypeMinimum - 1);
                int intWIL      = _objCharacter.WIL.Value - (_objCharacter.WIL.MetatypeMinimum - 1);
                int intEDG      = _objCharacter.EDG.Value - (_objCharacter.EDG.MetatypeMinimum - 1);
                int intMAG      = _objCharacter.MAG.Value - (_objCharacter.MAG.MetatypeMinimum - 1);
                int intMAGAdept = _objCharacter.MAGAdept.Value - (_objCharacter.MAGAdept.MetatypeMinimum - 1);
                int intDEP      = _objCharacter.DEP.Value - (_objCharacter.DEP.MetatypeMinimum - 1);
                int intRES      = _objCharacter.RES.Value - (_objCharacter.RES.MetatypeMinimum - 1);
                // <attributes>
                objWriter.WriteStartElement("attributes");
                objWriter.WriteElementString("bod", intBOD.ToString());
                objWriter.WriteElementString("agi", intAGI.ToString());
                objWriter.WriteElementString("rea", intREA.ToString());
                objWriter.WriteElementString("str", intSTR.ToString());
                objWriter.WriteElementString("cha", intCHA.ToString());
                objWriter.WriteElementString("int", intINT.ToString());
                objWriter.WriteElementString("log", intLOG.ToString());
                objWriter.WriteElementString("wil", intWIL.ToString());
                objWriter.WriteElementString("edg", intEDG.ToString());
                if (_objCharacter.MAGEnabled)
                {
                    objWriter.WriteElementString("mag", intMAG.ToString());
                    if (_objCharacter.Options.MysAdeptSecondMAGAttribute && _objCharacter.IsMysticAdept)
                    {
                        objWriter.WriteElementString("magadept", intMAGAdept.ToString());
                    }
                }
                if (_objCharacter.RESEnabled)
                {
                    objWriter.WriteElementString("res", intRES.ToString());
                }
                if (_objCharacter.DEPEnabled)
                {
                    objWriter.WriteElementString("dep", intDEP.ToString());
                }
                // </attributes>
                objWriter.WriteEndElement();
            }

            // Export Qualities.
            if (chkQualities.Checked)
            {
                bool blnPositive = false;
                bool blnNegative = false;
                // Determine if Positive or Negative Qualities exist.
                foreach (Quality objQuality in _objCharacter.Qualities)
                {
                    if (objQuality.Type == QualityType.Positive)
                    {
                        blnPositive = true;
                    }
                    if (objQuality.Type == QualityType.Negative)
                    {
                        blnNegative = true;
                    }
                    if (blnPositive && blnNegative)
                    {
                        break;
                    }
                }
                // <qualities>
                objWriter.WriteStartElement("qualities");

                // Positive Qualities.
                if (blnPositive)
                {
                    // <positive>
                    objWriter.WriteStartElement("positive");
                    foreach (Quality objQuality in _objCharacter.Qualities)
                    {
                        if (objQuality.Type == QualityType.Positive)
                        {
                            objWriter.WriteStartElement("quality");
                            if (!string.IsNullOrEmpty(objQuality.Extra))
                            {
                                objWriter.WriteAttributeString("select", objQuality.Extra);
                            }
                            objWriter.WriteValue(objQuality.Name);
                            objWriter.WriteEndElement();
                        }
                    }
                    // </positive>
                    objWriter.WriteEndElement();
                }

                // Negative Qualities.
                if (blnPositive)
                {
                    // <negative>
                    objWriter.WriteStartElement("negative");
                    foreach (Quality objQuality in _objCharacter.Qualities)
                    {
                        if (objQuality.Type == QualityType.Negative)
                        {
                            objWriter.WriteStartElement("quality");
                            if (!string.IsNullOrEmpty(objQuality.Extra))
                            {
                                objWriter.WriteAttributeString("select", objQuality.Extra);
                            }
                            objWriter.WriteValue(objQuality.Name);
                            objWriter.WriteEndElement();
                        }
                    }
                    // </negative>
                    objWriter.WriteEndElement();
                }

                // </qualities>
                objWriter.WriteEndElement();
            }

            // Export Starting Nuyen.
            if (chkStartingNuyen.Checked)
            {
                decimal decNuyenBP = _objCharacter.NuyenBP;
                if (_objCharacter.BuildMethod == CharacterBuildMethod.Karma)
                {
                    decNuyenBP /= 2.0m;
                }
                objWriter.WriteElementString("nuyenbp", decNuyenBP.ToString(GlobalOptions.InvariantCultureInfo));
            }

            // Export Active Skills.
            if (chkActiveSkills.Checked)
            {
                // <skills>
                objWriter.WriteStartElement("skills");

                //TODO: Figure out what this did?
                // Active Skills.
                //foreach (Skill objSkill in _objCharacter.Skills)
                //{
                //    if (!objSkill.KnowledgeSkill && !objSkill.IsGrouped && objSkill.Rating > 0)
                //    {
                //        // <skill>
                //        objWriter.WriteStartElement("skill");
                //        objWriter.WriteElementString("name", objSkill.Name);
                //        objWriter.WriteElementString("rating", objSkill.Rating.ToString());
                //        if (!string.IsNullOrEmpty(objSkill.Specialization))
                //            objWriter.WriteElementString("spec", objSkill.Specialization);
                //        // </skill>
                //        objWriter.WriteEndElement();
                //    }
                //}

                // Skill Groups.
                //foreach (SkillGroup objSkillGroup in _objCharacter.SkillGroups)
                //{
                //    if (!objSkillGroup.Broken && objSkillGroup.Rating > 0)
                //    {
                //        // <skillgroup>
                //        objWriter.WriteStartElement("skillgroup");
                //        objWriter.WriteElementString("name", objSkillGroup.Name);
                //        objWriter.WriteElementString("rating", objSkillGroup.Rating.ToString());
                //        // </skillgroup>
                //        objWriter.WriteEndElement();
                //    }
                //}
                // </skills>
                objWriter.WriteEndElement();
            }

            // Export Knowledge Skills.
            if (chkKnowledgeSkills.Checked)
            {
                // <knowledgeskills>
                objWriter.WriteStartElement("knowledgeskills");
                // Active Skills.
                foreach (Skill objSkill in _objCharacter.SkillsSection.Skills)
                {
                    if (objSkill.IsKnowledgeSkill)
                    {
                        // <skill>
                        objWriter.WriteStartElement("skill");
                        objWriter.WriteElementString("name", objSkill.Name);
                        objWriter.WriteElementString("rating", objSkill.Rating.ToString());
                        if (!string.IsNullOrEmpty(objSkill.Specialization))
                        {
                            objWriter.WriteElementString("spec", objSkill.Specialization);
                        }
                        objWriter.WriteElementString("category", objSkill.SkillCategory);
                        // </skill>
                        objWriter.WriteEndElement();
                    }
                }
                // </knowledgeskills>
                objWriter.WriteEndElement();
            }

            // Export Martial Arts.
            if (chkMartialArts.Checked)
            {
                // <martialarts>
                objWriter.WriteStartElement("martialarts");
                foreach (MartialArt objArt in _objCharacter.MartialArts)
                {
                    // <martialart>
                    objWriter.WriteStartElement("martialart");
                    objWriter.WriteElementString("name", objArt.Name);
                    objWriter.WriteElementString("rating", objArt.Rating.ToString());
                    if (objArt.Advantages.Count > 0)
                    {
                        // <advantages>
                        objWriter.WriteStartElement("advantages");
                        foreach (MartialArtAdvantage objAdvantage in objArt.Advantages)
                        {
                            objWriter.WriteElementString("advantage", objAdvantage.Name);
                        }
                        // </advantages>
                        objWriter.WriteEndElement();
                    }
                    // </martialart>
                    objWriter.WriteEndElement();
                }
                foreach (MartialArtManeuver objManeuver in _objCharacter.MartialArtManeuvers)
                {
                    objWriter.WriteElementString("maneuver", objManeuver.Name);
                }
                // </martialarts>
                objWriter.WriteEndElement();
            }

            // Export Spells.
            if (chkSpells.Checked)
            {
                // <spells>
                objWriter.WriteStartElement("spells");
                foreach (Spell objSpell in _objCharacter.Spells)
                {
                    objWriter.WriteStartElement("spell");
                    if (!string.IsNullOrEmpty(objSpell.Extra))
                    {
                        objWriter.WriteAttributeString("select", objSpell.Extra);
                    }
                    objWriter.WriteValue(objSpell.Name);
                    objWriter.WriteEndElement();
                }
                // </spells>
                objWriter.WriteEndElement();
            }

            // Export Complex Forms.
            if (chkComplexForms.Checked)
            {
                // <programs>
                objWriter.WriteStartElement("complexforms");
                foreach (ComplexForm objProgram in _objCharacter.ComplexForms)
                {
                    // <program>
                    objWriter.WriteStartElement("complexform");
                    objWriter.WriteStartElement("name");
                    objWriter.WriteValue(objProgram.Name);
                    objWriter.WriteEndElement();
                    // </program>
                    objWriter.WriteEndElement();
                }
                // </programs>
                objWriter.WriteEndElement();
            }

            // Export Cyberware/Bioware.
            if (chkCyberware.Checked)
            {
                bool blnCyberware = false;
                bool blnBioware   = false;
                foreach (Cyberware objCharacterCyberware in _objCharacter.Cyberware)
                {
                    if (objCharacterCyberware.SourceType == Improvement.ImprovementSource.Bioware)
                    {
                        blnBioware = true;
                    }
                    if (objCharacterCyberware.SourceType == Improvement.ImprovementSource.Cyberware)
                    {
                        blnCyberware = true;
                    }
                    if (blnCyberware && blnBioware)
                    {
                        break;
                    }
                }

                if (blnCyberware)
                {
                    // <cyberwares>
                    objWriter.WriteStartElement("cyberwares");
                    foreach (Cyberware objCyberware in _objCharacter.Cyberware)
                    {
                        if (objCyberware.SourceType == Improvement.ImprovementSource.Cyberware)
                        {
                            // <cyberware>
                            objWriter.WriteStartElement("cyberware");
                            objWriter.WriteElementString("name", objCyberware.Name);
                            if (objCyberware.Rating > 0)
                            {
                                objWriter.WriteElementString("rating", objCyberware.Rating.ToString());
                            }
                            objWriter.WriteElementString("grade", objCyberware.Grade.Name);
                            if (objCyberware.Children.Count > 0)
                            {
                                // <cyberwares>
                                objWriter.WriteStartElement("cyberwares");
                                foreach (Cyberware objChildCyberware in objCyberware.Children)
                                {
                                    if (objChildCyberware.Capacity != "[*]")
                                    {
                                        // <cyberware>
                                        objWriter.WriteStartElement("cyberware");
                                        objWriter.WriteElementString("name", objChildCyberware.Name);
                                        if (objChildCyberware.Rating > 0)
                                        {
                                            objWriter.WriteElementString("rating", objChildCyberware.Rating.ToString());
                                        }

                                        if (objChildCyberware.Gear.Count > 0)
                                        {
                                            WriteGear(objWriter, objChildCyberware.Gear);
                                        }
                                        // </cyberware>
                                        objWriter.WriteEndElement();
                                    }
                                }
                                // </cyberwares>
                                objWriter.WriteEndElement();
                            }

                            if (objCyberware.Gear.Count > 0)
                            {
                                WriteGear(objWriter, objCyberware.Gear);
                            }

                            // </cyberware>
                            objWriter.WriteEndElement();
                        }
                    }
                    // </cyberwares>
                    objWriter.WriteEndElement();
                }

                if (blnBioware)
                {
                    // <biowares>
                    objWriter.WriteStartElement("biowares");
                    foreach (Cyberware objCyberware in _objCharacter.Cyberware)
                    {
                        if (objCyberware.SourceType == Improvement.ImprovementSource.Bioware)
                        {
                            // <bioware>
                            objWriter.WriteStartElement("bioware");
                            objWriter.WriteElementString("name", objCyberware.Name);
                            if (objCyberware.Rating > 0)
                            {
                                objWriter.WriteElementString("rating", objCyberware.Rating.ToString());
                            }
                            objWriter.WriteElementString("grade", objCyberware.Grade.ToString());

                            if (objCyberware.Gear.Count > 0)
                            {
                                WriteGear(objWriter, objCyberware.Gear);
                            }
                            // </bioware>
                            objWriter.WriteEndElement();
                        }
                    }
                    // </biowares>
                    objWriter.WriteEndElement();
                }
            }

            // Export Lifestyle.
            if (chkLifestyle.Checked)
            {
                // <lifestyles>
                objWriter.WriteStartElement("lifestyles");
                foreach (Lifestyle objLifestyle in _objCharacter.Lifestyles)
                {
                    // <lifestyle>
                    objWriter.WriteStartElement("lifestyle");
                    objWriter.WriteElementString("name", objLifestyle.Name);
                    objWriter.WriteElementString("months", objLifestyle.Months.ToString());
                    if (!string.IsNullOrEmpty(objLifestyle.BaseLifestyle))
                    {
                        // This is an Advanced Lifestyle, so write out its properties.
                        objWriter.WriteElementString("cost", objLifestyle.Cost.ToString());
                        objWriter.WriteElementString("dice", objLifestyle.Dice.ToString());
                        objWriter.WriteElementString("multiplier", objLifestyle.Multiplier.ToString());
                        objWriter.WriteElementString("baselifestyle", objLifestyle.BaseLifestyle);
                        if (objLifestyle.LifestyleQualities.Count > 0)
                        {
                            // <qualities>
                            objWriter.WriteStartElement("qualities");
                            foreach (LifestyleQuality objQuality in objLifestyle.LifestyleQualities)
                            {
                                objWriter.WriteElementString("quality", objQuality.Name);
                            }
                            // </qualities>
                            objWriter.WriteEndElement();
                        }
                    }
                    // </lifestyle>
                    objWriter.WriteEndElement();
                }
                // </lifestyles>
                objWriter.WriteEndElement();
            }

            // Export Armor.
            if (chkArmor.Checked)
            {
                // <armors>
                objWriter.WriteStartElement("armors");
                foreach (Armor objArmor in _objCharacter.Armor)
                {
                    // <armor>
                    objWriter.WriteStartElement("armor");
                    objWriter.WriteElementString("name", objArmor.Name);
                    if (objArmor.ArmorMods.Count > 0)
                    {
                        // <mods>
                        objWriter.WriteStartElement("mods");
                        foreach (ArmorMod objMod in objArmor.ArmorMods)
                        {
                            // <mod>
                            objWriter.WriteStartElement("mod");
                            objWriter.WriteElementString("name", objMod.Name);
                            if (objMod.Rating > 0)
                            {
                                objWriter.WriteElementString("rating", objMod.Rating.ToString());
                            }
                            // </mod>
                            objWriter.WriteEndElement();
                        }
                        // </mods>
                        objWriter.WriteEndElement();
                    }

                    if (objArmor.Gear.Count > 0)
                    {
                        WriteGear(objWriter, objArmor.Gear);
                    }

                    // </armor>
                    objWriter.WriteEndElement();
                }
                // </armors>
                objWriter.WriteEndElement();
            }

            // Export Weapons.
            if (chkWeapons.Checked)
            {
                // <weapons>
                objWriter.WriteStartElement("weapons");
                foreach (Weapon objWeapon in _objCharacter.Weapons)
                {
                    // Don't attempt to export Cyberware and Gear Weapons since those are handled by those object types. The default Unarmed Attack Weapon should also not be exported.
                    if (objWeapon.Category != "Cyberware" && objWeapon.Category != "Gear" && objWeapon.Name != "Unarmed Attack")
                    {
                        // <weapon>
                        objWriter.WriteStartElement("weapon");
                        objWriter.WriteElementString("name", objWeapon.Name);

                        // Weapon Accessories.
                        if (objWeapon.WeaponAccessories.Count > 0)
                        {
                            // <accessories>
                            objWriter.WriteStartElement("accessories");
                            foreach (WeaponAccessory objAccessory in objWeapon.WeaponAccessories)
                            {
                                // Don't attempt to export items included in the Weapon.
                                if (!objAccessory.IncludedInWeapon)
                                {
                                    // <accessory>
                                    objWriter.WriteStartElement("accessory");
                                    objWriter.WriteElementString("name", objAccessory.Name);
                                    objWriter.WriteElementString("mount", objAccessory.Mount);
                                    objWriter.WriteElementString("extramount", objAccessory.ExtraMount);

                                    if (objAccessory.Gear.Count > 0)
                                    {
                                        WriteGear(objWriter, objAccessory.Gear);
                                    }

                                    // </accessory>
                                    objWriter.WriteEndElement();
                                }
                            }
                            // </accessories>
                            objWriter.WriteEndElement();
                        }

                        // Underbarrel Weapon.
                        if (objWeapon.UnderbarrelWeapons.Count > 0)
                        {
                            foreach (Weapon objUnderbarrelWeapon in objWeapon.UnderbarrelWeapons)
                            {
                                if (!objUnderbarrelWeapon.IncludedInWeapon)
                                {
                                    objWriter.WriteElementString("underbarrel", objUnderbarrelWeapon.Name);
                                }
                            }
                        }

                        // </weapon>
                        objWriter.WriteEndElement();
                    }
                }
                // </weapons>
                objWriter.WriteEndElement();
            }

            // Export Gear.
            if (chkGear.Checked)
            {
                WriteGear(objWriter, _objCharacter.Gear);
            }

            // Export Vehicles.
            if (chkVehicles.Checked)
            {
                // <vehicles>
                objWriter.WriteStartElement("vehicles");
                foreach (Vehicle objVehicle in _objCharacter.Vehicles)
                {
                    bool blnWeapons = false;
                    // <vehicle>
                    objWriter.WriteStartElement("vehicle");
                    objWriter.WriteElementString("name", objVehicle.Name);
                    if (objVehicle.Mods.Count > 0)
                    {
                        // <mods>
                        objWriter.WriteStartElement("mods");
                        foreach (VehicleMod objVehicleMod in objVehicle.Mods)
                        {
                            // Only write out the Mods that are not part of the base vehicle.
                            if (!objVehicleMod.IncludedInVehicle)
                            {
                                // <mod>
                                objWriter.WriteStartElement("mod");
                                objWriter.WriteElementString("name", objVehicleMod.Name);
                                if (objVehicleMod.Rating > 0)
                                {
                                    objWriter.WriteElementString("rating", objVehicleMod.Rating.ToString());
                                }
                                // </mod>
                                objWriter.WriteEndElement();

                                // See if this is a Weapon Mount with Weapons.
                                if (objVehicleMod.Weapons.Count > 0)
                                {
                                    blnWeapons = true;
                                }
                            }
                            else
                            {
                                // See if this is a Weapon Mount with Weapons.
                                if (objVehicleMod.Weapons.Count > 0)
                                {
                                    blnWeapons = true;
                                }
                            }
                        }
                        // </mods>
                        objWriter.WriteEndElement();
                    }

                    // If there are Weapons, add them.
                    if (blnWeapons)
                    {
                        // <weapons>
                        objWriter.WriteStartElement("weapons");
                        foreach (VehicleMod objVehicleMod in objVehicle.Mods)
                        {
                            foreach (Weapon objWeapon in objVehicleMod.Weapons)
                            {
                                // <weapon>
                                objWriter.WriteStartElement("weapon");
                                objWriter.WriteElementString("name", objWeapon.Name);

                                // Weapon Accessories.
                                if (objWeapon.WeaponAccessories.Count > 0)
                                {
                                    // <accessories>
                                    objWriter.WriteStartElement("accessories");
                                    foreach (WeaponAccessory objAccessory in objWeapon.WeaponAccessories)
                                    {
                                        // Don't attempt to export items included in the Weapon.
                                        if (!objAccessory.IncludedInWeapon)
                                        {
                                            // <accessory>
                                            objWriter.WriteStartElement("accessory");
                                            objWriter.WriteElementString("name", objAccessory.Name);
                                            objWriter.WriteElementString("mount", objAccessory.Mount);
                                            objWriter.WriteElementString("extramount", objAccessory.ExtraMount);
                                            // </accessory>
                                            objWriter.WriteEndElement();
                                        }
                                    }
                                    // </accessories>
                                    objWriter.WriteEndElement();
                                }

                                // Underbarrel Weapon.
                                if (objWeapon.UnderbarrelWeapons.Count > 0)
                                {
                                    foreach (Weapon objUnderbarrelWeapon in objWeapon.UnderbarrelWeapons)
                                    {
                                        objWriter.WriteElementString("underbarrel", objUnderbarrelWeapon.Name);
                                    }
                                }

                                // </weapon>
                                objWriter.WriteEndElement();
                            }
                        }
                        // </weapons>
                        objWriter.WriteEndElement();
                    }

                    // Gear.
                    if (objVehicle.Gear.Count > 0)
                    {
                        WriteGear(objWriter, objVehicle.Gear);
                    }
                    // </vehicle>
                    objWriter.WriteEndElement();
                }
                // </vehicles>
                objWriter.WriteEndElement();
            }

            // </pack>
            objWriter.WriteEndElement();
            // </packs>
            objWriter.WriteEndElement();
            // </chummer>
            objWriter.WriteEndElement();

            objWriter.WriteEndDocument();
            objWriter.Close();

            MessageBox.Show(LanguageManager.GetString("Message_CreatePACKSKit_SuiteCreated").Replace("{0}", txtName.Text), LanguageManager.GetString("MessageTitle_CreatePACKSKit_SuiteCreated"), MessageBoxButtons.OK, MessageBoxIcon.Information);
            DialogResult = DialogResult.OK;
        }
        /// <summary>
        /// </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)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Entity,
                        RetrieveAsIfPublished = true
                    };

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


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

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

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

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

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

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                metadataWriter.WriteElementString("OTC", currentEntity.ObjectTypeCode.ToString());
                                metadataWriter.WriteElementString("OwnershipType", currentEntity.OwnershipType.Value.ToString());
                                if (currentEntity.DisplayName.UserLocalizedLabel != null)
                                {
                                    metadataWriter.WriteElementString("DisplayName", currentEntity.DisplayName.UserLocalizedLabel.Label);
                                }
                                if (currentEntity.DisplayCollectionName.UserLocalizedLabel != null)
                                {
                                    metadataWriter.WriteElementString("DisplayCollectionName", currentEntity.DisplayCollectionName.UserLocalizedLabel.Label);
                                }
                                metadataWriter.WriteElementString("IntroducedVersion", currentEntity.IntroducedVersion.ToString());
                                metadataWriter.WriteElementString("AutoRouteToOwnerQueue", currentEntity.AutoRouteToOwnerQueue.ToString());
                                metadataWriter.WriteElementString("CanBeInManyToMany", currentEntity.CanBeInManyToMany.Value.ToString());
                                metadataWriter.WriteElementString("CanBePrimaryEntityInRelationship", currentEntity.CanBePrimaryEntityInRelationship.Value.ToString());
                                metadataWriter.WriteElementString("CanBeRelatedEntityInRelationship", currentEntity.CanBeRelatedEntityInRelationship.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateAttributes", currentEntity.CanCreateAttributes.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateCharts", currentEntity.CanCreateCharts.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateForms", currentEntity.CanCreateForms.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateViews", currentEntity.CanCreateViews.Value.ToString());
                                metadataWriter.WriteElementString("CanModifyAdditionalSettings", currentEntity.CanModifyAdditionalSettings.Value.ToString());
                                metadataWriter.WriteElementString("CanTriggerWorkflow", currentEntity.CanTriggerWorkflow.Value.ToString());

                                metadataWriter.WriteElementString("IsActivity", currentEntity.IsActivity.Value.ToString());
                                //metadataWriter.WriteElementString("ActivityTypeMask", currentEntity.ActivityTypeMask.ToString());

                                metadataWriter.WriteElementString("IsActivityParty", currentEntity.IsActivityParty.Value.ToString());

                                metadataWriter.WriteElementString("IsAuditEnabled", currentEntity.IsAuditEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsAvailableOffline", currentEntity.IsAvailableOffline.ToString());
                                metadataWriter.WriteElementString("IsChildEntity", currentEntity.IsChildEntity.ToString());
                                metadataWriter.WriteElementString("IsConnectionsEnabled", currentEntity.IsConnectionsEnabled.ManagedPropertyLogicalName.ToString());
                                metadataWriter.WriteElementString("IsCustomEntity", currentEntity.IsCustomEntity.Value.ToString());
                                metadataWriter.WriteElementString("IsCustomizable", currentEntity.IsCustomizable.Value.ToString());

                                metadataWriter.WriteElementString("IsDocumentManagementEnabled", currentEntity.IsDocumentManagementEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsDuplicateDetectionEnabled", currentEntity.IsDuplicateDetectionEnabled.Value.ToString());
                                if (currentEntity.IsEnabledForCharts != null)
                                {
                                    metadataWriter.WriteElementString("IsEnabledForCharts", currentEntity.IsEnabledForCharts.Value.ToString());
                                }
                                metadataWriter.WriteElementString("IsImportable", currentEntity.IsImportable.Value.ToString());
                                metadataWriter.WriteElementString("IsIntersect", currentEntity.IsIntersect.Value.ToString());

                                metadataWriter.WriteElementString("IsMailMergeEnabled", currentEntity.IsMailMergeEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsManaged", currentEntity.IsManaged.Value.ToString());
                                metadataWriter.WriteElementString("IsMappable", currentEntity.IsMappable.Value.ToString());

                                metadataWriter.WriteElementString("IsReadingPaneEnabled", currentEntity.IsReadingPaneEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsRenameable", currentEntity.IsRenameable.Value.ToString());
                                metadataWriter.WriteElementString("IsValidForAdvancedFind", currentEntity.IsValidForAdvancedFind.Value.ToString());
                                metadataWriter.WriteElementString("IsValidForQueue", currentEntity.IsValidForQueue.Value.ToString());
                                metadataWriter.WriteElementString("IsVisibleInMobile", currentEntity.IsVisibleInMobile.Value.ToString());

                                metadataWriter.WriteElementString("PrimaryIdAttribute", currentEntity.PrimaryIdAttribute);
                                metadataWriter.WriteElementString("PrimaryNameAttribute", currentEntity.PrimaryNameAttribute);
                                metadataWriter.WriteElementString("ReportViewName", currentEntity.ReportViewName);
                                metadataWriter.WriteElementString("RecurrenceBaseEntityLogicalName", currentEntity.RecurrenceBaseEntityLogicalName);
                                if (currentEntity.Description.UserLocalizedLabel != null)
                                {
                                    metadataWriter.WriteElementString("Description", currentEntity.Description.UserLocalizedLabel.Label);
                                }



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

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

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



                    Console.WriteLine("Done.");

                    //DeleteRequiredRecords(promptForDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemplo n.º 41
0
        private void WritePackageInfo(XmlTextWriter writer)
        {
            foreach (var package in this.ChainPackages)
            {
                if (!this.PackagesPayloads.TryGetValue(package.PackageId, out var payloads))
                {
                    continue;
                }

                var packagePayload = payloads[package.PackageSymbol.PayloadRef];

                var size = package.PackageSymbol.Size.ToString(CultureInfo.InvariantCulture);

                writer.WriteStartElement("WixPackageProperties");

                writer.WriteAttributeString("Package", package.PackageId);
                writer.WriteAttributeString("Vital", package.PackageSymbol.Vital == true ? "yes" : "no");

                if (!String.IsNullOrEmpty(package.PackageSymbol.DisplayName))
                {
                    writer.WriteAttributeString("DisplayName", package.PackageSymbol.DisplayName);
                }

                if (!String.IsNullOrEmpty(package.PackageSymbol.Description))
                {
                    writer.WriteAttributeString("Description", package.PackageSymbol.Description);
                }

                writer.WriteAttributeString("DownloadSize", size);
                writer.WriteAttributeString("PackageSize", size);
                writer.WriteAttributeString("InstalledSize", package.PackageSymbol.InstallSize?.ToString(CultureInfo.InvariantCulture) ?? size);
                writer.WriteAttributeString("PackageType", package.PackageSymbol.Type.ToString());
                writer.WriteAttributeString("Permanent", package.PackageSymbol.Permanent ? "yes" : "no");
                writer.WriteAttributeString("LogPathVariable", package.PackageSymbol.LogPathVariable);
                writer.WriteAttributeString("RollbackLogPathVariable", package.PackageSymbol.RollbackLogPathVariable);
                writer.WriteAttributeString("Compressed", packagePayload.Packaging == PackagingType.Embedded ? "yes" : "no");

                if (package.SpecificPackageSymbol is WixBundleMsiPackageSymbol msiPackage)
                {
                    if (!String.IsNullOrEmpty(msiPackage.ProductCode))
                    {
                        writer.WriteAttributeString("ProductCode", msiPackage.ProductCode);
                    }

                    if (!String.IsNullOrEmpty(msiPackage.UpgradeCode))
                    {
                        writer.WriteAttributeString("UpgradeCode", msiPackage.UpgradeCode);
                    }
                }
                else if (package.SpecificPackageSymbol is WixBundleMspPackageSymbol mspPackage)
                {
                    if (!String.IsNullOrEmpty(mspPackage.PatchCode))
                    {
                        writer.WriteAttributeString("ProductCode", mspPackage.PatchCode);
                    }
                }

                if (!String.IsNullOrEmpty(package.PackageSymbol.Version))
                {
                    writer.WriteAttributeString("Version", package.PackageSymbol.Version);
                }

                if (!String.IsNullOrEmpty(package.PackageSymbol.InstallCondition))
                {
                    writer.WriteAttributeString("InstallCondition", package.PackageSymbol.InstallCondition);
                }

                switch (package.PackageSymbol.Cache)
                {
                case BundleCacheType.Remove:
                    writer.WriteAttributeString("Cache", "remove");
                    break;

                case BundleCacheType.Keep:
                    writer.WriteAttributeString("Cache", "keep");
                    break;

                case BundleCacheType.Force:
                    writer.WriteAttributeString("Cache", "force");
                    break;
                }

                writer.WriteEndElement();
            }
        }
        public override void Save(InvoiceDescriptor descriptor, Stream stream)
        {
            if (!stream.CanWrite || !stream.CanSeek)
            {
                throw new IllegalStreamException("Cannot write to stream");
            }

            long streamPosition = stream.Position;

            this.Descriptor   = descriptor;
            this.Writer       = new XmlTextWriter(stream, Encoding.UTF8);
            Writer.Formatting = Formatting.Indented;
            Writer.WriteStartDocument();

            #region Kopfbereich
            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", this.Descriptor.IsTest ? "true" : "false");
            Writer.WriteEndElement(); // !ram:TestIndicator
            Writer.WriteStartElement("ram:GuidelineSpecifiedDocumentContextParameter");
            Writer.WriteElementString("ram:ID", this.Descriptor.Profile.EnumToString(ZUGFeRDVersion.Version1));
            Writer.WriteEndElement(); // !ram:GuidelineSpecifiedDocumentContextParameter
            Writer.WriteEndElement(); // !rsm:SpecifiedExchangedDocumentContext

            Writer.WriteStartElement("rsm:HeaderExchangedDocument");
            Writer.WriteElementString("ram:ID", this.Descriptor.InvoiceNo);
            Writer.WriteElementString("ram:Name", _translateInvoiceType(this.Descriptor.Type));
            Writer.WriteElementString("ram:TypeCode", String.Format("{0}", _encodeInvoiceType(this.Descriptor.Type)));

            if (this.Descriptor.InvoiceDate.HasValue)
            {
                Writer.WriteStartElement("ram:IssueDateTime");
                Writer.WriteStartElement("udt:DateTimeString");
                Writer.WriteAttributeString("format", "102");
                Writer.WriteValue(_formatDate(this.Descriptor.InvoiceDate.Value));
                Writer.WriteEndElement(); // !udt:DateTimeString
                Writer.WriteEndElement(); // !IssueDateTime
            }
            _writeNotes(Writer, this.Descriptor.Notes);
            Writer.WriteEndElement(); // !rsm:HeaderExchangedDocument
            #endregion

            #region SpecifiedSupplyChainTradeTransaction
            Writer.WriteStartElement("rsm:SpecifiedSupplyChainTradeTransaction");
            Writer.WriteStartElement("ram:ApplicableSupplyChainTradeAgreement");
            if (!String.IsNullOrEmpty(this.Descriptor.ReferenceOrderNo))
            {
                Writer.WriteElementString("ram:BuyerReference", this.Descriptor.ReferenceOrderNo);
            }

            _writeOptionalParty(Writer, "ram:SellerTradeParty", this.Descriptor.Seller, this.Descriptor.SellerContact, TaxRegistrations: this.Descriptor.SellerTaxRegistration);
            _writeOptionalParty(Writer, "ram:BuyerTradeParty", this.Descriptor.Buyer, this.Descriptor.BuyerContact, TaxRegistrations: this.Descriptor.BuyerTaxRegistration);

            if (this.Descriptor.OrderDate.HasValue || ((this.Descriptor.OrderNo != null) && (this.Descriptor.OrderNo.Length > 0)))
            {
                Writer.WriteStartElement("ram:BuyerOrderReferencedDocument");
                if (this.Descriptor.OrderDate.HasValue)
                {
                    Writer.WriteStartElement("ram:IssueDateTime");
                    //Writer.WriteStartElement("udt:DateTimeString");
                    //Writer.WriteAttributeString("format", "102");
                    Writer.WriteValue(_formatDate(this.Descriptor.OrderDate.Value, false));
                    //Writer.WriteEndElement(); // !udt:DateTimeString
                    Writer.WriteEndElement(); // !IssueDateTime()
                }

                Writer.WriteElementString("ram:ID", this.Descriptor.OrderNo);
                Writer.WriteEndElement(); // !BuyerOrderReferencedDocument
            }

            if (this.Descriptor.AdditionalReferencedDocument != null)
            {
                Writer.WriteStartElement("ram:AdditionalReferencedDocument");
                if (this.Descriptor.AdditionalReferencedDocument.IssueDateTime.HasValue)
                {
                    Writer.WriteStartElement("ram:IssueDateTime");
                    //Writer.WriteStartElement("udt:DateTimeString");
                    //Writer.WriteAttributeString("format", "102");
                    Writer.WriteValue(_formatDate(this.Descriptor.AdditionalReferencedDocument.IssueDateTime.Value, false));
                    //Writer.WriteEndElement(); // !udt:DateTimeString
                    Writer.WriteEndElement(); // !IssueDateTime()
                }

                if (this.Descriptor.AdditionalReferencedDocument.ReferenceTypeCode != ReferenceTypeCodes.Unknown)
                {
                    Writer.WriteElementString("ram:TypeCode", this.Descriptor.AdditionalReferencedDocument.ReferenceTypeCode.EnumToString());
                }

                Writer.WriteElementString("ram:ID", this.Descriptor.AdditionalReferencedDocument.ID);
                Writer.WriteEndElement(); // !ram:AdditionalReferencedDocument
            }

            Writer.WriteEndElement();                                           // !ApplicableSupplyChainTradeAgreement

            Writer.WriteStartElement("ram:ApplicableSupplyChainTradeDelivery"); // Pflichteintrag
            if (this.Descriptor.ActualDeliveryDate.HasValue)
            {
                Writer.WriteStartElement("ram:ActualDeliverySupplyChainEvent");
                Writer.WriteStartElement("ram:OccurrenceDateTime");
                Writer.WriteStartElement("udt:DateTimeString");
                Writer.WriteAttributeString("format", "102");
                Writer.WriteValue(_formatDate(this.Descriptor.ActualDeliveryDate.Value));
                Writer.WriteEndElement(); // "udt:DateTimeString
                Writer.WriteEndElement(); // !OccurrenceDateTime()
                Writer.WriteEndElement(); // !ActualDeliverySupplyChainEvent
            }

            if (this.Descriptor.DeliveryNoteReferencedDocument != null)
            {
                Writer.WriteStartElement("ram:DeliveryNoteReferencedDocument");

                if (this.Descriptor.DeliveryNoteReferencedDocument.IssueDateTime.HasValue)
                {
                    Writer.WriteStartElement("ram:IssueDateTime");
                    Writer.WriteValue(_formatDate(this.Descriptor.DeliveryNoteReferencedDocument.IssueDateTime.Value, false));
                    Writer.WriteEndElement(); // !IssueDateTime
                }

                Writer.WriteElementString("ram:ID", this.Descriptor.DeliveryNoteReferencedDocument.ID);
                Writer.WriteEndElement(); // !DeliveryNoteReferencedDocument
            }

            Writer.WriteEndElement(); // !ApplicableSupplyChainTradeDelivery

            Writer.WriteStartElement("ram:ApplicableSupplyChainTradeSettlement");
            if (!String.IsNullOrEmpty(this.Descriptor.InvoiceNoAsReference))
            {
                _writeOptionalElementString(Writer, "ram:PaymentReference", this.Descriptor.InvoiceNoAsReference);
            }
            Writer.WriteElementString("ram:InvoiceCurrencyCode", this.Descriptor.Currency.EnumToString());

            if ((this.Descriptor.CreditorBankAccounts.Count > 0) || (this.Descriptor.PaymentMeans != null))
            {
                Writer.WriteStartElement("ram:SpecifiedTradeSettlementPaymentMeans");

                if ((this.Descriptor.PaymentMeans != null) && (this.Descriptor.PaymentMeans.TypeCode != PaymentMeansTypeCodes.Unknown))
                {
                    Writer.WriteElementString("ram:TypeCode", this.Descriptor.PaymentMeans.TypeCode.EnumToString());
                    Writer.WriteElementString("ram:Information", this.Descriptor.PaymentMeans.Information);

                    if (!String.IsNullOrEmpty(this.Descriptor.PaymentMeans.SEPACreditorIdentifier) && !String.IsNullOrEmpty(this.Descriptor.PaymentMeans.SEPAMandateReference))
                    {
                        Writer.WriteStartElement("ram:ID");
                        Writer.WriteAttributeString("schemeAgencyID", this.Descriptor.PaymentMeans.SEPACreditorIdentifier);
                        Writer.WriteValue(this.Descriptor.PaymentMeans.SEPAMandateReference);
                        Writer.WriteEndElement(); // !ram:ID
                    }
                }

                foreach (BankAccount account in this.Descriptor.CreditorBankAccounts)
                {
                    Writer.WriteStartElement("ram:PayeePartyCreditorFinancialAccount");
                    Writer.WriteElementString("ram:IBANID", account.IBAN);
                    if (!String.IsNullOrEmpty(account.ID))
                    {
                        Writer.WriteElementString("ram:ProprietaryID", account.ID);
                    }
                    Writer.WriteEndElement(); // !PayeePartyCreditorFinancialAccount

                    Writer.WriteStartElement("ram:PayeeSpecifiedCreditorFinancialInstitution");
                    Writer.WriteElementString("ram:BICID", account.BIC);

                    if (!String.IsNullOrEmpty(account.Bankleitzahl))
                    {
                        Writer.WriteElementString("ram:GermanBankleitzahlID", account.Bankleitzahl);
                    }

                    if (!String.IsNullOrEmpty(account.BankName))
                    {
                        Writer.WriteElementString("ram:Name", account.BankName);
                    }
                    Writer.WriteEndElement(); // !PayeeSpecifiedCreditorFinancialInstitution
                }

                foreach (BankAccount account in this.Descriptor.DebitorBankAccounts)
                {
                    Writer.WriteStartElement("ram:PayerPartyDebtorFinancialAccount");
                    Writer.WriteElementString("ram:IBANID", account.IBAN);
                    if (!String.IsNullOrEmpty(account.ID))
                    {
                        Writer.WriteElementString("ram:ProprietaryID", account.ID);
                    }
                    Writer.WriteEndElement(); // !PayerPartyDebtorFinancialAccount

                    Writer.WriteStartElement("ram:PayerSpecifiedDebtorFinancialInstitution");
                    Writer.WriteElementString("ram:BICID", account.BIC);

                    if (!String.IsNullOrEmpty(account.Bankleitzahl))
                    {
                        Writer.WriteElementString("ram:GermanBankleitzahlID", account.Bankleitzahl);
                    }

                    if (!String.IsNullOrEmpty(account.BankName))
                    {
                        Writer.WriteElementString("ram:Name", account.BankName);
                    }
                    Writer.WriteEndElement(); // !PayerSpecifiedDebtorFinancialInstitution
                }

                Writer.WriteEndElement(); // !SpecifiedTradeSettlementPaymentMeans
            }


            /**
             * @todo add writer for this:
             * <SpecifiedTradeSettlementPaymentMeans>
             * <TypeCode>42</TypeCode>
             *  <Information>Überweisung</Information>
             * <PayeePartyCreditorFinancialAccount>
             *      <IBANID>DE08700901001234567890</IBANID>
             *      <ProprietaryID>1234567890</ProprietaryID>
             *  </PayeePartyCreditorFinancialAccount>
             *  <PayeeSpecifiedCreditorFinancialInstitution>
             *      <BICID>GENODEF1M04</BICID>
             *      <GermanBankleitzahlID>70090100</GermanBankleitzahlID>
             *      <Name>Hausbank München</Name>
             *  </PayeeSpecifiedCreditorFinancialInstitution>
             * </SpecifiedTradeSettlementPaymentMeans>
             */

            _writeOptionalTaxes(Writer);

            if ((this.Descriptor.TradeAllowanceCharges != null) && (this.Descriptor.TradeAllowanceCharges.Count > 0))
            {
                foreach (TradeAllowanceCharge tradeAllowanceCharge in this.Descriptor.TradeAllowanceCharges)
                {
                    Writer.WriteStartElement("ram:SpecifiedTradeAllowanceCharge");
                    Writer.WriteStartElement("ram:ChargeIndicator");
                    Writer.WriteElementString("udt:Indicator", tradeAllowanceCharge.ChargeIndicator ? "true" : "false");
                    Writer.WriteEndElement(); // !ram:ChargeIndicator

                    Writer.WriteStartElement("ram:BasisAmount");
                    Writer.WriteAttributeString("currencyID", tradeAllowanceCharge.Currency.EnumToString());
                    Writer.WriteValue(_formatDecimal(tradeAllowanceCharge.BasisAmount));
                    Writer.WriteEndElement();

                    Writer.WriteStartElement("ram:ActualAmount");
                    Writer.WriteAttributeString("currencyID", tradeAllowanceCharge.Currency.EnumToString());
                    Writer.WriteValue(_formatDecimal(tradeAllowanceCharge.ActualAmount, 2));
                    Writer.WriteEndElement();


                    _writeOptionalElementString(Writer, "ram:Reason", tradeAllowanceCharge.Reason);

                    if (tradeAllowanceCharge.Tax != null)
                    {
                        Writer.WriteStartElement("ram:CategoryTradeTax");
                        Writer.WriteElementString("ram:TypeCode", tradeAllowanceCharge.Tax.TypeCode.EnumToString());
                        if (tradeAllowanceCharge.Tax.CategoryCode.HasValue)
                        {
                            Writer.WriteElementString("ram:CategoryCode", tradeAllowanceCharge.Tax.CategoryCode?.EnumToString());
                        }
                        Writer.WriteElementString("ram:ApplicablePercent", _formatDecimal(tradeAllowanceCharge.Tax.Percent));
                        Writer.WriteEndElement();
                    }
                    Writer.WriteEndElement();
                }
            }

            if ((this.Descriptor.ServiceCharges != null) && (this.Descriptor.ServiceCharges.Count > 0))
            {
                foreach (ServiceCharge serviceCharge in this.Descriptor.ServiceCharges)
                {
                    Writer.WriteStartElement("ram:SpecifiedLogisticsServiceCharge");
                    if (!String.IsNullOrEmpty(serviceCharge.Description))
                    {
                        Writer.WriteElementString("ram:Description", serviceCharge.Description);
                    }
                    Writer.WriteElementString("ram:AppliedAmount", _formatDecimal(serviceCharge.Amount));
                    if (serviceCharge.Tax != null)
                    {
                        Writer.WriteStartElement("ram:AppliedTradeTax");
                        Writer.WriteElementString("ram:TypeCode", serviceCharge.Tax.TypeCode.EnumToString());
                        if (serviceCharge.Tax.CategoryCode.HasValue)
                        {
                            Writer.WriteElementString("ram:CategoryCode", serviceCharge.Tax.CategoryCode?.EnumToString());
                        }
                        Writer.WriteElementString("ram:ApplicablePercent", _formatDecimal(serviceCharge.Tax.Percent));
                        Writer.WriteEndElement();
                    }
                    Writer.WriteEndElement();
                }
            }

            if (this.Descriptor.PaymentTerms != null)
            {
                Writer.WriteStartElement("ram:SpecifiedTradePaymentTerms");
                _writeOptionalElementString(Writer, "ram:Description", this.Descriptor.PaymentTerms.Description);
                if (this.Descriptor.PaymentTerms.DueDate.HasValue)
                {
                    Writer.WriteStartElement("ram:DueDateDateTime");
                    _writeElementWithAttribute(Writer, "udt:DateTimeString", "format", "102", _formatDate(this.Descriptor.PaymentTerms.DueDate.Value));
                    Writer.WriteEndElement(); // !ram:DueDateDateTime
                }
                Writer.WriteEndElement();
            }

            Writer.WriteStartElement("ram:SpecifiedTradeSettlementMonetarySummation");
            _writeOptionalAmount(Writer, "ram:LineTotalAmount", this.Descriptor.LineTotalAmount);
            _writeOptionalAmount(Writer, "ram:ChargeTotalAmount", this.Descriptor.ChargeTotalAmount);
            _writeOptionalAmount(Writer, "ram:AllowanceTotalAmount", this.Descriptor.AllowanceTotalAmount);
            _writeOptionalAmount(Writer, "ram:TaxBasisTotalAmount", this.Descriptor.TaxBasisAmount);
            _writeOptionalAmount(Writer, "ram:TaxTotalAmount", this.Descriptor.TaxTotalAmount);
            _writeOptionalAmount(Writer, "ram:GrandTotalAmount", this.Descriptor.GrandTotalAmount);
            _writeOptionalAmount(Writer, "ram:TotalPrepaidAmount", this.Descriptor.TotalPrepaidAmount);
            _writeOptionalAmount(Writer, "ram:DuePayableAmount", this.Descriptor.DuePayableAmount);
            Writer.WriteEndElement(); // !ram:SpecifiedTradeSettlementMonetarySummation

            Writer.WriteEndElement(); // !ram:ApplicableSupplyChainTradeSettlement

            foreach (TradeLineItem tradeLineItem in this.Descriptor.TradeLineItems)
            {
                Writer.WriteStartElement("ram:IncludedSupplyChainTradeLineItem");

                if (tradeLineItem.AssociatedDocument != null)
                {
                    Writer.WriteStartElement("ram:AssociatedDocumentLineDocument");
                    if (tradeLineItem.AssociatedDocument.LineID.HasValue)
                    {
                        Writer.WriteElementString("ram:LineID", String.Format("{0}", tradeLineItem.AssociatedDocument.LineID));
                    }
                    _writeNotes(Writer, tradeLineItem.AssociatedDocument.Notes);
                    Writer.WriteEndElement(); // ram:AssociatedDocumentLineDocument
                }

                // handelt es sich um einen Kommentar?
                if ((tradeLineItem.AssociatedDocument?.Notes.Count > 0) && (tradeLineItem.BilledQuantity == 0) && (String.IsNullOrEmpty(tradeLineItem.Description)))
                {
                    Writer.WriteEndElement(); // !ram:IncludedSupplyChainTradeLineItem
                    continue;
                }

                if (Descriptor.Profile != Profile.Basic)
                {
                    Writer.WriteStartElement("ram:SpecifiedSupplyChainTradeAgreement");

                    if (tradeLineItem.BuyerOrderReferencedDocument != null)
                    {
                        Writer.WriteStartElement("ram:BuyerOrderReferencedDocument");
                        if (tradeLineItem.BuyerOrderReferencedDocument.IssueDateTime.HasValue)
                        {
                            Writer.WriteStartElement("ram:IssueDateTime");
                            Writer.WriteValue(_formatDate(tradeLineItem.BuyerOrderReferencedDocument.IssueDateTime.Value, false));
                            Writer.WriteEndElement(); // !ram:IssueDateTime
                        }
                        if (!String.IsNullOrEmpty(tradeLineItem.BuyerOrderReferencedDocument.ID))
                        {
                            Writer.WriteElementString("ram:ID", tradeLineItem.BuyerOrderReferencedDocument.ID);
                        }

                        Writer.WriteEndElement(); // !ram:BuyerOrderReferencedDocument
                    }

                    if (tradeLineItem.ContractReferencedDocument != null)
                    {
                        Writer.WriteStartElement("ram:ContractReferencedDocument");
                        if (tradeLineItem.ContractReferencedDocument.IssueDateTime.HasValue)
                        {
                            Writer.WriteStartElement("ram:IssueDateTime");
                            Writer.WriteValue(_formatDate(tradeLineItem.ContractReferencedDocument.IssueDateTime.Value, false));
                            Writer.WriteEndElement(); // !ram:IssueDateTime
                        }
                        if (!String.IsNullOrEmpty(tradeLineItem.ContractReferencedDocument.ID))
                        {
                            Writer.WriteElementString("ram:ID", tradeLineItem.ContractReferencedDocument.ID);
                        }

                        Writer.WriteEndElement(); // !ram:ContractReferencedDocument
                    }

                    if ((tradeLineItem.AdditionalReferencedDocuments != null) && (tradeLineItem.AdditionalReferencedDocuments.Count > 0))
                    {
                        foreach (AdditionalReferencedDocument doc in tradeLineItem.AdditionalReferencedDocuments)
                        {
                            Writer.WriteStartElement("ram:AdditionalReferencedDocument");
                            if (doc.IssueDateTime.HasValue)
                            {
                                Writer.WriteStartElement("ram:IssueDateTime");
                                Writer.WriteValue(_formatDate(doc.IssueDateTime.Value, false));
                                Writer.WriteEndElement(); // !ram:IssueDateTime
                            }

                            Writer.WriteElementString("ram:LineID", String.Format("{0}", tradeLineItem.AssociatedDocument?.LineID));

                            if (!String.IsNullOrEmpty(doc.ID))
                            {
                                Writer.WriteElementString("ram:ID", doc.ID);
                            }

                            Writer.WriteElementString("ram:ReferenceTypeCode", doc.ReferenceTypeCode.EnumToString());

                            Writer.WriteEndElement(); // !ram:AdditionalReferencedDocument
                        }
                    }

                    Writer.WriteStartElement("ram:GrossPriceProductTradePrice");
                    _writeOptionalAmount(Writer, "ram:ChargeAmount", tradeLineItem.GrossUnitPrice, 4);
                    if (tradeLineItem.UnitQuantity.HasValue)
                    {
                        _writeElementWithAttribute(Writer, "ram:BasisQuantity", "unitCode", tradeLineItem.UnitCode.EnumToString(), _formatDecimal(tradeLineItem.UnitQuantity.Value, 4));
                    }

                    foreach (TradeAllowanceCharge tradeAllowanceCharge in tradeLineItem.TradeAllowanceCharges)
                    {
                        Writer.WriteStartElement("ram:AppliedTradeAllowanceCharge");

                        Writer.WriteStartElement("ram:ChargeIndicator");
                        Writer.WriteElementString("udt:Indicator", tradeAllowanceCharge.ChargeIndicator ? "true" : "false");
                        Writer.WriteEndElement(); // !ram:ChargeIndicator

                        Writer.WriteStartElement("ram:BasisAmount");
                        Writer.WriteAttributeString("currencyID", tradeAllowanceCharge.Currency.EnumToString());
                        Writer.WriteValue(_formatDecimal(tradeAllowanceCharge.BasisAmount, 4));
                        Writer.WriteEndElement();
                        Writer.WriteStartElement("ram:ActualAmount");
                        Writer.WriteAttributeString("currencyID", tradeAllowanceCharge.Currency.EnumToString());
                        Writer.WriteValue(_formatDecimal(tradeAllowanceCharge.ActualAmount, 4));
                        Writer.WriteEndElement();

                        _writeOptionalElementString(Writer, "ram:Reason", tradeAllowanceCharge.Reason);

                        Writer.WriteEndElement(); // !AppliedTradeAllowanceCharge
                    }

                    Writer.WriteEndElement(); // ram:GrossPriceProductTradePrice

                    Writer.WriteStartElement("ram:NetPriceProductTradePrice");
                    _writeOptionalAmount(Writer, "ram:ChargeAmount", tradeLineItem.NetUnitPrice, 4);

                    if (tradeLineItem.UnitQuantity.HasValue)
                    {
                        _writeElementWithAttribute(Writer, "ram:BasisQuantity", "unitCode", tradeLineItem.UnitCode.EnumToString(), _formatDecimal(tradeLineItem.UnitQuantity.Value, 4));
                    }
                    Writer.WriteEndElement(); // ram:NetPriceProductTradePrice

                    Writer.WriteEndElement(); // !ram:SpecifiedSupplyChainTradeAgreement
                }

                if (Descriptor.Profile != Profile.Basic)
                {
                    Writer.WriteStartElement("ram:SpecifiedSupplyChainTradeDelivery");
                    _writeElementWithAttribute(Writer, "ram:BilledQuantity", "unitCode", tradeLineItem.UnitCode.EnumToString(), _formatDecimal(tradeLineItem.BilledQuantity, 4));

                    if (tradeLineItem.DeliveryNoteReferencedDocument != null)
                    {
                        Writer.WriteStartElement("ram:DeliveryNoteReferencedDocument");
                        if (tradeLineItem.DeliveryNoteReferencedDocument.IssueDateTime.HasValue)
                        {
                            Writer.WriteStartElement("ram:IssueDateTime");
                            Writer.WriteValue(_formatDate(tradeLineItem.DeliveryNoteReferencedDocument.IssueDateTime.Value, false));
                            Writer.WriteEndElement(); // !ram:IssueDateTime
                        }
                        if (!String.IsNullOrEmpty(tradeLineItem.DeliveryNoteReferencedDocument.ID))
                        {
                            Writer.WriteElementString("ram:ID", tradeLineItem.DeliveryNoteReferencedDocument.ID);
                        }

                        Writer.WriteEndElement(); // !ram:DeliveryNoteReferencedDocument
                    }

                    if (tradeLineItem.ActualDeliveryDate.HasValue)
                    {
                        Writer.WriteStartElement("ram:ActualDeliverySupplyChainEvent");
                        Writer.WriteStartElement("ram:OccurrenceDateTime");
                        Writer.WriteStartElement("udt:DateTimeString");
                        Writer.WriteAttributeString("format", "102");
                        Writer.WriteValue(_formatDate(tradeLineItem.ActualDeliveryDate.Value));
                        Writer.WriteEndElement(); // "udt:DateTimeString
                        Writer.WriteEndElement(); // !OccurrenceDateTime()
                        Writer.WriteEndElement(); // !ActualDeliverySupplyChainEvent
                    }

                    Writer.WriteEndElement(); // !ram:SpecifiedSupplyChainTradeDelivery
                }
                else
                {
                    Writer.WriteStartElement("ram:SpecifiedSupplyChainTradeDelivery");
                    _writeElementWithAttribute(Writer, "ram:BilledQuantity", "unitCode", tradeLineItem.UnitCode.EnumToString(), _formatDecimal(tradeLineItem.BilledQuantity, 4));
                    Writer.WriteEndElement(); // !ram:SpecifiedSupplyChainTradeDelivery
                }

                Writer.WriteStartElement("ram:SpecifiedSupplyChainTradeSettlement");

                if (Descriptor.Profile != Profile.Basic)
                {
                    Writer.WriteStartElement("ram:ApplicableTradeTax");
                    Writer.WriteElementString("ram:TypeCode", tradeLineItem.TaxType.EnumToString());
                    Writer.WriteElementString("ram:CategoryCode", tradeLineItem.TaxCategoryCode.EnumToString());
                    Writer.WriteElementString("ram:ApplicablePercent", _formatDecimal(tradeLineItem.TaxPercent));
                    Writer.WriteEndElement(); // !ram:ApplicableTradeTax
                }
                Writer.WriteStartElement("ram:SpecifiedTradeSettlementMonetarySummation");

                decimal _total = 0m;

                if (tradeLineItem.LineTotalAmount.HasValue)
                {
                    _total = tradeLineItem.LineTotalAmount.Value;
                }
                else
                {
                    _total = tradeLineItem.NetUnitPrice * tradeLineItem.BilledQuantity;
                }

                _writeElementWithAttribute(Writer, "ram:LineTotalAmount", "currencyID", this.Descriptor.Currency.EnumToString(), _formatDecimal(_total));
                Writer.WriteEndElement(); // ram:SpecifiedTradeSettlementMonetarySummation
                Writer.WriteEndElement(); // !ram:SpecifiedSupplyChainTradeSettlement

                Writer.WriteStartElement("ram:SpecifiedTradeProduct");
                if ((tradeLineItem.GlobalID != null) && !String.IsNullOrEmpty(tradeLineItem.GlobalID.SchemeID) && !String.IsNullOrEmpty(tradeLineItem.GlobalID.ID))
                {
                    _writeElementWithAttribute(Writer, "ram:GlobalID", "schemeID", tradeLineItem.GlobalID.SchemeID, tradeLineItem.GlobalID.ID);
                }

                _writeOptionalElementString(Writer, "ram:SellerAssignedID", tradeLineItem.SellerAssignedID);
                _writeOptionalElementString(Writer, "ram:BuyerAssignedID", tradeLineItem.BuyerAssignedID);
                _writeOptionalElementString(Writer, "ram:Name", tradeLineItem.Name);
                _writeOptionalElementString(Writer, "ram:Description", tradeLineItem.Description);

                Writer.WriteEndElement(); // !ram:SpecifiedTradeProduct
                Writer.WriteEndElement(); // !ram:IncludedSupplyChainTradeLineItem
            } // !foreach(tradeLineItem)

            Writer.WriteEndElement(); // !ram:SpecifiedSupplyChainTradeTransaction
            #endregion

            Writer.WriteEndElement(); // !ram:Invoice
            Writer.WriteEndDocument();
            Writer.Flush();

            stream.Seek(streamPosition, SeekOrigin.Begin);
        } // !Save()
Exemplo n.º 43
0
        private void cmdDelete_Click(object sender, EventArgs e)
        {
            if (lstKits.Text == string.Empty)
            {
                return;
            }

            if (MessageBox.Show(LanguageManager.Instance.GetString("Message_DeletePACKSKit").Replace("{0}", lstKits.Text), LanguageManager.Instance.GetString("MessageTitle_Delete"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
            {
                return;
            }

            // Delete the selectec custom PACKS Kit.
            // Find a custom PACKS Kit with the name. This is done without the XmlManager since we need to check each file individually.
            XmlDocument objXmlDocument = new XmlDocument();
            string      strCustomPath  = Path.Combine(Environment.CurrentDirectory, "data");

            foreach (string strFile in Directory.GetFiles(strCustomPath, "custom*_packs.xml"))
            {
                objXmlDocument.Load(strFile);
                XmlNodeList objXmlPACKSList = objXmlDocument.SelectNodes("/chummer/packs/pack[name = \"" + lstKits.SelectedValue + "\" and category = \"Custom\"]");
                if (objXmlPACKSList.Count > 0)
                {
                    // Read in the entire file.
                    XmlDocument objXmlCurrentDocument = new XmlDocument();
                    objXmlCurrentDocument.Load(strFile);

                    FileStream    objStream = new FileStream(strFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                    XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.Unicode);
                    objWriter.Formatting  = Formatting.Indented;
                    objWriter.Indentation = 1;
                    objWriter.IndentChar  = '\t';
                    objWriter.WriteStartDocument();

                    // <chummer>
                    objWriter.WriteStartElement("chummer");
                    // <packs>
                    objWriter.WriteStartElement("packs");

                    // If this is not a new file, write out the current contents.
                    XmlNodeList objXmlNodeList = objXmlCurrentDocument.SelectNodes("/chummer/packs/*");
                    foreach (XmlNode objXmlNode in objXmlNodeList)
                    {
                        if (objXmlNode["name"].InnerText != lstKits.SelectedValue.ToString())
                        {
                            // <pack>
                            objWriter.WriteStartElement("pack");
                            objXmlNode.WriteContentTo(objWriter);
                            // </pack>
                            objWriter.WriteEndElement();
                        }
                    }

                    // </packs>
                    objWriter.WriteEndElement();
                    // </chummer>
                    objWriter.WriteEndElement();

                    objWriter.WriteEndDocument();
                    objWriter.Close();
                    objStream.Close();
                }
            }

            // Reload the PACKS files since they have changed.
            _objXmlDocument = XmlManager.Instance.Load("packs.xml");
            cboCategory_SelectedIndexChanged(sender, e);
        }
        private void but_getfw_Click(object sender, EventArgs e)
        {
            var basedir = Settings.GetDataDirectory() + "History";

            Directory.CreateDirectory(basedir);

            var fw = new Firmware();

            var list = fw.getFWList();

            using (
                var xmlwriter = new XmlTextWriter(basedir + Path.DirectorySeparatorChar + @"firmware2.xml",
                                                  Encoding.ASCII))
            {
                xmlwriter.Formatting = Formatting.Indented;

                xmlwriter.WriteStartDocument();

                xmlwriter.WriteStartElement("options");

                int a = 0;

                foreach (var software in list)
                {
                    a++;
                    Loading.ShowLoading(((a - 1) / (float)list.Count) * 100.0 + "% " + software.name, this);

                    //if (!software.name.Contains("Copter"))
                    //  continue;

                    xmlwriter.WriteStartElement("Firmware");

                    if (software.url != "")
                    {
                        xmlwriter.WriteElementString("url", new Uri(software.url).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.url2560 != "")
                    {
                        xmlwriter.WriteElementString("url2560", new Uri(software.url2560).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.url2560_2 != "")
                    {
                        xmlwriter.WriteElementString("url2560-2",
                                                     new Uri(software.url2560_2).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlpx4v1 != "")
                    {
                        xmlwriter.WriteElementString("urlpx4", new Uri(software.urlpx4v1).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlpx4v2 != "")
                    {
                        xmlwriter.WriteElementString("urlpx4v2",
                                                     new Uri(software.urlpx4v2).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlpx4v4 != "")
                    {
                        xmlwriter.WriteElementString("urlpx4v4",
                                                     new Uri(software.urlpx4v4).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlpx4v4pro != "")
                    {
                        xmlwriter.WriteElementString("urlpx4v4pro",
                                                     new Uri(software.urlpx4v4pro).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrbrainv40 != "")
                    {
                        xmlwriter.WriteElementString("urlvrbrainv40",
                                                     new Uri(software.urlvrbrainv40).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrbrainv45 != "")
                    {
                        xmlwriter.WriteElementString("urlvrbrainv45",
                                                     new Uri(software.urlvrbrainv45).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrbrainv50 != "")
                    {
                        xmlwriter.WriteElementString("urlvrbrainv50",
                                                     new Uri(software.urlvrbrainv50).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrbrainv51 != "")
                    {
                        xmlwriter.WriteElementString("urlvrbrainv51",
                                                     new Uri(software.urlvrbrainv51).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrbrainv52 != "")
                    {
                        xmlwriter.WriteElementString("urlvrbrainv52",
                                                     new Uri(software.urlvrbrainv52).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrbrainv54 != "")
                    {
                        xmlwriter.WriteElementString("urlvrbrainv54",
                                                     new Uri(software.urlvrbrainv54).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrcorev10 != "")
                    {
                        xmlwriter.WriteElementString("urlvrcorev10",
                                                     new Uri(software.urlvrcorev10).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrubrainv51 != "")
                    {
                        xmlwriter.WriteElementString("urlvrubrainv51",
                                                     new Uri(software.urlvrubrainv51).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrubrainv52 != "")
                    {
                        xmlwriter.WriteElementString("urlvrubrainv52",
                                                     new Uri(software.urlvrubrainv52).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlbebop2 != "")
                    {
                        xmlwriter.WriteElementString("urlbebop2",
                                                     new Uri(software.urlbebop2).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urldisco != "")
                    {
                        xmlwriter.WriteElementString("urldisco",
                                                     new Uri(software.urldisco).LocalPath.TrimStart('/', '\\'));
                    }
                    xmlwriter.WriteElementString("name", software.name);
                    xmlwriter.WriteElementString("desc", software.desc);
                    xmlwriter.WriteElementString("format_version", software.k_format_version.ToString());

                    xmlwriter.WriteEndElement();

                    if (software.url != "")
                    {
                        Download.getFilefromNet(software.url, basedir + new Uri(software.url).LocalPath);
                    }
                    if (software.url2560 != "")
                    {
                        Download.getFilefromNet(software.url2560, basedir + new Uri(software.url2560).LocalPath);
                    }
                    if (software.url2560_2 != "")
                    {
                        Download.getFilefromNet(software.url2560_2, basedir + new Uri(software.url2560_2).LocalPath);
                    }
                    if (software.urlpx4v1 != "")
                    {
                        Download.getFilefromNet(software.urlpx4v1, basedir + new Uri(software.urlpx4v1).LocalPath);
                    }
                    if (software.urlpx4v2 != "")
                    {
                        Download.getFilefromNet(software.urlpx4v2, basedir + new Uri(software.urlpx4v2).LocalPath);
                    }
                    if (software.urlpx4v4 != "")
                    {
                        Download.getFilefromNet(software.urlpx4v4, basedir + new Uri(software.urlpx4v4).LocalPath);
                    }
                    if (software.urlpx4v4pro != "")
                    {
                        Download.getFilefromNet(software.urlpx4v4pro, basedir + new Uri(software.urlpx4v4pro).LocalPath);
                    }

                    if (software.urlvrbrainv40 != "")
                    {
                        Download.getFilefromNet(software.urlvrbrainv40,
                                                basedir + new Uri(software.urlvrbrainv40).LocalPath);
                    }
                    if (software.urlvrbrainv45 != "")
                    {
                        Download.getFilefromNet(software.urlvrbrainv45,
                                                basedir + new Uri(software.urlvrbrainv45).LocalPath);
                    }
                    if (software.urlvrbrainv50 != "")
                    {
                        Download.getFilefromNet(software.urlvrbrainv50,
                                                basedir + new Uri(software.urlvrbrainv50).LocalPath);
                    }
                    if (software.urlvrbrainv51 != "")
                    {
                        Download.getFilefromNet(software.urlvrbrainv51,
                                                basedir + new Uri(software.urlvrbrainv51).LocalPath);
                    }
                    if (software.urlvrbrainv52 != "")
                    {
                        Download.getFilefromNet(software.urlvrbrainv52,
                                                basedir + new Uri(software.urlvrbrainv52).LocalPath);
                    }
                    if (software.urlvrbrainv54 != "")
                    {
                        Download.getFilefromNet(software.urlvrbrainv54,
                                                basedir + new Uri(software.urlvrbrainv54).LocalPath);
                    }
                    if (software.urlvrcorev10 != "")
                    {
                        Download.getFilefromNet(software.urlvrcorev10, basedir + new Uri(software.urlvrcorev10).LocalPath);
                    }
                    if (software.urlvrubrainv51 != "")
                    {
                        Download.getFilefromNet(software.urlvrubrainv51,
                                                basedir + new Uri(software.urlvrubrainv51).LocalPath);
                    }
                    if (software.urlvrubrainv52 != "")
                    {
                        Download.getFilefromNet(software.urlvrubrainv52,
                                                basedir + new Uri(software.urlvrubrainv52).LocalPath);
                    }
                    if (software.urlbebop2 != "")
                    {
                        Download.getFilefromNet(software.urlbebop2,
                                                basedir + new Uri(software.urlbebop2).LocalPath);
                    }
                    if (software.urldisco != "")
                    {
                        Download.getFilefromNet(software.urldisco,
                                                basedir + new Uri(software.urldisco).LocalPath);
                    }
                }

                xmlwriter.WriteEndElement();
                xmlwriter.WriteEndDocument();
            }

            Loading.Close();
        }
Exemplo n.º 45
0
        private static void PrintHierarchy(IIfcObjectDefinition o, int level, Dictionary <string, IfcSpace> spaceidset, Dictionary <string, IfcBuildingStorey> storeyidset, List <XbimShapeInstance> _shapes, int number_of_shapes, Xbim3DModelContext mod_context)
        {
            Console.WriteLine($"{GetIndent(level)}{" >> " + o.Name} [{o.GetType().Name}{ " | #" + o.EntityLabel  }] {"\n"}");
            var item = o.IsDecomposedBy.SelectMany(r => r.RelatedObjects);

            foreach (var i in item)
            {
                var id = i.GlobalId.ToString();

                //Console.WriteLine("------------------Matches found :" + _si.ShapeGeometryLabel.ToString());

                PrintHierarchy(i, level + 2, spaceidset, storeyidset, _shapes, number_of_shapes, mod_context);

                //Console.WriteLine("Instance ID: " + eid);

                if (spaceidset.ContainsKey(id))
                {
                    IfcSpace spacenode;
                    spaceidset.TryGetValue(id, out spacenode);
                    var spacenodelelems = spacenode.GetContainedElements();

                    if (spacenodelelems.Count() > 0)
                    {
                        Console.WriteLine($"{GetIndent(level + 4)}" + "OBJECTS FOUND UNDER SPACE ARE: \n");
                        foreach (var sne in spacenodelelems)
                        {
                            var parent = sne.IsContainedIn;
                            var eid    = sne.EntityLabel.ToString();

                            Console.WriteLine($"{GetIndent(level + 5)}{" --> " + sne.Name} [{sne.GetType().Name}{ " | #" + sne.EntityLabel }{" | PARENT : #" + parent.EntityLabel}]");
                            Console.WriteLine(sne.EntityLabel);
                            var si = _shapes.Find(x => x.IfcProductLabel.ToString() == eid);
                            //Console.WriteLine("------------------Matches found :" + si.ShapeGeometryLabel.ToString());
                            getgeometry(si, mod_context);
                        }
                    }
                }

                else if (storeyidset.ContainsKey(id))
                {
                    IfcBuildingStorey bsnode;
                    storeyidset.TryGetValue(id, out bsnode);
                    var bsnodelelems = bsnode.GetContainedElements();

                    if (bsnodelelems.Count() > 0)
                    {
                        Console.WriteLine($"{GetIndent(level + 4)}" + "OTHER OBJECTS FOUND UNDER STOREY ARE: \n");



                        foreach (var bsne in bsnodelelems)
                        {
                            var parent = bsne.IsContainedIn;
                            var eid    = bsne.EntityLabel.ToString();

                            var name_of_shape = bsne.GetType().Name;

                            Console.WriteLine($"{GetIndent(level + 5)}{" --> " + bsne.Name} [{name_of_shape}{ " | #" + bsne.EntityLabel } {" | PARENT : #" + parent.EntityLabel }]");
                            Console.WriteLine("]]]]]]]]]]" + bsne.EntityLabel);



                            var si = _shapes.Find(x => x.IfcProductLabel.ToString() == eid);

                            //write the name of the shape  with its id
                            xmlWriter.WriteStartElement(name_of_shape);
                            xmlWriter.WriteAttributeString("ID", bsne.EntityLabel.ToString());


                            getgeometry(si, mod_context, bsne.EntityLabel, number_of_shapes);

                            // for each XML element that we created we should close it in order to have the correct hierarchy in the xml file
                            xmlWriter.WriteEndElement();
                        }
                    }
                }


                /***************************************************************************/
            }
        }
        private void WritePackageInfo(XmlTextWriter writer)
        {
            foreach (var package in this.ChainPackages)
            {
                var packagePayload = this.Payloads[package.PackageSymbol.PayloadRef];

                var size = package.PackageSymbol.Size.ToString(CultureInfo.InvariantCulture);

                writer.WriteStartElement("WixPackageProperties");

                writer.WriteAttributeString("Package", package.PackageId);
                writer.WriteAttributeString("Vital", package.PackageSymbol.Vital == true ? "yes" : "no");

                if (!String.IsNullOrEmpty(package.PackageSymbol.DisplayName))
                {
                    writer.WriteAttributeString("DisplayName", package.PackageSymbol.DisplayName);
                }

                if (!String.IsNullOrEmpty(package.PackageSymbol.Description))
                {
                    writer.WriteAttributeString("Description", package.PackageSymbol.Description);
                }

                writer.WriteAttributeString("DownloadSize", size);
                writer.WriteAttributeString("PackageSize", size);
                writer.WriteAttributeString("InstalledSize", package.PackageSymbol.InstallSize?.ToString(CultureInfo.InvariantCulture) ?? size);
                writer.WriteAttributeString("PackageType", package.PackageSymbol.Type.ToString());
                writer.WriteAttributeString("Permanent", package.PackageSymbol.Permanent ? "yes" : "no");
                writer.WriteAttributeString("LogPathVariable", package.PackageSymbol.LogPathVariable);
                writer.WriteAttributeString("RollbackLogPathVariable", package.PackageSymbol.RollbackLogPathVariable);
                writer.WriteAttributeString("Compressed", packagePayload.Compressed == true ? "yes" : "no");

                if (package.SpecificPackageSymbol is WixBundleMsiPackageSymbol msiPackage)
                {
                    if (!String.IsNullOrEmpty(msiPackage.ProductCode))
                    {
                        writer.WriteAttributeString("ProductCode", msiPackage.ProductCode);
                    }

                    if (!String.IsNullOrEmpty(msiPackage.UpgradeCode))
                    {
                        writer.WriteAttributeString("UpgradeCode", msiPackage.UpgradeCode);
                    }
                }
                else if (package.SpecificPackageSymbol is WixBundleMspPackageSymbol mspPackage)
                {
                    if (!String.IsNullOrEmpty(mspPackage.PatchCode))
                    {
                        writer.WriteAttributeString("ProductCode", mspPackage.PatchCode);
                    }
                }

                if (!String.IsNullOrEmpty(package.PackageSymbol.Version))
                {
                    writer.WriteAttributeString("Version", package.PackageSymbol.Version);
                }

                if (!String.IsNullOrEmpty(package.PackageSymbol.InstallCondition))
                {
                    writer.WriteAttributeString("InstallCondition", package.PackageSymbol.InstallCondition);
                }

                switch (package.PackageSymbol.Cache)
                {
                case YesNoAlwaysType.No:
                    writer.WriteAttributeString("Cache", "no");
                    break;

                case YesNoAlwaysType.Yes:
                    writer.WriteAttributeString("Cache", "yes");
                    break;

                case YesNoAlwaysType.Always:
                    writer.WriteAttributeString("Cache", "always");
                    break;
                }

                writer.WriteEndElement();
            }
        }
Exemplo n.º 47
0
        public void createNode(string UserId, string TableNo, string ItemId, string ItemName, string FullQty, string HalfQty, string Fullprice, string HalfPrice, string Amount, string VatAmt, string Vatamtchrg, string OfferQty, XmlTextWriter writer)
        {
            writer.WriteStartElement("Items");
            writer.WriteStartElement("UserId");
            writer.WriteString(UserId);
            writer.WriteEndElement();
            writer.WriteStartElement("TableNo");
            writer.WriteString(TableNo);
            writer.WriteEndElement();
            writer.WriteStartElement("ItemId");
            writer.WriteString(ItemId);
            writer.WriteEndElement();
            writer.WriteStartElement("ItemName");
            writer.WriteString(ItemName);
            writer.WriteEndElement();
            writer.WriteStartElement("FullQty");
            writer.WriteString(FullQty);
            writer.WriteEndElement();

            writer.WriteStartElement("HalfQty");
            writer.WriteString(HalfQty);
            writer.WriteEndElement();
            writer.WriteStartElement("Fullprice");
            writer.WriteString(Fullprice);
            writer.WriteEndElement();
            writer.WriteStartElement("HalfPrice");
            writer.WriteString(HalfPrice);
            writer.WriteEndElement();
            writer.WriteStartElement("Amount");
            writer.WriteString(Amount);
            writer.WriteEndElement();
            writer.WriteStartElement("VatAmt");
            writer.WriteString(VatAmt);
            writer.WriteEndElement();
            writer.WriteStartElement("VatAmountCharges");
            writer.WriteString(Vatamtchrg);
            writer.WriteEndElement();
            writer.WriteStartElement("OfferQty");
            writer.WriteString(OfferQty);
            writer.WriteEndElement();
            writer.WriteEndElement();
        }
Exemplo n.º 48
0
        public override object ConvertTo(ITypeDescriptorContext context,
                                         CultureInfo culture,
                                         object value,
                                         Type destinationType)
        {
            if (!(value is TableLayoutSettings) || destinationType != typeof(string))
            {
                return(base.ConvertTo(context, culture, value, destinationType));
            }

            TableLayoutSettings settings = value as TableLayoutSettings;
            StringWriter        sw       = new StringWriter();
            XmlTextWriter       xw       = new XmlTextWriter(sw);

            xw.WriteStartDocument();
            List <ControlInfo> list = settings.GetControls();

            xw.WriteStartElement("TableLayoutSettings");
            xw.WriteStartElement("Controls");

            foreach (ControlInfo info in list)
            {
                xw.WriteStartElement("Control");
                xw.WriteAttributeString("Name", info.Control.ToString());
                xw.WriteAttributeString("Row", info.Row.ToString());
                xw.WriteAttributeString("RowSpan", info.RowSpan.ToString());
                xw.WriteAttributeString("Column", info.Col.ToString());
                xw.WriteAttributeString("ColumnSpan", info.ColSpan.ToString());
                xw.WriteEndElement();
            }
            xw.WriteEndElement();


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

            foreach (ColumnStyle style in settings.ColumnStyles)
            {
                styles.Add(style.SizeType.ToString());
                styles.Add(style.Width.ToString(CultureInfo.InvariantCulture));
            }


            xw.WriteStartElement("Columns");
            xw.WriteAttributeString("Styles", String.Join(",", styles.ToArray()));
            xw.WriteEndElement();

            styles.Clear();
            foreach (RowStyle style in settings.RowStyles)
            {
                styles.Add(style.SizeType.ToString());
                styles.Add(style.Height.ToString(CultureInfo.InvariantCulture));
            }

            xw.WriteStartElement("Rows");
            xw.WriteAttributeString("Styles", String.Join(",", styles.ToArray()));
            xw.WriteEndElement();

            xw.WriteEndElement();
            xw.WriteEndDocument();
            xw.Close();

            return(sw.ToString());
        }
Exemplo n.º 49
0
        /// <summary>
        /// Saves the current state and matches of the Member to the XML storage file
        /// </summary>
        public void SaveToXML()
        {
            // Create a new XmlTextWriter instance
            XmlTextWriter writer = new XmlTextWriter(@"goAbout.xml", Encoding.UTF8);

            // start writing
            writer.WriteStartDocument();

            // create a Member element
            writer.WriteStartElement("Member");

            // Encrypt the Screen Name & Password and write them as elements values
            writer.WriteElementString("MemberID", enc(memberID));
            writer.WriteElementString("Password", enc(this.Password));
            writer.WriteElementString("ServerAddress", enc(this.serverAddress));

            // create a new element for the options
            writer.WriteStartElement("Options");

            // store the options
            writer.WriteElementString("Option1", this.option1.ToString());
            writer.WriteElementString("Option2", this.option2.ToString());
            writer.WriteElementString("Option3", this.option3.ToString());
            writer.WriteElementString("Option4", this.option4.ToString());

            // close the options element
            writer.WriteEndElement();

            // create a new element for the Profile
            writer.WriteStartElement("Profile");

            // All filter options are encrypted
            writer.WriteElementString("Age", enc(Age.ToString()));
            writer.WriteElementString("Gender", enc(Gender.ToString()));
            writer.WriteElementString("AgeSeek", enc(SeekAge.ToString()));
            writer.WriteElementString("GenderSeek", enc(SeekGender.ToString()));

            // close the profile element
            writer.WriteEndElement();

            // This is where photo storage would be implemented
            //			if(this.image!=null)
            //			{
            //				Byte[] b = this.ImageFile.
            //				writer.WriteStartElement("Photo");
            //
            //					writer.WriteElementString("Name","photo.jpg");
            //					writer.WriteElementString("Data","");
            //
            //				writer.WriteEndElement();
            //			}

            // create a Matches element
            writer.WriteStartElement("Matches");

            // loop though all the Matches
            for (int i = 0; i < Matches.Count; i++)
            {
                // Create a new Match element
                writer.WriteStartElement("Match");

                // Encrypt all Match details
                writer.WriteElementString("MatchName", enc(((Match)Matches[i]).memberID));
                writer.WriteElementString("MAC", enc(((Match)Matches[i]).MACAddress));
                writer.WriteElementString("MatchDT", enc(DateTime.Now.ToLongTimeString()));
                writer.WriteElementString("ConfirmedByServer", enc(((Match)Matches[i]).ConfirmedByServer.ToString()));
                writer.WriteEndElement();
            }

            // close the Matches element
            writer.WriteEndElement();

            // Close the Member element
            writer.WriteEndDocument();

            // Close the writer object
            writer.Close();
        }
Exemplo n.º 50
0
        private string BuildUPSRateRequestForShipment(IShipment shipment)
        {
            var sXML      = string.Empty;
            var strWriter = new StringWriter();
            var xw        = new XmlTextWriter(strWriter);

            try
            {
                xw.Formatting  = Formatting.Indented;
                xw.Indentation = 3;

                //--------------------------------------------
                // Agreement Request
                xw.WriteStartElement("RatingServiceSelectionRequest");

                //--------------------------------------------
                // Request
                xw.WriteStartElement("Request");
                //--------------------------------------------
                // TransactionReference
                xw.WriteStartElement("TransactionReference");
                xw.WriteElementString("CustomerContext", "Rate Request");
                xw.WriteElementString("XpciVersion", "1.0001");
                xw.WriteEndElement();
                // End TransactionReference
                //--------------------------------------------
                xw.WriteElementString("RequestOption", "Shop");
                xw.WriteEndElement();
                // End Request
                //--------------------------------------------

                //--------------------------------------------
                // Pickup Type
                if (GlobalSettings.PickUpType != PickupType.Unknown)
                {
                    var pickupCode = ((int)GlobalSettings.PickUpType).ToString();

                    if (pickupCode.Trim().Length < 2)
                    {
                        pickupCode = "0" + pickupCode;
                    }

                    xw.WriteStartElement("PickupType");
                    xw.WriteElementString("Code", pickupCode);
                    xw.WriteEndElement();
                }
                // End Pickup Type
                //--------------------------------------------

                //--------------------------------------------
                // Shipment
                xw.WriteStartElement("Shipment");

                // Shipper
                xw.WriteStartElement("Shipper");
                xw.WriteStartElement("Address");

                //Use City name for countries that don't have postal codes
                if (shipment.SourceAddress.PostalCode.Trim().Length > 0)
                {
                    xw.WriteElementString("PostalCode",
                                          XmlTools.TrimToLength(shipment.SourceAddress.PostalCode.Trim(), 9));
                }
                else
                {
                    xw.WriteElementString("City", XmlTools.TrimToLength(shipment.SourceAddress.City.Trim(), 30));
                }

                xw.WriteElementString("CountryCode", shipment.SourceAddress.CountryData.IsoCode);
                xw.WriteEndElement();
                xw.WriteEndElement();

                // Ship To
                xw.WriteStartElement("ShipTo");
                xw.WriteStartElement("Address");

                if (shipment.DestinationAddress.PostalCode.Length > 0)
                {
                    xw.WriteElementString("PostalCode", shipment.DestinationAddress.PostalCode);
                }
                else
                {
                    if (shipment.DestinationAddress.City.Length > 0)
                    {
                        xw.WriteElementString("City", shipment.DestinationAddress.City);
                    }
                }

                if (shipment.DestinationAddress.CountryData.Bvin.Length > 0)
                {
                    xw.WriteElementString("CountryCode", shipment.DestinationAddress.CountryData.IsoCode);
                }

                if (GlobalSettings.ForceResidential)
                {
                    xw.WriteElementString("ResidentialAddress", string.Empty);
                }

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

                var ignoreDimensions = GlobalSettings.IgnoreDimensions;

                // Optimize Packages for Weight
                var optimizedPackages = OptimizeSingleGroup(shipment);

                foreach (var p in optimizedPackages)
                {
                    WriteSingleUPSPackage(ref xw, p, ignoreDimensions);
                }

                if (Settings.NegotiatedRates)
                {
                    xw.WriteStartElement("RateInformation");
                    xw.WriteElementString("NegotiatedRatesIndicator", string.Empty);
                    xw.WriteEndElement();
                }

                xw.WriteEndElement();
                // End Shipment
                //--------------------------------------------

                xw.WriteEndElement();
                // End Agreement Request
                //--------------------------------------------

                xw.Flush();
                xw.Close();
            }
            catch (Exception ex)
            {
                _Logger.LogException(ex);
            }

            sXML = strWriter.GetStringBuilder().ToString();

            return(sXML);
        }
Exemplo n.º 51
0
        void WriteLanguageFile(XmlTextWriter writer)
        {
            writer.Formatting  = Formatting.Indented;
            writer.IndentChar  = '\t';
            writer.Indentation = 1;
            writer.Namespaces  = false;

            writer.WriteStartDocument();

            writer.WriteStartElement("Translation"); //<Translation>
            {
                if (!string.IsNullOrEmpty(EnglishName))
                {
                    writer.WriteElementString("LangEn", EnglishName);
                }

                if (!string.IsNullOrEmpty(Name))
                {
                    writer.WriteElementString("Lang", Name);
                }

                if (!string.IsNullOrEmpty(Culture))
                {
                    writer.WriteElementString("Culture", Culture);
                }

                writer.WriteStartElement("Buttons"); //<Buttons>
                {
                    WriteString(writer, "Next", NextButton);
                    WriteString(writer, "Update", UpdateButton);
                    WriteString(writer, "Finish", FinishButton);
                    WriteString(writer, "Cancel", CancelButton);
                    WriteString(writer, "ShowDetails", ShowDetails);
                    WriteString(writer, "Close", ClosePrc);
                    WriteString(writer, "CloseAll", CloseAllPrc);
                    WriteString(writer, "CancelUpdate", CancelUpdate);
                }
                writer.WriteEndElement();            //</Buttons>

                writer.WriteStartElement("Dialogs"); //<Dialogs>
                {
                    WriteScreenDialog(writer, "Cancel", CancelDialog);
                    WriteScreenDialog(writer, "Processes", ProcessDialog);
                    WriteScreenDialog(writer, "FilesInUse", FilesInUseDialog);
                }
                writer.WriteEndElement();           //</Dialogs>

                writer.WriteStartElement("Errors"); //<Errors>
                {
                    WriteString(writer, "Admin", AdminError);
                    WriteString(writer, "Download", DownloadError);
                    WriteString(writer, "LogOff", LogOffError);
                    WriteString(writer, "SelfUpdate", SelfUpdateInstallError);
                    WriteString(writer, "ServFile", ServerError);
                    WriteString(writer, "Update", GeneralUpdateError);
                }
                writer.WriteEndElement();            //</Errors>

                writer.WriteStartElement("Screens"); //<Screens>
                {
                    WriteScreenDialog(writer, "Checking", Checking);
                    WriteScreenDialog(writer, "UpdateInfo", UpdateInfo);
                    WriteScreenDialog(writer, "DownInstall", DownInstall);
                    WriteScreenDialog(writer, "Uninstall", Uninstall);
                    WriteScreenDialog(writer, "SuccessUpdate", SuccessUpdate);
                    WriteScreenDialog(writer, "AlreadyLatest", AlreadyLatest);
                    WriteScreenDialog(writer, "NoUpdateToLatest", NoUpdateToLatest);
                    WriteScreenDialog(writer, "UpdateError", UpdateError);
                }
                writer.WriteEndElement();           //</Screens>

                writer.WriteStartElement("Status"); //<Status>
                {
                    WriteString(writer, "Download", Download);
                    WriteString(writer, "DownloadSelfUpdate", DownloadingSelfUpdate);
                    WriteString(writer, "SelfUpdate", SelfUpdate);
                    WriteString(writer, "Extract", Extract);
                    WriteString(writer, "Processes", Processes);
                    WriteString(writer, "PreExec", PreExec);
                    WriteString(writer, "Files", Files);
                    WriteString(writer, "Registry", Registry);
                    WriteString(writer, "Optimize", Optimize);
                    WriteString(writer, "TempFiles", TempFiles);
                    WriteString(writer, "UninstallFiles", UninstallFiles);
                    WriteString(writer, "UninstallReg", UninstallRegistry);
                    WriteString(writer, "RollingBackFiles", RollingBackFiles);
                    WriteString(writer, "RollingBackRegistry", RollingBackRegistry);
                }
                writer.WriteEndElement();            //</Status>

                writer.WriteStartElement("Bottoms"); //<Bottoms>
                {
                    WriteString(writer, "Update", UpdateBottom);
                    WriteString(writer, "Finish", FinishBottom);
                }
                writer.WriteEndElement(); //</Bottoms>
            }
            writer.WriteEndElement();     // </Translation>

            writer.Flush();
            writer.Close();
        }
Exemplo n.º 52
0
        private void ExportResults()
        {
            //SS:01/03/2018:2018-R1:ABSEXCH-19796: When Running the ExchDVT.exe, SQL Admin Passwords are visible in dump file.
            ADODB.Connection conn = new ADODB.Connection();
            ADODB.Command    cmd  = new ADODB.Command();

            if (CompanyCode == null)
            {
                cmd.CommandText = "SELECT [IntegrityErrorNo]" +
                                  ", [IntegrityErrorCode]" +
                                  ", [Severity]" +
                                  ", [IntegrityErrorMessage]" +
                                  ", [IntegritySummaryDescription]" +
                                  ", [SchemaName]" +
                                  ", [TableName]" +
                                  ", [PositionId]" +
                                  "FROM [common].[SQLDataValidation] ";
            }
            else
            {
                cmd.CommandText = "SELECT [IntegrityErrorNo]" +
                                  ", [IntegrityErrorCode]" +
                                  ", [Severity]" +
                                  ", [IntegrityErrorMessage]" +
                                  ", [IntegritySummaryDescription]" +
                                  ", [SchemaName]" +
                                  ", [TableName]" +
                                  ", [PositionId] " +
                                  "FROM [common].[SQLDataValidation] " +
                                  "WHERE SchemaName = '" + CompanyCode + "'";
            }

            cmd.CommandTimeout = 10000;

            if (conn.State == 0)
            {
                if (ConnPassword.Trim() == "")
                {
                    conn.Open();
                }
                else
                {
                    conn.Open(ExchequerCommonSQLConnection, "", ConnPassword.Trim(),
                              (int)ADODB.ConnectModeEnum.adModeUnknown);
                }
            }
            conn.CursorLocation = ADODB.CursorLocationEnum.adUseClient;

            System.Data.DataTable dataTable = new System.Data.DataTable {
                TableName = "resultSet"
            };

            try
            {
                cmd.CommandType      = ADODB.CommandTypeEnum.adCmdText;
                cmd.ActiveConnection = conn;
                ADODB.Recordset recordSet = null;
                object          objRecAff;
                recordSet = (ADODB.Recordset)cmd.Execute(out objRecAff, Type.Missing, (int)ADODB.CommandTypeEnum.adCmdText);

                System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
                adapter.Fill(dataTable, recordSet);

                if (conn.State == 1)
                {
                    conn.Close();
                }
            }
            catch
            {
                throw;
            }

            Type officeType = Type.GetTypeFromProgID("Excel.Application");

            if (officeType == null)
            {
                //no Excel installed
                SaveFileDialog.Filter           = "XML File | *.xml";
                SaveFileDialog.InitialDirectory = ExchequerPath + "\\Logs";
                SaveFileDialog.DefaultExt       = "XML";
                SaveFileDialog.OverwritePrompt  = true;
                SaveFileDialog.FileName         = "ExchSQLDataValidationResults";
                if (CompanyCode != null)
                {
                    SaveFileDialog.FileName = SaveFileDialog.FileName + "-" + CompanyCode;
                }
                SaveFileDialog.ShowDialog();
                this.UseWaitCursor = true;

                txtCompanyName.Enabled  = false;
                txtContactName.Enabled  = false;
                txtEmailAddress.Enabled = false;
                btnSaveResults.Enabled  = false;
                System.Windows.Forms.Application.DoEvents();

                XmlTextWriter writer = new XmlTextWriter(@SaveFileDialog.FileName, null);
                writer.WriteStartDocument(true);
                writer.Formatting = Formatting.Indented;

                writer.WriteStartElement("SQLDataValidationResults");

                writer.WriteStartElement("CompanyName");
                writer.WriteString(txtCompanyName.Text);
                writer.WriteEndElement();

                writer.WriteStartElement("ContactName");
                writer.WriteString(txtContactName.Text);
                writer.WriteEndElement();

                writer.WriteStartElement("EmailAddress");
                writer.WriteString(txtEmailAddress.Text);
                writer.WriteEndElement();

                writer.WriteStartElement("VersionInfo");
                writer.WriteString(VersionInfo);
                writer.WriteEndElement();

                dataTable.WriteXml(writer);

                writer.WriteEndDocument();

                writer.Close();
            }
            else
            {
                //Excel installed
                SaveFileDialog.Filter           = "Excel File | *.xlsx";
                SaveFileDialog.InitialDirectory = ExchequerPath + "\\Logs";
                SaveFileDialog.DefaultExt       = "XLSX";
                SaveFileDialog.OverwritePrompt  = true;
                SaveFileDialog.FileName         = "ExchSQLDataValidationResults";
                if (CompanyCode != null)
                {
                    SaveFileDialog.FileName = SaveFileDialog.FileName + "-" + CompanyCode;
                }
                SaveFileDialog.ShowDialog();

                this.UseWaitCursor = true;

                txtCompanyName.Enabled  = false;
                txtContactName.Enabled  = false;
                txtEmailAddress.Enabled = false;
                btnSaveResults.Enabled  = false;
                System.Windows.Forms.Application.DoEvents();

                clsExcelUtlity obj = new Data_Integrity_Checker.clsExcelUtlity();

                obj.WriteDataTableToExcel(dataTable, "ExchSQL Data Validation Results", SaveFileDialog.FileName, txtCompanyName.Text, txtContactName.Text, txtEmailAddress.Text, VersionInfo);
            }

            this.UseWaitCursor = false;
            dataTable          = null;

            Close();
        }
Exemplo n.º 53
0
 public void ToXml(XmlTextWriter writer, UGUI nextOwner, XmlSerializationOptions options)
 {
     writer.WriteNamedValue("InventorySerial", InventorySerial);
     writer.WriteStartElement("TaskInventory");
     {
         foreach (ObjectPartInventoryItem item in Values)
         {
             writer.WriteStartElement("TaskInventoryItem");
             {
                 writer.WriteUUID("AssetID", (options & XmlSerializationOptions.AdjustForNextOwner) != 0 ? item.NextOwnerAssetID : item.AssetID);
                 writer.WriteNamedValue("BasePermissions", (uint)item.Permissions.Base);
                 writer.WriteNamedValue("CreationDate", item.CreationDate.AsUInt);
                 writer.WriteUUID("CreatorID", item.Creator.ID);
                 if (!string.IsNullOrEmpty(item.Creator.CreatorData))
                 {
                     writer.WriteNamedValue("CreatorData", item.Creator.CreatorData);
                 }
                 writer.WriteNamedValue("Description", item.Description);
                 writer.WriteNamedValue("EveryonePermissions", (uint)item.Permissions.EveryOne);
                 writer.WriteNamedValue("Flags", (uint)item.Flags);
                 if ((options & XmlSerializationOptions.WriteOwnerInfo) != XmlSerializationOptions.None)
                 {
                     writer.WriteNamedValue("GroupID", item.Group.ID);
                 }
                 else
                 {
                     writer.WriteNamedValue("GroupID", UUID.Zero);
                 }
                 writer.WriteNamedValue("GroupPermissions", (uint)item.Permissions.Group);
                 writer.WriteNamedValue("InvType", (uint)item.InventoryType);
                 writer.WriteUUID("ItemID", item.ID);
                 writer.WriteUUID("OldItemID", UUID.Zero);
                 writer.WriteUUID("LastOwnerID", item.LastOwner.ID);
                 writer.WriteNamedValue("Name", item.Name);
                 writer.WriteNamedValue("NextPermissions", (uint)item.Permissions.NextOwner);
                 if ((options & XmlSerializationOptions.WriteOwnerInfo) != XmlSerializationOptions.None)
                 {
                     writer.WriteUUID("OwnerID", item.Owner.ID);
                     writer.WriteNamedValue("CurrentPermissions", (uint)item.Permissions.Current);
                 }
                 else if ((options & XmlSerializationOptions.AdjustForNextOwner) != XmlSerializationOptions.None)
                 {
                     writer.WriteUUID("OwnerID", nextOwner.ID);
                     writer.WriteNamedValue("CurrentPermissions", (uint)item.Permissions.NextOwner);
                 }
                 else
                 {
                     writer.WriteUUID("OwnerID", UUID.Zero);
                     writer.WriteNamedValue("CurrentPermissions", (uint)item.Permissions.Current);
                 }
                 writer.WriteUUID("ParentID", item.ParentFolderID);
                 writer.WriteUUID("ParentPartID", item.ParentFolderID);
                 var grantinfo = item.PermsGranter;
                 writer.WriteUUID("PermsGranter", grantinfo.PermsGranter.ID);
                 writer.WriteNamedValue("PermsMask", (uint)grantinfo.PermsMask);
                 writer.WriteNamedValue("Type", (int)item.AssetType);
                 writer.WriteNamedValue("OwnerChanged", (options & XmlSerializationOptions.AdjustForNextOwner) != XmlSerializationOptions.None);
                 UEI experienceID = item.ExperienceID;
                 if (experienceID != UEI.Unknown)
                 {
                     writer.WriteNamedValue("ExperienceID", experienceID.ToString());
                 }
                 {
                     ObjectPartInventoryItem.CollisionFilterParam p = item.CollisionFilter;
                     if (p.ID != UUID.Zero || p.Name?.Length != 0)
                     {
                         writer.WriteStartElement("CollisionFilter");
                         writer.WriteNamedValue("Name", p.Name);
                         writer.WriteNamedValue("ID", p.ID);
                         writer.WriteNamedValue("Type", p.Type.ToString());
                         writer.WriteEndElement();
                     }
                 }
             }
             writer.WriteEndElement();
         }
     }
     writer.WriteEndElement();
 }
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            int    x  = 0;
            string st = x.ToString();

            if (Name.Text == "" || starting.Text == "")
            {
                MessageBox.Show("Please fill the required information !");
            }

            else if (!File.Exists("Clubs.xml"))
            {
                XmlTextWriter document = new XmlTextWriter("Clubs.xml", Encoding.UTF8);

                document.Formatting = Formatting.Indented;
                document.WriteStartDocument();
                document.WriteStartElement("Clubs");
                document.WriteStartElement("Club");

                document.WriteStartElement("Club_Name");
                document.WriteString(Name.Text);
                document.WriteEndElement();

                document.WriteStartElement("Starting_Date");
                document.WriteString(starting.Text);
                document.WriteEndElement();

                document.WriteStartElement("Club_Teams");
                document.WriteString(st);
                document.WriteEndElement();

                document.WriteStartElement("Club_Championships");
                document.WriteString(st);
                document.WriteEndElement();

                document.WriteStartElement("Club_Sponsors");
                document.WriteString(st);
                document.WriteEndElement();

                document.WriteEndElement();
                document.WriteEndElement();
                document.WriteEndDocument();

                document.Close();

                MessageBox.Show("Club Successfuly Added.");
            }
            else

            {
                XmlDocument doc = new XmlDocument();
                doc.Load("Clubs.xml");

                XmlNode clubss = doc.CreateElement("Club");

                XmlNode club_Name = doc.CreateElement("Club_Name");
                club_Name.InnerText = Name.Text;
                clubss.AppendChild(club_Name);

                XmlNode Starting = doc.CreateElement("starting_Date");
                Starting.InnerText = starting.Text;
                clubss.AppendChild(Starting);

                XmlNode Clubteams = doc.CreateElement("Club_Teams");
                Clubteams.InnerText = st;
                clubss.AppendChild(Clubteams);

                XmlNode champion = doc.CreateElement("Club_Championships");
                champion.InnerText = st;
                clubss.AppendChild(champion);

                XmlNode sponsor = doc.CreateElement("Club_Sponsors");
                sponsor.InnerText = st;
                clubss.AppendChild(sponsor);

                doc.DocumentElement.AppendChild(clubss);
                doc.Save("Clubs.xml");

                MessageBox.Show("Club Successfuly Added.");
            }
        }
        public DomesticResponse ProcessRequest(DomesticRequest request)
        {
            LastResponse = string.Empty;
            LastRequest  = string.Empty;

            // Validate Request First
            var result = ValidateRequest(request);

            if (result.Errors.Count > 0)
            {
                return(result);
            }

            try
            {
                var sURL = request.ApiUrl;
                sURL += "?API=RateV4&XML=";

                // Build XML
                var requestXml = string.Empty;

                var sw = new StringWriter(CultureInfo.InvariantCulture);
                var xw = new XmlTextWriter(sw)
                {
                    Formatting = Formatting.None
                };

                // Start Request
                xw.WriteStartElement("RateV4Request");
                xw.WriteAttributeString("USERID", request.UserId);
                xw.WriteElementString("Revision", request.Revision);

                foreach (var pak in request.Packages)
                {
                    pak.WriteToXml(ref xw);
                }

                //End Rate Request
                xw.WriteEndElement();
                xw.Flush();
                xw.Close();

                requestXml = sw.GetStringBuilder().ToString();

                if (!requestXml.StartsWith("<"))
                {
                    requestXml = requestXml.Substring(1, requestXml.Length - 1);
                }

                // Diagnostics
                LastRequest = requestXml;

                var sResponse  = string.Empty;
                var dataToSend = sURL + HttpUtility.UrlEncode(requestXml);

                sResponse = readHtmlPage(dataToSend);

                // Diagnostics
                LastResponse = sResponse;

                result = new DomesticResponse(sResponse);
            }
            catch (Exception ex)
            {
                result.Errors.Add(new USPSError
                {
                    Description = ex.Message + " " + ex.StackTrace,
                    Source      = "HCC Exception"
                });
            }
            return(result);
        }
Exemplo n.º 56
0
 public override void FinishObject()
 {
     m_Xml.WriteEndElement();
 }
Exemplo n.º 57
0
        private void InitializeWriter()
        {
            if (xmlTextWriter == null)
            {
                //

                bool writeHeaderRequired = false;

                if (textWriter != null)
                {
                    textWriter.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                    writeHeaderRequired = true;

                    xmlTextWriter = new XmlTextWriter(textWriter);
                }
                else if (stream != null)
                {
                    xmlTextWriter = new XmlTextWriter(stream, System.Text.Encoding.UTF8);
                }
                else
                {
                    Debug.Assert(fileName != null, "Nothing to output to");
                    xmlTextWriter = new XmlTextWriter(fileName, System.Text.Encoding.UTF8);
                }
                xmlTextWriter.Formatting  = Formatting.Indented;
                xmlTextWriter.Indentation = 2;

                if (!writeHeaderRequired)
                {
                    xmlTextWriter.WriteStartDocument(); // writes <?xml version="1.0" encoding="utf-8"?>
                }
            }
            else
            {
                xmlTextWriter.WriteStartDocument();
            }

            xmlTextWriter.WriteStartElement("root");
            XmlTextReader reader = new XmlTextReader(new StringReader(ResourceSchema));

            reader.WhitespaceHandling = WhitespaceHandling.None;
            xmlTextWriter.WriteNode(reader, true);

            xmlTextWriter.WriteStartElement(ResHeaderStr); {
                xmlTextWriter.WriteAttributeString(NameStr, ResMimeTypeStr);
                xmlTextWriter.WriteStartElement(ValueStr); {
                    xmlTextWriter.WriteString(ResMimeType);
                }
                xmlTextWriter.WriteEndElement();
            }
            xmlTextWriter.WriteEndElement();
            xmlTextWriter.WriteStartElement(ResHeaderStr); {
                xmlTextWriter.WriteAttributeString(NameStr, VersionStr);
                xmlTextWriter.WriteStartElement(ValueStr); {
                    xmlTextWriter.WriteString(Version);
                }
                xmlTextWriter.WriteEndElement();
            }
            xmlTextWriter.WriteEndElement();
            xmlTextWriter.WriteStartElement(ResHeaderStr); {
                xmlTextWriter.WriteAttributeString(NameStr, ReaderStr);
                xmlTextWriter.WriteStartElement(ValueStr); {
                    xmlTextWriter.WriteString(MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXResourceReader), this.typeNameConverter));
                }
                xmlTextWriter.WriteEndElement();
            }
            xmlTextWriter.WriteEndElement();
            xmlTextWriter.WriteStartElement(ResHeaderStr); {
                xmlTextWriter.WriteAttributeString(NameStr, WriterStr);
                xmlTextWriter.WriteStartElement(ValueStr); {
                    xmlTextWriter.WriteString(MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXResourceWriter), this.typeNameConverter));
                }
                xmlTextWriter.WriteEndElement();
            }
            xmlTextWriter.WriteEndElement();

            initialized = true;
        }
Exemplo n.º 58
0
        private void xmlcamera(bool write, string filename = "cameras.xml")
        {
            bool exists = File.Exists(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + filename);

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

                    xmlwriter.WriteStartDocument();

                    xmlwriter.WriteStartElement("Cameras");

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

                    xmlwriter.WriteEndElement();

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

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

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

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

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

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

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

                                        case "Camera":
                                            cameras[camera.name] = camera;
                                            dobreak = true;
                                            break;
                                        }
                                        if (dobreak)
                                        {
                                            break;
                                        }
                                    }
                                    string temp = xmlreader.ReadString();
                                }
                                break;

                                case "Config":
                                    break;

                                case "xml":
                                    break;

                                default:
                                    if (xmlreader.Name == "")     // line feeds
                                    {
                                        break;
                                    }
                                    //config[xmlreader.Name] = xmlreader.ReadString();
                                    break;
                                }
                            }
                            catch (Exception ee) { Console.WriteLine(ee.Message); } // silent fail on bad entry
                        }
                    }
                }
                catch (Exception ex) { Console.WriteLine("Bad Camera File: " + ex.ToString()); } // bad config file

                // populate list
                foreach (var camera in cameras.Values)
                {
                    if (!CMB_camera.Items.Contains(camera.name))
                    {
                        CMB_camera.Items.Add(camera.name);
                    }
                }
            }
        }
Exemplo n.º 59
0
        private Stream SignedInfoTransformed()
        {
            Transform t = GetC14NMethod();

            if (signatureElement == null)
            {
                // when creating signatures
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                doc.LoadXml(m_signature.SignedInfo.GetXml().OuterXml);
                if (envdoc != null)
                {
                    foreach (XmlAttribute attr in envdoc.DocumentElement.SelectNodes("namespace::*"))
                    {
                        if (attr.LocalName == "xml")
                        {
                            continue;
                        }
                        if (attr.Prefix == doc.DocumentElement.Prefix)
                        {
                            continue;
                        }
                        doc.DocumentElement.SetAttributeNode(doc.ImportNode(attr, true) as XmlAttribute);
                    }
                }
                t.LoadInput(doc);
            }
            else
            {
                // when verifying signatures
                // TODO - check m_signature.SignedInfo.Id
                XmlElement    el  = signatureElement.GetElementsByTagName(XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI) [0] as XmlElement;
                StringWriter  sw  = new StringWriter();
                XmlTextWriter xtw = new XmlTextWriter(sw);
                xtw.WriteStartElement(el.Prefix, el.LocalName, el.NamespaceURI);

                // context namespace nodes (except for "xmlns:xml")
                XmlNodeList nl = el.SelectNodes("namespace::*");
                foreach (XmlAttribute attr in nl)
                {
                    if (attr.ParentNode == el)
                    {
                        continue;
                    }
                    if (attr.LocalName == "xml")
                    {
                        continue;
                    }
                    if (attr.Prefix == el.Prefix)
                    {
                        continue;
                    }
                    attr.WriteTo(xtw);
                }
                foreach (XmlNode attr in el.Attributes)
                {
                    attr.WriteTo(xtw);
                }
                foreach (XmlNode n in el.ChildNodes)
                {
                    n.WriteTo(xtw);
                }

                xtw.WriteEndElement();
                byte [] si = Encoding.UTF8.GetBytes(sw.ToString());

                MemoryStream ms = new MemoryStream();
                ms.Write(si, 0, si.Length);
                ms.Position = 0;

                t.LoadInput(ms);
            }
            // C14N and C14NWithComments always return a Stream in GetOutput
            return((Stream)t.GetOutput());
        }
Exemplo n.º 60
0
        protected override List <RelationShip> CopyPart(XmlReader xtr, XmlTextWriter xtw, string ns, string partName, ZipReader archive)
        {
            bool isInRel                = false;
            bool extractRels            = ns.Equals(RELATIONSHIP_NS);
            bool fieldBegin             = false;
            bool isInIndex              = false;
            List <RelationShip> rels    = new List <RelationShip>();
            Stack <string>      context = new Stack <string>();

            XmlDocument xmlDocument  = new XmlDocument();
            XmlNode     bookmarkNode = null;

            RelationShip rel = new RelationShip();

            while (xtr.Read())
            {
                switch (xtr.NodeType)
                {
                case XmlNodeType.Attribute:
                    break;

                case XmlNodeType.CDATA:
                    xtw.WriteCData(xtr.Value);
                    break;

                case XmlNodeType.Comment:
                    xtw.WriteComment(xtr.Value);
                    break;

                case XmlNodeType.DocumentType:
                    xtw.WriteDocType(xtr.Name, null, null, null);
                    break;

                case XmlNodeType.Element:
                    if (extractRels && xtr.LocalName == "Relationship" && xtr.NamespaceURI == RELATIONSHIP_NS)
                    {
                        isInRel = true;
                        rel     = new RelationShip();
                    }

                    if ((xtr.Name.Equals("w:bookmarkEnd") || xtr.Name.Equals("w:bookmarkStart")) &&
                        (xtr.Depth == 1 || (ns.Equals("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument") && xtr.Depth == 2)))
                    {
                        // opening and closing bookmark tags below w:body (or below w:hdr, w:ftr, w:footnotes etc) will be moved inside the following w:p tag
                        // because in ODF bookmarks can only be opened and closed in paragraph-content
                        bookmarkNode = xmlDocument.CreateElement(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI);
                        if (xtr.HasAttributes)
                        {
                            while (xtr.MoveToNextAttribute())
                            {
                                XmlAttribute xmlAttribute = xmlDocument.CreateAttribute(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI);
                                xmlAttribute.Value = xtr.Value;
                                bookmarkNode.Attributes.Append(xmlAttribute);
                            }
                        }
                    }
                    else if (!xtr.LocalName.Equals("proofErr"))
                    {
                        context.Push(xtr.Name);
                        xtw.WriteStartElement(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI);

                        if (xtr.HasAttributes)
                        {
                            while (xtr.MoveToNextAttribute())
                            {
                                if (extractRels && isInRel)
                                {
                                    if (xtr.LocalName == "Type")
                                    {
                                        rel.Type = xtr.Value;
                                    }
                                    else if (xtr.LocalName == "Target")
                                    {
                                        rel.Target = xtr.Value;
                                    }
                                    else if (xtr.LocalName == "Id")
                                    {
                                        rel.Id = xtr.Value;
                                    }
                                }

                                if (!xtr.LocalName.StartsWith("rsid"))
                                {
                                    string value = xtr.Value;
                                    // normalize type ST_OnOff
                                    if (value == "on" || value == "true")
                                    {
                                        value = "1";
                                    }
                                    else if (value == "off" || value == "false")
                                    {
                                        value = "0";
                                    }

                                    xtw.WriteAttributeString(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI, value);
                                }

                                switch (xtr.LocalName)
                                {
                                case "fldCharType":
                                    if (xtr.Value.Equals("begin"))
                                    {
                                        fieldBegin = true;
                                        _insideField++;
                                        _fieldId++;
                                    }
                                    if (xtr.Value.Equals("end"))
                                    {
                                        fieldBegin = false;
                                        _insideField--;
                                        if (_insideField == 0)
                                        {
                                            isInIndex = false;
                                        }
                                    }
                                    break;

                                case "fldLock":
                                    _fieldLocked = (xtr.Value.Equals("on") || xtr.Value.Equals("true") || xtr.Value.Equals("1")) ? 1 : 0;
                                    break;
                                }
                            }
                            xtr.MoveToElement();
                        }

                        if (isInRel)
                        {
                            isInRel = false;
                            rels.Add(rel);
                        }

                        switch (xtr.LocalName)
                        {
                        case "p":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, _paraId.ToString());
                            xtw.WriteAttributeString(NS_PREFIX, "s", PACKAGE_NS, _sectPrId.ToString());
                            _paraId++;

                            if (bookmarkNode != null)
                            {
                                xtw.WriteStartElement(bookmarkNode.Prefix, bookmarkNode.LocalName, bookmarkNode.NamespaceURI);

                                foreach (XmlAttribute attrib in bookmarkNode.Attributes)
                                {
                                    xtw.WriteAttributeString(attrib.Prefix, attrib.LocalName, attrib.NamespaceURI, attrib.Value);
                                }
                                xtw.WriteEndElement();
                                bookmarkNode = null;
                            }

                            // re-trigger field translation for fields spanning across multiple paragraphs
                            if (_insideField > 0)
                            {
                                fieldBegin = true;
                            }

                            if (isInIndex)
                            {
                                xtw.WriteAttributeString(NS_PREFIX, "index", PACKAGE_NS, "1");
                            }

                            break;

                        case "altChunk":
                        case "bookmarkEnd":
                        case "bookmarkStart":
                        case "commentRangeEnd":
                        case "commentRangeStart":
                        case "del":
                        case "ins":
                        case "moveFrom":
                        case "moveFromRangeEnd":
                        case "moveFromRangeStart":
                        case "moveToRangeEnd":
                        case "moveToRangeStart":
                        case "oMath":
                        case "oMathPara":
                        case "permEnd":
                        case "permStart":
                        case "proofErr":
                        case "sdt":
                        case "tbl":
                            // write the id of the following w:p
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, _paraId.ToString());

                            // write the id of the current section
                            xtw.WriteAttributeString(NS_PREFIX, "s", PACKAGE_NS, _sectPrId.ToString());
                            break;

                        case "r":
                            if (_insideField > 0)
                            {
                                // add an attribute if we are inside a field definition
                                xtw.WriteAttributeString(NS_PREFIX, "f", PACKAGE_NS, _insideField.ToString());
                                xtw.WriteAttributeString(NS_PREFIX, "fid", PACKAGE_NS, _fieldId.ToString());

                                // also add the id of the current paragraph so we can get the display value of the
                                // field for a specific paragraph easily. This is to support multi-paragraph fields.
                                xtw.WriteAttributeString(NS_PREFIX, "fpid", PACKAGE_NS, _paraId.ToString());

                                // also add a marker indicating whether a field is locked or not
                                xtw.WriteAttributeString(NS_PREFIX, "flocked", PACKAGE_NS, _fieldLocked.ToString());

                                if (fieldBegin)
                                {
                                    // add markup to the first run of a field so that we can trigger field
                                    // translation later in template InsertComplexField
                                    // This is also used to support multi-paragraph fields.
                                    //
                                    xtw.WriteAttributeString(NS_PREFIX, "fStart", PACKAGE_NS, "1");
                                    fieldBegin   = false;
                                    _fieldLocked = 0;
                                }
                            }
                            break;

                        case "sectPr":
                            xtw.WriteAttributeString(NS_PREFIX, "s", PACKAGE_NS, _sectPrId.ToString());
                            _sectPrId++;
                            break;

                        case "fldSimple":
                            if (!xtr.IsEmptyElement)
                            {
                                _insideField++;
                            }
                            break;
                        }

                        if (xtr.IsEmptyElement)
                        {
                            xtw.WriteEndElement();
                            context.Pop();
                        }
                    }
                    break;

                case XmlNodeType.EndElement:
                    if (xtr.LocalName.Equals("fldSimple"))
                    {
                        _insideField--;
                    }
                    if (!xtr.LocalName.Equals("proofErr"))
                    {
                        xtw.WriteEndElement();
                        context.Pop();
                    }
                    if (_insideField == 0)
                    {
                        isInIndex = false;
                    }
                    break;

                case XmlNodeType.EntityReference:
                    xtw.WriteEntityRef(xtr.Name);
                    break;

                case XmlNodeType.ProcessingInstruction:
                    xtw.WriteProcessingInstruction(xtr.Name, xtr.Value);
                    break;

                case XmlNodeType.SignificantWhitespace:
                    xtw.WriteWhitespace(xtr.Value);
                    break;

                case XmlNodeType.Text:
                    if (context.Count > 0 && context.Peek().Equals("w:instrText"))
                    {
                        if (xtr.Value.ToUpper().Contains("TOC") || xtr.Value.ToUpper().Contains("BIBLIOGRAPHY") || xtr.Value.ToUpper().Contains("INDEX"))
                        {
                            isInIndex = true;
                        }
                    }
                    xtw.WriteString(xtr.Value);
                    break;

                case XmlNodeType.Whitespace:
                    xtw.WriteWhitespace(xtr.Value);
                    break;

                case XmlNodeType.XmlDeclaration:
                    // omit XML declaration
                    break;

                default:
                    Debug.Assert(false);
                    break;
                }
            }

            _paraId++;
            _sectPrId++;

            return(rels);
        }