コード例 #1
1
ファイル: DefinitionsGenerator.cs プロジェクト: LogoFX/tools
        public void CreateDefinitions(WizardConfiguration wizardConfiguration)
        {
            var projectCollection = new XElement(Ns + "ProjectCollection");

            var doc = new XDocument(
                new XElement(Ns + "VSTemplate",
                    new XAttribute("Version", "3.0.0"),
                    new XAttribute("Type", "ProjectGroup"),
                    new XElement(Ns + "TemplateData",
                        new XElement(Ns + "Name", wizardConfiguration.Name),
                        new XElement(Ns + "Description", wizardConfiguration.Description),
                        new XElement(Ns + "ProjectType", wizardConfiguration.ProjectType),
                        new XElement(Ns + "DefaultName", wizardConfiguration.DefaultName),
                        new XElement(Ns + "SortOrder", wizardConfiguration.SortOrder),
                        new XElement(Ns + "Icon", wizardConfiguration.IconName)),
                    new XElement(Ns + "TemplateContent", projectCollection),
                    MakeWizardExtension(
                        "LogoFX.Tools.Templates.Wizard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        $"LogoFX.Tools.Templates.Wizard.SolutionWizard")
                    ));

            XmlWriterSettings settings = new XmlWriterSettings
            {
                OmitXmlDeclaration = true,
                Indent = true
            };

            var definitionFile = GetDefinitionFileName();

            using (XmlWriter xw = XmlWriter.Create(definitionFile, settings))
            {
                doc.Save(xw);
            }
        }
コード例 #2
0
ファイル: Images.aspx.cs プロジェクト: BehnamAbdy/Ajancy
    protected void btnSave_Click(object sender, EventArgs e)
    {
        doc = XDocument.Load(Server.MapPath("~/App_Data/Images.xml"));
        if (this.drpLetters.SelectedIndex > 0) // Edit mode
        {
            IEnumerable<XElement> elements = doc.Element("Images").Elements("Image").Where(an => an.Attribute("id").Value == this.drpLetters.SelectedValue);
            foreach (XElement item in elements)
            {
                item.Attribute("isActive").Value = this.chkIsActive.Checked.ToString();
                item.Element("Title").Value = this.txtTitle.Text;
            }
            doc.Save(Server.MapPath("~/App_Data/Images.xml"));
            if (this.fluLetter.HasFile)
            {
                if (this.fluLetter.PostedFile.ContentType.Equals("image/pjpeg") || this.fluLetter.PostedFile.ContentType.Equals("image/x-png"))
                {
                    string file = string.Format("{0}/{1}.jpg", Server.MapPath("~/LettImg"), this.drpLetters.SelectedValue);
                    System.IO.File.Delete(file);
                    this.fluLetter.PostedFile.SaveAs(file);
                }
                else
                {
                    this.lblMessage.Text = "فرمت عکس jpg نمیباشد";
                }
            }
            this.lblMessage.Text = Public.EDITMESSAGE;
        }
        else // Add mode
        {
            if (this.fluLetter.HasFile)
            {
                if (this.fluLetter.PostedFile.ContentType.Equals("image/pjpeg") || this.fluLetter.PostedFile.ContentType.Equals("image/x-png"))
                {
                    string maxId = doc.Element("Images").Elements("Image").Max(tst => tst.Attribute("id").Value);
                    string nextId = maxId == null ? "1" : (byte.Parse(maxId) + 1).ToString();
                    doc.Element("Images").Add(new XElement("Image", new XAttribute("id", nextId),
                                                                                         new XAttribute("isActive", this.chkIsActive.Checked.ToString()),
                                                                                         new XElement("Title", this.txtTitle.Text.Trim())));

                    doc.Save(Server.MapPath("~/App_Data/Images.xml"));
                    this.fluLetter.PostedFile.SaveAs(string.Format("{0}/{1}.jpg", Server.MapPath("~/LettImg"), nextId));
                    this.lblMessage.Text = Public.SAVEMESSAGE;
                }
                else
                {
                    this.lblMessage.Text = "فرمت عکس jpg نمیباشد";
                }
            }
        }

        this.drpLetters.DataSource = doc.Element("Images").Elements("Image").Select(an => new { Id = an.Attribute("id").Value, Title = an.Element("Title").Value });
        this.drpLetters.DataBind();
        this.drpLetters.Items.Insert(0, "- جدید -");
        this.drpLetters.SelectedIndex = 0;
        this.chkIsActive.Checked = false;
        this.txtTitle.Text = null;
        this.imgLetter.ImageUrl = null;
    }
コード例 #3
0
ファイル: LocalConfigService.cs プロジェクト: RyanFu/shoperp
        public static void UpdateValue(string name, string value)
        {
            XElement xe = GetXElement(name);

            if (xe == null)
            {
                xe = new XElement(name, value.Trim());
                xDoc.Root.Add(xe);
            }
            xe.Value = value.Trim();
            xDoc.Save(CONFIG_PATH);
        }
コード例 #4
0
 public override void SaveImages(Stream stream)
 {
     var xdocument = new XDocument();
     var xelement = new XElement("images");
     xdocument.Add(xelement);
     xdocument.Save(stream);
 }
コード例 #5
0
        protected override void ProcessRecord()
        {
            string path = null;

            XDocument document = null;

                // check for existing configuration, if not existing, create it
                string appDataFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string configFolder = System.IO.Path.Combine(appDataFolder, "Contoso.PSOnline.PowerShell");
                if (!Directory.Exists(configFolder))
                {
                    Directory.CreateDirectory(configFolder);
                }
                path = System.IO.Path.Combine(configFolder, "configuration.xml");

            if (!File.Exists(path))
            {
                document = new XDocument(new XDeclaration("1.0", "UTF-8", string.Empty));
                var configElement = new XElement("items");
                var siteProvisionServiceUrlElement = new XElement("item", new XAttribute("key", "RelativeSiteProvisionServiceUrl"));
                siteProvisionServiceUrlElement.Value = "/_vti_bin/contoso.services.sitemanager/sitemanager.svc";
                configElement.Add(siteProvisionServiceUrlElement);
                document.Add(configElement);

                document.Save(path);
            }
            else
            {
                document = XDocument.Load(path);
            }
            var itemsElement = document.Element("items");
            if (Value != null)
            {
                var items = from item in document.Descendants("item")
                            where item.Attribute("key").Value == Key
                            select item;
                if(items.Count() > 0)
                {
                    items.FirstOrDefault().Value = Value;
                }
                else
                {
                    var itemElement = new XElement("item", new XAttribute("key", Key));
                    itemElement.Value = Value;
                    itemsElement.Add(itemElement);
                }
            }
            else
            {
                var items = from item in document.Descendants("item")
                            where item.Attribute("key").Value == Key
                            select item;
                if(items.Count() > 0)
                {
                    items.FirstOrDefault().Remove();
                }
            }

            document.Save(path);
        }
コード例 #6
0
        //------------------------------------------------------------------------------------------------
        //Xmlデータを初期化する
        //------------------------------------------------------------------------------------------------
        public void XmlAllDelete()
        {
            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database(), LoadOptions.PreserveWhitespace);

            //Xmlファイル内を検索
            //ぜんぶけす
            try
            {
                var query = from y in XmlDoc.Descendants("Chord")
                            select y;

                foreach (XElement item in query.ToList())
                {
                    item.Remove();
                    XmlDoc.Save(createConfigXML.CurrentPath_database());
                }
            }
            catch (Exception ex)
            {
            }

            MessageBox.Show("更新が完了しました。",
                            "Infomation", MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
        }
コード例 #7
0
        public static void Main()
        {
            var context = new GeographyEntities();
            var countries = context.Countries;

            var countriesQuery = countries
                .Where(c => c.Monasteries.Any())
                .OrderBy(c => c.CountryName)
                .Select(c => new
                {
                    c.CountryName,
                    Monasteries = c.Monasteries
                        .OrderBy(m => m.Name)
                        .Select(m => m.Name)
                });

            // Build the output XML
            var xmlMonasteries = new XElement("monasteries");
            foreach (var country in countriesQuery)
            {
                var xmlCountry = new XElement("country");
                xmlCountry.Add(new XAttribute("name", country.CountryName));

                foreach (var monastery in country.Monasteries)
                {
                    xmlCountry.Add(new XElement("monastery", monastery));
                }

                xmlMonasteries.Add(xmlCountry);
            }
            Console.WriteLine(xmlMonasteries);

            var xmlDoc = new XDocument(xmlMonasteries);
            xmlDoc.Save(@"..\..\monasteries.xml");
        }
コード例 #8
0
ファイル: XMLProcess.cs プロジェクト: thachgiasoft/qAustfeed
    public void Update(string fileName, MathRule mathRule)
    {
        System.Xml.Linq.XDocument document = System.Xml.Linq.XDocument.Load(fileName);
        var node = (from t in document.Descendants("Column")
                    where t.Element("DataBase").Value == mathRule.ColumnInDB
                    select t).FirstOrDefault();

        // check exist element excel
        string[]      arr  = node.Element("Excel").Value.Split(';');
        List <string> list = new List <string>();

        for (int i = 0; i < arr.Length; i++)
        {
            list.Add(arr[i].Trim());
        }
        if (!list.Contains(mathRule.ColumnInExcel.Trim()))
        {
            node.Element("Excel").Value += ";" + mathRule.ColumnInExcel;
        }
        // end check
        //node.Attribute("AllowBlank").Value = mathRule.AllowBlank;
        //node.Attribute("DataType").Value = mathRule.DataType;
        //node.Attribute("DisplayOnGrid").Value = mathRule.DisplayOnGrid.ToString();
        //if (!string.IsNullOrEmpty(mathRule.DefaultValue))
        //    node.Attribute("DefaultValue").Value = mathRule.DefaultValue;
        //else
        //    node.Attribute("DefaultValue").Value = "";
        document.Save(fileName);
    }
コード例 #9
0
        static void Main(string[] args)
        {
            var db = new GeographyEntities();
            var countries = db.Countries
            .OrderBy(c => c.CountryName)
            .Select(c => new
            {
                coutryName = c.CountryName,
                monasteries = c.Monasteries.OrderBy(m => m.Name).Select(m => m.Name)
            }).ToList();

            XElement root = new XElement("monasteries");
            foreach (var country in countries)
            {
                if (country.monasteries.Count() != 0)
                {
                    var xmlCountry = new XElement("country");
                    xmlCountry.Add(new XAttribute("name", country.coutryName));
                    foreach (var xmlMonasteries in country.monasteries)
                    {
                        xmlCountry.Add(new XElement("monastery", xmlMonasteries));
                    }
                    root.Add(xmlCountry);   
                }
            }

            var xmlDoc = new XDocument(root);
            xmlDoc.Save("../../monasteries.xml");
        }
コード例 #10
0
 /// <summary>
 /// Updates the XML data.
 /// </summary>
 /// <param name="dtRow">The dt row.</param>
 /// <param name="uniqueIdentity">The unique identity.</param>
 /// <param name="type">The type.</param>
 /// <returns></returns>
 public int UpdateXmlData(DataRow dtRow, string uniqueIdentity, string type)
 {
     try
     {
         System.Xml.Linq.XDocument resultsDoc = System.Xml.Linq.XDocument.Parse((System.Xml.Linq.XDocument.Load(Datacontext.GetInstance().CorporateFavoriteFile)).ToString());
         var query = resultsDoc.Root.Descendants("Favorites");
         foreach (System.Xml.Linq.XElement e in query)
         {
             if (e.Element("UniqueIdentity").Value.ToString() == uniqueIdentity && e.Element("Type").Value.ToString() == type)
             {
                 e.Element("Category").Value     = dtRow["Category"].ToString();
                 e.Element("DisplayName").Value  = dtRow["DisplayName"].ToString();
                 e.Element("FirstName").Value    = dtRow["FirstName"].ToString();
                 e.Element("LastName").Value     = dtRow["LastName"].ToString();
                 e.Element("PhoneNumber").Value  = dtRow["PhoneNumber"].ToString();
                 e.Element("EmailAddress").Value = dtRow["EmailAddress"].ToString();
                 e.Element("Type").Value         = dtRow["Type"].ToString();
             }
         }
         resultsDoc.Save(Datacontext.GetInstance().CorporateFavoriteFile);
     }
     catch (Exception error)
     {
         _logger.Error("Error in updating favorite XMLdata : " + error.Message.ToString());
     }
     return(0);
 }
コード例 #11
0
        static void Main(string[] args)
        {
            var context = new GeographyEntities();
            var countriesQuery = context.Countries
                .Where(c => c.Monasteries.Any())
                .OrderBy(c => c.CountryName)
                .Select(c => new
                    {
                            countryName = c.CountryName,
                            monasteries = c.Monasteries
                            .OrderBy(m => m.Name)
                            .Select(m => m.Name)
                    });

            var xmlDoc = new XDocument();
            var xmlRoot = new XElement("monasteries");
            xmlDoc.Add(xmlRoot);

            foreach (var country in countriesQuery)
            {

                var countryXml = new XElement("country", new XAttribute("name", country.countryName));
                xmlRoot.Add(countryXml);

                foreach (var monastery in country.monasteries)
                {
                    var monasteryXml = new XElement("monastery", monastery);
                    countryXml.Add(monasteryXml);
                }
            }

            Console.WriteLine(xmlDoc);
            xmlDoc.Save("monasteries.xml");

        }
コード例 #12
0
        public static void Save(string path)
        {
            var document = new XDocument();
            var root = new XElement("PrettyCheckoutDatabase", new XAttribute("Version", DataReaderFileVersion));

            foreach (var product in Program.Environment.Products)
            {
                var element = new XElement("Product");
                element.Add(new XAttribute("ID", product.Index));
                element.Add(new XAttribute("Name", product.Name));
                element.Add(new XAttribute("Price", product.Price));
                element.Add(new XAttribute("PriceN", product.PriceN));
                element.Add(new XAttribute("Vat", product.Vat));
                element.Add(new XElement("Description", new XCData(product.Description == null ? string.Empty : product.Description)));

                root.Add(element);
            }

            document.Add(root);

            try
            {
                document.Save(path);
            }
            catch (Exception)
            {
                MessageBox.Show("Data file could not be saved - " + path);
            }
        }
コード例 #13
0
ファイル: XmlLoggerFacts.cs プロジェクト: hackmp/kudu
        public void XmlLoggerBasicTest()
        {
            var path = @"x:\deployments\1234\log.xml";
            var fileSystem = new Mock<IFileSystem>();
            var file = new Mock<FileBase>();
            var id = Guid.NewGuid().ToString();
            var message = Guid.NewGuid().ToString();
            var doc = new XDocument(new XElement("entries", 
                new XElement("entry",
                    new XAttribute("time", "2013-12-08T01:58:24.0247841Z"),
                    new XAttribute("id", id),
                    new XAttribute("type", "0"),
                    new XElement("message", message)
                )
            ));
            var mem = new MemoryStream();
            doc.Save(mem);

            // Setup
            fileSystem.SetupGet(f => f.File)
                      .Returns(file.Object);
            file.Setup(f => f.Exists(path))
                .Returns(true);
            file.Setup(f => f.OpenRead(path))
                .Returns(() => { mem.Position = 0; return mem; });

            // Test
            var logger = new XmlLogger(fileSystem.Object, path, Mock.Of<IAnalytics>());
            var entries = logger.GetLogEntries();

            // Assert
            Assert.Equal(1, entries.Count());
            Assert.Equal(id, entries.First().Id);
            Assert.Equal(message, entries.First().Message);
        }
コード例 #14
0
        protected void OnSubmitButton(Object s, EventArgs e)
        {
            // Create the XML document
            XDocument xml = new XDocument(
                new XElement("order",
                    new XElement("reference_number", order.GetReferenceNumber().ToString()),
                    new XElement("pizzas",
                        order.pizzas.Select(pizza => new XElement("pizza",
                            new XElement("name", pizza.name),
                            new XElement("base_toppings", pizza.base_toppings),
                            pizza.toppings.Select(topping =>
                                new XElement("extra_topping", topping.name)),
                            new XElement("cost", pizza.Cost().ToString("c"))))),
                    new XElement("total_price", order.Cost().ToString("c")),
                    new XElement("order_time", DateTime.Now.ToString())));

            // Write the XML to file
            // TODO(topher): where should this file be saved?
            string output_filename = @"C:\Users\topher\Documents\order_" +
                order.GetReferenceNumber() + ".xml";
            using (System.IO.FileStream fs =
                System.IO.File.Create(output_filename))
            {
                xml.Save(fs);
            }

            Response.Redirect("OrderComplete.aspx");
        }
コード例 #15
0
        private Action<Stream> GetXmlContents(IEnumerable<Post> model)
        {
            var blank = XNamespace.Get(@"http://www.sitemaps.org/schemas/sitemap/0.9");
            var xDocument = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement(blank+"urlset", new XAttribute("xmlns", blank.NamespaceName)));

            foreach (Post post in model)
            {
                var xElement = new XElement(blank+"url",
                                            new XElement(blank + "loc", siteUrl + post.Url),
                                            new XElement(blank + "lastmod", post.Date.ToString("yyyy-MM-dd")),
                                            new XElement(blank + "changefreq", "weekly"),
                                            new XElement(blank + "priority", "1.00"));

                xDocument.Root.Add(xElement);
            }

            return stream =>
            {
                using (XmlWriter writer = XmlWriter.Create(stream))
                {

                    xDocument.Save(writer);
                }
            };
        }
コード例 #16
0
		private async void ExportEventLogButton_Click(object sender, RoutedEventArgs e)
		{
			XDocument doc = new XDocument(
				new XDeclaration("1.0", "UTF-8", "true"),
				new XElement("LogEntries",
					from entry in (this.DataContext as MainViewModel).LogEntries
					select new XElement("LogEntry",
						new XElement("Date", entry.EventDateTimeUTC),
						new XElement("Type", entry.Level),
						new XElement("DeploymentId", entry.DeploymentId),
						new XElement("Role", entry.Role),
						new XElement("Instance", entry.RoleInstance),
						new XElement("Message", entry.Message)
					)
				)
			);

			// Configure save file dialog box
			Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
			dlg.FileName = "Export.xml";

			// Show save file dialog box
			if (dlg.ShowDialog() == true)
			{
				doc.Save(dlg.FileName);
			}
		}
コード例 #17
0
ファイル: QuoteListDAL.cs プロジェクト: akiander/December
        internal static void Save(QuoteList inQuoteList)
        {
            XDocument document = new XDocument();
            document.Add(XElement.Parse(@"<QuoteList xmlns='http://kiander.com'></QuoteList>"));
            document.Root.Add(new XAttribute("QuoteListId", inQuoteList.Id));

            foreach (IQuote quote in inQuoteList.Quotes)
            {
                XElement quoteRecord = new XElement("QuoteRecord");
                quoteRecord.Add(new XElement("QuoteID", quote.Id));
                quoteRecord.Add(new XElement("Quote", quote.Text));
                quoteRecord.Add(new XElement("Author", quote.Author));
                XElement categories = new XElement("Categories");

                if (quote.Categories != null)
                {
                    foreach (string category in quote.Categories)
                    {
                        categories.Add(new XElement("Category", category));
                    }
                }
                if (quote.Categories == null || quote.Categories.Count < 1)
                {
                    categories.Add(new XElement("Category", string.Empty));
                }
                quoteRecord.Add(categories);
                document.Root.Add(quoteRecord);
            }

            if (File.Exists(DataFileHelper.FullPath(inQuoteList.Id)))
                File.Delete(DataFileHelper.FullPath(inQuoteList.Id));

            document.Save(DataFileHelper.FullPath(inQuoteList.Id));
        }
コード例 #18
0
ファイル: WorldTests.cs プロジェクト: neaket/Dragonfly
        public void ValidateSave()
        {
            WorldEntity world = createTestWorld();

            XElement xElement = WorldTransformer.Instance.ToXElement(world, TransformerSettings.WorldNamespace + "World");

            xElement.Save("unittestsave.xml", SaveOptions.OmitDuplicateNamespaces);

            XmlSchemaSet schemaSet = new XmlSchemaSet();

            schemaSet.Add(null, "WorldSchema1.xsd");

            XDocument xDocument = new XDocument(xElement);
            xDocument.AddAnnotation(SaveOptions.OmitDuplicateNamespaces);
            xDocument.Save("unittest2.xml", SaveOptions.OmitDuplicateNamespaces);

            XElement x1 = new XElement(TransformerSettings.WorldNamespace + "Outer");
            x1.Add(new XElement(TransformerSettings.WorldNamespace + "Inner"));
            x1.Save("unittest3.xml", SaveOptions.OmitDuplicateNamespaces);
            string val = "";
            xDocument.Validate(schemaSet, (o, vea) => {
                val += o.GetType().Name + "\n";
                val += vea.Message + "\n";
            }, true);

            Assert.AreEqual("", val);
        }
コード例 #19
0
        private void CreateXmlDocument()
        {
            try
            {
                XDocument srcTree = new XDocument(
                    new XComment("This is a comment"),
                    new XElement("Root",
                        new XElement("Child1", "data1"),
                        new XElement("Child2", "data2"),
                        new XElement("Child3", "data3"),
                        new XElement("Child2", "data4"),
                        new XElement("Info5", "info5"),
                        new XElement("Info6", "info6"),
                        new XElement("Info7", "info7"),
                        new XElement("Info8", "info8")
                    )
                );

                srcTree.Save(@"C:\TestDoc\test2.xml");
                lblResult1.Text = "Document successfully saved to path: C:\\TestDoc\\test2.xml";
                lblResult1.ForeColor = System.Drawing.Color.Black;
            }
            catch (Exception ex)
            {
                lblResult1.Text = "An error occured: " + ex.Message;
                lblResult1.ForeColor = System.Drawing.Color.Red;
            }
        }
コード例 #20
0
		/// <summary>
		/// Exports data for the grammar sketch.
		/// </summary>
		/// <param name="outputPath">The output path.</param>
		/// <param name="languageProject">The language project.</param>
		public static void ExportGrammarSketch(string outputPath, ILangProject languageProject)
		{
			if (string.IsNullOrEmpty(outputPath)) throw new ArgumentNullException("outputPath");
			if (languageProject == null) throw new ArgumentNullException("languageProject");

			var servLoc = languageProject.Cache.ServiceLocator;
			const Icu.UNormalizationMode mode = Icu.UNormalizationMode.UNORM_NFC;
			var morphologicalData = languageProject.MorphologicalDataOA;
			var doc = new XDocument(
				new XDeclaration("1.0", "utf-8", "yes"),
				new XElement("M3Dump",
					ExportLanguageProject(languageProject, mode),
					ExportPartsOfSpeech(languageProject, mode),
					ExportPhonologicalData(languageProject.PhonologicalDataOA, mode),
					new XElement("MoMorphData",
						ExportCompoundRules(servLoc.GetInstance<IMoEndoCompoundRepository>(),
							servLoc.GetInstance<IMoExoCompoundRepository>(), mode),
						ExportAdhocCoProhibitions(morphologicalData, mode),
						ExportProdRestrict(morphologicalData, mode)),
					ExportMorphTypes(servLoc.GetInstance<IMoMorphTypeRepository>(), mode),
					ExportLexEntryInflTypes(servLoc.GetInstance<ILexEntryInflTypeRepository>(), mode),
					ExportLexiconFull(servLoc, mode),
					ExportFeatureSystem(languageProject.MsFeatureSystemOA, "FeatureSystem", mode),
					ExportFeatureSystem(languageProject.PhFeatureSystemOA, "PhFeatureSystem", mode)
				)
			);
			doc.Save(outputPath);
		}
コード例 #21
0
        private static void Main()
        {
            helper.ConsoleMio.Setup();
            helper.ConsoleMio.PrintHeading("Filter Albums using XDocument");

            string selctedFile = helper.SelectFileToOpen("catalogue.xml|catalogue.xml");

            var originalDoc = XDocument.Load(selctedFile);
            XNamespace ns = originalDoc.Root.GetDefaultNamespace();

            var albums = new XDocument(new XElement("albums",
                from album in originalDoc.Descendants(ns + "album")
                select new XElement(
                    "album"
                    , album.Element(ns + "name")
                    , album.Element(ns + "artist")
                )
            ));

            string saveLocation = helper.SelectSaveLocation("XML document|*.xml");

            albums.Save(saveLocation);

            helper.ConsoleMio.PrintColorText("Completed\n ", ConsoleColor.Green);

            helper.ConsoleMio.Restart(Main);
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: JustLogic/EatCodeLive
        public void get_report_list()
        {
            var username = "";
            var password = "";

            var ub = new UriBuilder("https", "reports.office365.com");
            ub.Path = "ecp/reportingwebservice/reporting.svc";
            var fullRestURL = Uri.EscapeUriString(ub.Uri.ToString());
            var request = (HttpWebRequest)HttpWebRequest.Create(fullRestURL);
            request.Credentials = new NetworkCredential(username, password);

            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                var encode = System.Text.Encoding.GetEncoding("utf-8");
                var readStream = new StreamReader(response.GetResponseStream(), encode);
                var doc = new XDocument();
                doc = XDocument.Load(response.GetResponseStream());

                var nodes = doc.DescendantNodes().Where(x => x.NodeType == XmlNodeType.Text).ToList();

                var node_str = string.Join(",", nodes);

                doc.Save(@"C:\Office365\Reports\ReportList.xml");

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
コード例 #23
0
        /// <summary>
        /// Đăng nhập vào hệ thống
        /// </summary>
        /// <param name="tenDangNhap"></param>
        /// <param name="matKhau"></param>
        /// <returns></returns>
        public static async Task<bool> login(string tenDangNhap, string matKhau, bool isRemember)
        {
            try
            {
                matKhau = Utilities.EncryptMD5(matKhau);
                var result = await SystemInfo.DatabaseModel.login(tenDangNhap, matKhau);
                if (!result)
                {
                    SystemInfo.IsDangNhap = false;
                    SystemInfo.MaNguoiDung = -1;
                    SystemInfo.TenDangNhap = null;
                    SystemInfo.MatKhauDangNhap = null;
                }
                else
                {
                    SystemInfo.IsDangNhap = true;
                    NguoiDung nguoiDung = await SystemInfo.DatabaseModel.getNguoiDungTenDangNhap(tenDangNhap);
                    SystemInfo.MaNguoiDung = nguoiDung.MaNguoiDung;
                    SystemInfo.TenDangNhap = tenDangNhap;
                    SystemInfo.MatKhauDangNhap = matKhau;

                    if (!(await SystemInfo.DatabaseModel.insertNguoiDungLocal(nguoiDung.MaNguoiDung, nguoiDung.HoTen, nguoiDung.NgaySinh,
                        nguoiDung.Email, nguoiDung.SoDienThoai)))
                    {
                        await SystemInfo.DatabaseModel.updateNguoiDung(nguoiDung.MaNguoiDung, nguoiDung.HoTen, nguoiDung.NgaySinh,
                        nguoiDung.SoDienThoai);
                    }
                    if (isRemember)
                    {


                        StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("AppConfig.qltcconfig");
                        using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                        {

                            System.IO.Stream s = writeStream.AsStreamForWrite();
                            System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
                            settings.Async = true;
                            settings.Indent = true;
                            settings.CheckCharacters = false;
                            using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(s, settings))
                            {
                                XDocument xdoc = new XDocument();
                                XElement element = new XElement("ThongTinDangNhap");
                                element.Add(new XElement("MaNguoiDung", nguoiDung.MaNguoiDung + ""));
                                element.Add(new XElement("TenDangNhap", tenDangNhap));
                                xdoc.Add(element);
                                writer.Flush();
                                xdoc.Save(writer);
                            }
                        }
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #24
0
        /// <summary>
        /// Creates the XML data.
        /// </summary>
        /// <param name="dtRow">The dt row.</param>
        /// <returns></returns>
        public int CreateXMLData(DataRow dtRow)
        {
            try
            {
                if (File.Exists(Datacontext.GetInstance().CorporateFavoriteFile))
                {
                    System.Xml.Linq.XDocument resultsDoc = System.Xml.Linq.XDocument.Parse((System.Xml.Linq.XDocument.Load(Datacontext.GetInstance().CorporateFavoriteFile)).ToString());
                    var query = resultsDoc.Root;
                    query.Add(new System.Xml.Linq.XElement("Favorites", (new System.Xml.Linq.XElement("Category", dtRow["Category"].ToString())),
                                                           (new System.Xml.Linq.XElement("DisplayName", dtRow["DisplayName"])),
                                                           (new System.Xml.Linq.XElement("UniqueIdentity", dtRow["UniqueIdentity"])),
                                                           (new System.Xml.Linq.XElement("FirstName", dtRow["FirstName"])),
                                                           (new System.Xml.Linq.XElement("LastName", dtRow["LastName"])),
                                                           (new System.Xml.Linq.XElement("PhoneNumber", dtRow["PhoneNumber"])),
                                                           (new System.Xml.Linq.XElement("EmailAddress", dtRow["EmailAddress"])),
                                                           (new System.Xml.Linq.XElement("Type", dtRow["Type"]))));

                    resultsDoc.Save(Datacontext.GetInstance().CorporateFavoriteFile);
                    return(1);
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error in creating favorite XML Data : " + ex.Message.ToString());
            }
            return(0);
        }
コード例 #25
0
        public static void GenerateXmlReport(string filePath, StoreContext db)
        {
            var manufacturers = db.Manufacturers.
                                Join(db.Laptops,
                                m => m.Id, l => l.ManufacturerId,
                                (m, l) => new
                                {
                                    Manufacturer = m.Name,
                                    Model = l.Model,
                                    Class = l.Class.Name
                                }).ToList();

            var doc = new XDocument(new XElement(
                "manufacturers",
                from manufacturer in manufacturers
                select new XElement(
                    "manufacturer",
                new XElement("manufacturer", manufacturer.Manufacturer),
                new XElement("model", manufacturer.Model),
                new XElement("class", manufacturer.Class))));

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            string fileName = AddUniqueFilenameSuffix(@"\Manufacturers");
            var fullPath = filePath + fileName;
            doc.Save(fullPath);
        }
コード例 #26
0
        protected override void OnMouseUnclick(int button)
        {
            if (button == 0) // Only handle left clicks, ignore others.
            {
                TileMap orig = world.Map;

                // Save TileMap here.
                TileMap copy = new TileMap(orig.Width, orig.Height,
                                           orig.TileWidth, orig.TileHeight,
                                           orig.LayerCount, orig.SubLayerCount);

                Tile tile;
                for (int i = 0; i < orig.Width; ++i)
                {
                    for (int j = 0; j < orig.Height; ++j)
                    {
                        tile = orig[i,j];
                        if (tile != null)
                            copy[i, j] = tile;
                    }
                }
                copy.Minimize();
                world.ShiftWorldObjects(-EditorScreen.Offset);

                XDocument tileDoc = new XDocument(copy.ToXElement());
                tileDoc.Save("..\\..\\..\\Content\\"+orig.FileName+".xml");
                XDocument worldDoc = new XDocument(world.ToXElement());
                worldDoc.Save("..\\..\\..\\Content\\WorldXML\\TestWorld.xml");
                world.ShiftWorldObjects(EditorScreen.Offset);
            }
            base.OnMouseUnclick(button);
        }
コード例 #27
0
        public ActionResult Index()
        {
            var doc = new XDocument(new XDeclaration("1.0", "utf-8", null));

            var indexElement = new XElement(SitemapXmlNamespace + "sitemapindex");

            foreach (var sitemapData in _sitemapRepository.GetAllSitemapData())
            {
                var sitemapElement = new XElement(
                    SitemapXmlNamespace + "sitemap",
                    new XElement(SitemapXmlNamespace + "loc", _sitemapRepository.GetSitemapUrl(sitemapData))
                );

                indexElement.Add(sitemapElement);
            }

            doc.Add(indexElement);

            Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress);
            Response.AppendHeader("Content-Encoding", "gzip");

            byte[] sitemapIndexData;

            using (var ms = new MemoryStream())
            {
                var xtw = new XmlTextWriter(ms, Encoding.UTF8);
                doc.Save(xtw);
                xtw.Flush();
                sitemapIndexData = ms.ToArray();
            }

            return new FileContentResult(sitemapIndexData, "text/xml");
        }
コード例 #28
0
ファイル: XmlBlogRepository.cs プロジェクト: cnurse/Naif.Blog
        protected override void SavePost(Post post, string file)
        {
            XDocument doc = new XDocument(
                            new XElement("post",
                                new XElement("title", post.Title),
                                new XElement("slug", post.Slug),
                                new XElement("author", post.Author),
                                new XElement("pubDate", post.PubDate.ToString("yyyy-MM-dd HH:mm:ss")),
                                new XElement("lastModified", post.LastModified.ToString("yyyy-MM-dd HH:mm:ss")),
                                new XElement("excerpt", post.Excerpt),
                                new XElement("content", post.Content),
                                new XElement("categories", string.Empty),
                                new XElement("tags", post.Keywords),
                                new XElement("ispublished", post.IsPublished)
                            ));

            XElement categories = doc.Document.Element("post").Element("categories");
            foreach (string category in post.Categories)
            {
                categories.Add(new XElement("category", category));
            }
            using(var stream = new FileStream(file, FileMode.Create))
            {
                doc.Save(stream);
            }
        }
コード例 #29
0
ファイル: CustomMenuService.cs プロジェクト: Marbulinek/NIS
        public void PersistPages()
        {
            if(_store.FileExists(_fileName))
            {
                _store.DeleteFile(_fileName);
            }
            IsolatedStorageFileStream stream= _store.CreateFile(_fileName);
            XDocument document = new XDocument();
            XElement pages = new XElement("Pages");
            foreach (CustomMenuButton customMenuButton in ButtonsList)
            {
                if(string.IsNullOrEmpty( customMenuButton.PageLocation))
                {
                    continue;
                }
                XElement page=new XElement("Page");
                page.Add(new XAttribute("Label",customMenuButton.Label));
                page.Add(new XAttribute("Tooltyp", customMenuButton.Tooltyp));
                page.Add(new XAttribute("PageLocation", customMenuButton.PageLocation));
                pages.Add(page);
            }
            document.Add(pages);
            document.Save(stream);

        }
コード例 #30
0
        public static void CreateXml(IEnumerable<Pilot> pilots, string path)
        {
            var xmlDoc = new XDocument();
            var xmlRoot = new XElement("pilots");

            xmlDoc.Add(xmlRoot);

            foreach (var pilot in pilots)
            {
                var pilotEntry = new XElement("pilot");
                xmlRoot.Add(pilotEntry);

                var pilotName = new XElement("name", pilot.Name);
                pilotEntry.Add(pilotName);

                var pilotPosition = new XElement("position", pilot.Position);
                pilotEntry.Add(pilotPosition);

                if (pilot.SupervisorId != null)
                {
                    var pilotSupervisorId = new XElement("supervisorId", pilot.SupervisorId);
                    pilotEntry.Add(pilotSupervisorId);
                }
            }

            xmlDoc.Save(path);
        }
コード例 #31
0
ファイル: Exporter.cs プロジェクト: alexmcbride/insimsniffer
        public static void ExportXml(string path, IEnumerable<SniffedPacket> packets) {
            if (packets == null) {
                throw new ArgumentNullException("packets");
            }

            XDocument xDoc = new XDocument(
                new XDeclaration("1.0", Encoding.UTF8.HeaderName, String.Empty));
            XElement xPackets = new XElement(
                "Packets",
                new XAttribute("Version", XmlVersion));

            foreach (SniffedPacket packet in packets) {
                XElement xPacket = new XElement("Packet");
                xPacket.Add(new XAttribute("Elapsed", packet.ElapsedTime.TotalMilliseconds));

                foreach (SniffedValue value in packet.Values) {
                    xPacket.Add(new XElement(value.Name, value.Value));
                }

                xPackets.Add(xPacket);
            }

            xDoc.Add(xPackets);
            xDoc.Save(path);
        }
コード例 #32
0
ファイル: LibraryWriter.cs プロジェクト: nemoload/Espera
        public static void Write(IEnumerable<LocalSong> songs, IEnumerable<PlaylistInfo> playlists, Stream targetStream)
        {
            var document = new XDocument(
                new XElement("Root",
                    new XElement("Version", "1.0.0"),
                    new XElement("Songs", songs.Select(song =>
                        new XElement("Song",
                            new XAttribute("Album", song.Album),
                            new XAttribute("Artist", song.Artist),
                            new XAttribute("AudioType", song.AudioType),
                            new XAttribute("Duration", song.Duration.Ticks),
                            new XAttribute("Genre", song.Genre),
                            new XAttribute("Path", song.OriginalPath),
                            new XAttribute("Title", song.Title),
                            new XAttribute("TrackNumber", song.TrackNumber)))),
                    new XElement("Playlists", playlists.Select(playlist =>
                        new XElement("Playlist",
                            new XAttribute("Name", playlist.Name),
                            new XElement("Entries", playlist.Songs.Select(song =>
                                new XElement("Entry",
                                    new XAttribute("Path", song.OriginalPath),
                                    song is YoutubeSong ? new XAttribute("Title", song.Title) : null,
                                    new XAttribute("Type", (song is LocalSong) ? "Local" : "YouTube"),
                                    song is YoutubeSong ? new XAttribute("Duration", song.Duration.Ticks) : null))))))));

            document.Save(targetStream);
        }
コード例 #33
0
ファイル: Program.cs プロジェクト: jerrylee1999/GacUI
        static void Main(string[] args)
        {
            var tokens = File.ReadAllLines(args[0]);
            var global = new GlobalDecl();
            {
                int index = 0;
                CppDeclParser.ParseSymbols(tokens, ref index, global);
                if (index != tokens.Length)
                {
                    throw new ArgumentException("Failed to parse.");
                }
            }

            var xml = new XDocument(global.Serialize());
            xml.Save(args[1]);

            global.BuildSymbolTree(null, null);
            var grouping = ExpandChildren(global)
                .Where(decl => decl.OverloadKey != null)
                .GroupBy(decl => decl.OverloadKey)
                .ToDictionary(g => g.Key, g => g.ToArray())
                ;
            foreach (var pair in grouping)
            {
                if (pair.Value.Length > 1 && pair.Value.Any(decl => !(decl is NamespaceDecl)))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Duplicate key founds: " + pair.Key);
                    Console.ResetColor();
                }
            }
        }
コード例 #34
0
ファイル: WpExporter.cs プロジェクト: enyim/Fb2Wp
        public void Write(string target)
        {
            var authors = GetAuthors();
            var channel = new XElement("channel",
                            new XElement("title", "export"),
                            new XElement("language", "hu-hu"),
                            new XElement(Xmlns.Wp + "wxr_version", "1.2"),
                            new XElement(Xmlns.Wp + "base_site_url", "http://lofasz.com"),
                            new XElement(Xmlns.Wp + "base_blog_url", "http://lofasz.com"),
                            new XElement("pubDate", DateTimeOffset.Now.ToString("r", CultureInfo.InvariantCulture))
                        );

            channel.AddSection("AUTHOR LIST", GetAuthors());
            channel.AddSection("CATEGORY LIST", GetCategories());
            channel.AddSection("TAG LIST", GetTags());

            channel.Add(GetEntries());

            var doc = new XDocument(
                new XElement("rss",
                    new XAttribute(XNamespace.Xmlns + "excerpt", Xmlns.Excerpt),
                    new XAttribute(XNamespace.Xmlns + "content", Xmlns.Content),
                    new XAttribute(XNamespace.Xmlns + "wfw", Xmlns.Wfw),
                    new XAttribute(XNamespace.Xmlns + "dc", Xmlns.Dc),
                    new XAttribute(XNamespace.Xmlns + "wp", Xmlns.Wp),

                    channel
                    ));

            //Console.WriteLine(doc);

            doc.Save(target, SaveOptions.DisableFormatting);
        }
コード例 #35
0
ファイル: LINQHTML.cs プロジェクト: alexssource/Labs
        /// <summary>
        /// Create html file with information about timetable and save it
        /// </summary>
        /// <param name="Path">Where html file should be saved</param>
        /// <param name="station">Station</param>
        public void SaveTimetables(string Path, Station station)
        {
            FileStream fs = new FileStream(Path, FileMode.Create);

            XDocument document = new XDocument();
            document.AddFirst(new XElement("html"));

            document.Root.Add(new XElement("head",
                new XElement("title", station.Name)));

            XElement body = new XElement("body");
            XElement div = new XElement("div");
            foreach (Timetable tt in station)
            {
                XElement inner = new XElement("div", new XAttribute("style", "width:800px;"));
                inner.Add(new XElement("div", tt.FirstStation + " - " + tt.LastStation, new XAttribute("style", "border:solid; float:left; width:400px; heigth:20px;"), new XAttribute("align", "center")),
                    new XElement("div", tt.TimeOfArrival.ToString() + " - " + tt.TimeOfDeparture.ToString(), new XAttribute("style", "border:solid; float:left; width:150px; heigth:20px;"), new XAttribute("align", "center")),
                    new XElement("div", tt.FreqType, new XAttribute("style", "border:solid; float:left; width:150px; heigth:20px;"), new XAttribute("align", "center")),
                    new XElement("br"));
                div.Add(inner);
            }
            body.Add(div);
            document.Root.Add(body);

            document.Save(fs);
            fs.Close();
        }
コード例 #36
0
        //------------------------------------------------------------------------------------------------
        //Xml内のデータを整理する(すっからかんのデータを消す)
        //------------------------------------------------------------------------------------------------
        public void SortXml()
        {
            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database(), LoadOptions.PreserveWhitespace);

            var query = from y in XmlDoc.Descendants("Chord")
                        select y;
            int itemCount = 1;

            foreach (XElement item in query.ToList())
            {
                //すっからかんのデータは消す
                try
                {
                    if (item.Element("Root").Value == "" &&
                        item.Element("Degree").Value == "" &&
                        item.Element("Position1").Value == "" &&
                        item.Element("Position2").Value == "" &&
                        item.Element("Position3").Value == "" &&
                        item.Element("Position4").Value == "" &&
                        item.Element("BarreFlg").Value == "" &&
                        item.Element("Barre").Value == "" &&
                        item.Element("High").Value == "")
                    {
                        item.Remove();
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                    }
                }
                catch (Exception ex)
                {
                }
            }

            //IDの値を並べなおし
            try
            {
                foreach (XElement item in query.ToList())
                {
                    item.Attribute("ID").Value = Convert.ToString(itemCount);
                    XmlDoc.Save(createConfigXML.CurrentPath_database());
                    itemCount++;
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #37
0
ファイル: RDLGenerator.cs プロジェクト: Avinash-acid/saveenr
        private static MemoryStream SaveXMLToMemoryStream(SXL.XDocument new_dom)
        {
            var mem_stream = new System.IO.MemoryStream();
            var ts         = new System.IO.StreamWriter(mem_stream);

            new_dom.Save(ts);
            mem_stream.Seek(0, System.IO.SeekOrigin.Begin);
            return(mem_stream);
        }
コード例 #38
0
        public void UpdateTuDien(string fileName, MathRule mathRule)
        {
            System.Xml.Linq.XDocument document = System.Xml.Linq.XDocument.Load(fileName);
            var node = (from t in document.Descendants("Column")
                        where t.Element("DataBase").Value == mathRule.ColumnInDB
                        select t).FirstOrDefault();

            node.Element("Excel").Value = mathRule.ColumnInExcel;
            document.Save(fileName);
        }
コード例 #39
0
ファイル: Config.cs プロジェクト: thistuna/schLauncher
 private void buttonOK_Click(object sender, EventArgs e)
 {
     Xml.XDocument xDocument = new Xml.XDocument(new Xml.XDeclaration("1.0", "utf-8", "Yes"));
     Xml.XElement  xSettings = new Xml.XElement("schLauncherSettings");
     xSettings.Add(new Xml.XElement("KiCadPath", textBoxKiCad.Text));
     xSettings.Add(new Xml.XElement("EaglePath", textBoxEagle.Text));
     xDocument.Add(xSettings);
     xDocument.Save("settings.xml");
     this.Close();
 }
コード例 #40
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (!System.IO.Directory.Exists(@"D:\"))
                {
                    Program.MessageError("Sticker", "Drive D:", "Not found.", false);
                }
                else
                {
                    if (!System.IO.Directory.Exists(@"D:\EmrCheckup"))
                    {
                        System.IO.DirectoryInfo di = System.IO.Directory.CreateDirectory(@"D:\EmrCheckup");
                        di.Attributes = System.IO.FileAttributes.Directory | System.IO.FileAttributes.Hidden;
                    }
                    if (!System.IO.File.Exists(@"D:\EmrCheckup\PrinterSticker.xml"))
                    {
                        new XDocument(
                            new XElement("PrinterCls",
                                         new XElement("Report",
                                                      new XAttribute("id", "Wristband"),
                                                      new XElement("Printer", comboAutoDropDownWidth1.Text),
                                                      new XElement("Paper", ((PrinterPaperSize)comboAutoDropDownWidth2.SelectedItem).Name)
                                                      )
                                         )
                            ).Save(@"D:\EmrCheckup\PrinterSticker.xml");
                    }
                    else
                    {
                        System.Xml.Linq.XDocument xml = System.Xml.Linq.XDocument.Load(@"D:\EmrCheckup\PrinterSticker.xml");
                        var wb = xml.Element("PrinterCls").Elements("Report").Where(x => x.Attribute("id").Value == "Wristband").FirstOrDefault();

                        if (wb == null)
                        {
                            xml.Element("PrinterCls").Add(
                                new XElement("Report",
                                             new XAttribute("id", "Wristband"),
                                             new XElement("Printer", comboAutoDropDownWidth1.Text),
                                             new XElement("Paper", ((PrinterPaperSize)comboAutoDropDownWidth2.SelectedItem).Name)
                                             )
                                );
                        }
                        else
                        {
                            wb.Element("Printer").Value = comboAutoDropDownWidth1.Text;
                            wb.Element("Paper").Value   = ((PrinterPaperSize)comboAutoDropDownWidth2.SelectedItem).Name;
                        }
                        xml.Save(@"D:\EmrCheckup\PrinterSticker.xml");
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #41
0
        public void SaveSettings(string fileName, XElement extras = null)
        {
            System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument(GetSettings());

            if (extras != null)
            {
                doc.Elements("settings").ElementAtOrDefault(0).Add(extras);
            }

            doc.Save(fileName);
        }
コード例 #42
0
        private void SelectionToSVGXHTML(IVisio.Selection selection, string filename, System.Action <string> verboselog)
        {
            this.AssertApplicationAvailable();
            this.AssertDocumentAvailable();

            // Save temp SVG
            string svg_filename = System.IO.Path.GetTempFileName() + "_temp.svg";

            selection.Export(svg_filename);

            // Load temp SVG
            var load_svg_timer = new System.Diagnostics.Stopwatch();
            var svg_doc        = SXL.XDocument.Load(svg_filename);

            load_svg_timer.Stop();
            verboselog(string.Format("Finished SVG Loading ({0} seconds)", load_svg_timer.Elapsed.TotalSeconds));

            // Delete temp SVG
            if (System.IO.File.Exists(svg_filename))
            {
                System.IO.File.Delete(svg_filename);
            }
            else
            {
                // TODO: throw an exception
            }

            verboselog(string.Format("Creating XHTML with embedded SVG"));
            var s = svg_filename;

            if (System.IO.File.Exists(filename))
            {
                verboselog(string.Format("Deleting \"{0}\"", filename));
                System.IO.File.Delete(filename);
            }

            var xhtml_doc  = new SXL.XDocument();
            var xhtml_root = new SXL.XElement("{http://www.w3.org/1999/xhtml}html");

            xhtml_doc.Add(xhtml_root);
            var svg_node = svg_doc.Root;

            svg_node.Remove();

            var body = new SXL.XElement("{http://www.w3.org/1999/xhtml}body");

            xhtml_root.Add(body);
            body.Add(svg_node);

            xhtml_doc.Save(filename);
            verboselog(string.Format("Done writing XHTML file \"{0}\"", filename));
        }
コード例 #43
0
        //------------------------------------------------------------------------------------------------
        //新規登録フォームのデータをXmlに書き込む
        //------------------------------------------------------------------------------------------------
        public void NewDataAdd()
        {
            var Root      = "";
            var Degree    = "";
            var Position1 = "";
            var Position2 = "";
            var Position3 = "";
            var Position4 = "";
            var BarreFlg  = "";
            var Barre     = "";
            var High      = "";

            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database());

            //Xmlファイルに書き込み
            Root      = textBox1_Root.Text;
            Degree    = textBox1_degree.Text;;
            Position1 = textBox_position1.Text;
            Position2 = textBox3_position2.Text;
            Position3 = textBox2_position3.Text;
            Position4 = textBox5_position4.Text;
            BarreFlg  = textBox6_barreflg.Text;
            Barre     = textBox7_barre.Text;
            High      = textBox8_high.Text;

            try
            {
                var query = (from y in XmlDoc.Descendants("Chord")
                             select y);

                int Count = query.Elements("Chord").Count();

                var writeXml = new XElement("Chord",
                                            new XAttribute("ID", Count + 1),
                                            new XElement("Root", Root),
                                            new XElement("Degree", Degree),
                                            new XElement("Position1", Position1),
                                            new XElement("Position2", Position2),
                                            new XElement("Position3", Position3),
                                            new XElement("Position4", Position4),
                                            new XElement("BarreFlg", BarreFlg),
                                            new XElement("Barre", Barre),
                                            new XElement("High", High));

                XmlDoc.Elements().First().Add(writeXml);
                XmlDoc.Save(createConfigXML.CurrentPath_database());
            }
            catch (Exception ex)
            {
            }
        }
コード例 #44
0
        private void _export_selection_to_html(IVisio.Selection selection, string filename, System.Action <string> export_log)
        {
            var cmdtarget = this._client.GetCommandTargetPage();

            // Save temp SVG
            string svg_filename = System.IO.Path.GetTempFileName() + "_temp.svg";

            selection.Export(svg_filename);

            // Load temp SVG
            var load_svg_timer = new System.Diagnostics.Stopwatch();
            var svg_doc        = SXL.XDocument.Load(svg_filename);

            load_svg_timer.Stop();
            export_log(string.Format("Finished SVG Loading ({0} seconds)", load_svg_timer.Elapsed.TotalSeconds));

            // Delete temp SVG
            if (System.IO.File.Exists(svg_filename))
            {
                System.IO.File.Delete(svg_filename);
            }

            export_log("Creating XHTML with embedded SVG");

            if (System.IO.File.Exists(filename))
            {
                export_log(string.Format("Deleting \"{0}\"", filename));
                System.IO.File.Delete(filename);
            }

            var xhtml_doc  = new SXL.XDocument();
            var xhtml_root = new SXL.XElement("{http://www.w3.org/1999/xhtml}html");

            xhtml_doc.Add(xhtml_root);
            var svg_node = svg_doc.Root;

            svg_node.Remove();

            var body = new SXL.XElement("{http://www.w3.org/1999/xhtml}body");

            xhtml_root.Add(body);
            body.Add(svg_node);

            xhtml_doc.Save(filename);
            export_log(string.Format("Done writing XHTML file \"{0}\"", filename));
        }
コード例 #45
0
 public int CreateXmlData(string XMLFile, string Key, string value)
 {
     try
     {
         if (File.Exists(XMLFile))
         {
             System.Xml.Linq.XDocument resultsDoc = System.Xml.Linq.XDocument.Parse((System.Xml.Linq.XDocument.Load(XMLFile)).ToString());
             var query = resultsDoc.Root;
             query.Add(new System.Xml.Linq.XElement("Item", (new System.Xml.Linq.XElement("Key", Key)), (new System.Xml.Linq.XElement("Value", value))));
             resultsDoc.Save(XMLFile);
             return(1);
         }
     }
     catch (Exception ErrorEventArgs)
     { }
     return(0);
 }
コード例 #46
0
 public int UpdateXmlData(string XMLFile, string Key, string value)
 {
     try
     {
         System.Xml.Linq.XDocument resultsDoc = System.Xml.Linq.XDocument.Parse((System.Xml.Linq.XDocument.Load(XMLFile)).ToString());
         var query = resultsDoc.Root.Descendants("Item");
         foreach (System.Xml.Linq.XElement e in query)
         {
             if (e.Element("Key").Value.ToString() == Key)
             {
                 e.Element("Value").Value = value;
             }
         }
         resultsDoc.Save(XMLFile);
         return(1);
     }
     catch (Exception error) {  }
     return(0);
 }
コード例 #47
0
        public void SaveCustomer(Customer _C)
        {
            if (!File.Exists(CustomerStorage))
            {
                XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
                xmlWriterSettings.Indent = true;
                xmlWriterSettings.NewLineOnAttributes = true;
                using (XmlWriter xmlWriter = XmlWriter.Create(CustomerStorage, xmlWriterSettings))
                {
                    xmlWriter.WriteStartDocument();
                    xmlWriter.WriteStartElement("Customers");

                    xmlWriter.WriteStartElement("Customer");
                    xmlWriter.WriteElementString("CID", _C.ID);
                    xmlWriter.WriteElementString("FirstName", _C.FirstName);
                    xmlWriter.WriteElementString("LastName", _C.LastName);
                    xmlWriter.WriteElementString("TimeStamp", DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString());
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteEndElement();
                    xmlWriter.WriteEndDocument();
                    xmlWriter.Flush();
                    xmlWriter.Close();
                }
            }
            else
            {
                System.Xml.Linq.XDocument xDocument = XDocument.Load(CustomerStorage);
                XElement root = xDocument.Element("Customers");
                IEnumerable <XElement> rows = root.Descendants("Customer");
                XElement firstRow           = rows.First();
                firstRow.AddBeforeSelf(
                    new XElement("Customer",
                                 new XElement("CID", _C.ID),
                                 new XElement("FirstName", _C.FirstName),
                                 new XElement("LastName", _C.LastName),
                                 new XElement("TimeStamp", DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString())));
                xDocument.Save(CustomerStorage);
            }
        }
コード例 #48
0
ファイル: MyIO.cs プロジェクト: mikols/WinDirmaker
        } // ReadInitFile

        /// <summary>
        /// Skapa/Ändra inställningar dirmaker.XML
        /// </summary>
        /// <returns></returns>
        public bool WriteInitFile()
        {
            bool retval = true;

            //mFolderSource = sourceFile;
            //mFolderDestination = destFile;
            if (IsSourcePath())
            {
                // Skriv till XML
                System.Xml.Linq.XDocument xdoc    = new System.Xml.Linq.XDocument(new System.Xml.Linq.XComment("Inställningar för Dirmaker"));
                System.Xml.Linq.XElement  xmlroot = new System.Xml.Linq.XElement("Dirmaker");
                xmlroot.Add(
                    new System.Xml.Linq.XElement(MyConstants.cFileTagVersion, MyConstants.FileVersion),
                    new System.Xml.Linq.XElement(MyConstants.cFileTagAssemblyVersion, MyConstants.AssemblyVersion),
                    new System.Xml.Linq.XElement(MyConstants.cFileTagSourceRootFolder, mFolderSource),
                    new System.Xml.Linq.XElement(MyConstants.cFileTagDestinationRootFolder, mFolderDestination),
                    new XElement(MyConstants.cPriorityWork1, Priority1),
                    new XElement(MyConstants.cPriorityWork2, Priority2),
                    new XElement(MyConstants.cPriorityWork3, Priority3),
                    new XElement(MyConstants.cPriorityWork4, Priority4),
                    new XElement(MyConstants.cPriorityWork5, Priority5),
                    new XElement(MyConstants.cPriorityWork6, Priority6),
                    new XElement(MyConstants.cPriorityWork7, Priority7),
                    new XElement(MyConstants.cPriorityWork8, Priority8),
                    new XElement(MyConstants.cSearchDirTag1, SearchDir1),
                    new XElement(MyConstants.cSearchDirTag2, SearchDir2),
                    new XElement(MyConstants.cSearchDirTag3, SearchDir3),
                    new XElement(MyConstants.cSearchDirTag4, SearchDir4),
                    new XElement(MyConstants.cSearchDirTag5, SearchDir5),
                    new XElement(MyConstants.cSearchDirTag6, SearchDir6),
                    new XElement(MyConstants.cSearchDirTag7, SearchDir7),
                    new XElement(MyConstants.cSearchDirTag8, SearchDir8),
                    new XElement(MyConstants.cExcludedFileTypes, ExcludedFileTypes)
                    );
                xdoc.Add(xmlroot);
                xdoc.Save(FilePathDirmakerXML);
            }
            return(retval);
        }
コード例 #49
0
        public void Update(string fileName, MathRule mathRule)
        {
            System.Xml.Linq.XDocument document = System.Xml.Linq.XDocument.Load(fileName);
            var node = (from t in document.Descendants("Column")
                        where t.Element("DataBase").Value == mathRule.ColumnInDB
                        select t).FirstOrDefault();

            // check exist element excel
            string[]      arr  = node.Element("Excel").Value.Split(';');
            List <string> list = new List <string>();

            for (int i = 0; i < arr.Length; i++)
            {
                list.Add(arr[i].Trim());
            }

            if (!list.Contains(mathRule.ColumnInExcel.Trim()))
            {
                node.Element("Excel").Value += ";" + mathRule.ColumnInExcel;
            }

            document.Save(fileName);
        }
コード例 #50
0
 public int RemoveFavorite(string uniqueIdentity, string type)
 {
     try
     {
         System.Xml.Linq.XDocument resultsDoc = System.Xml.Linq.XDocument.Parse((System.Xml.Linq.XDocument.Load(Datacontext.GetInstance().CorporateFavoriteFile)).ToString());
         var query = resultsDoc.Root.Descendants("Favorites");
         foreach (System.Xml.Linq.XElement e in query)
         {
             if (e.Element("UniqueIdentity").Value.ToString() == uniqueIdentity && e.Element("Type").Value.ToString() == type)
             {
                 var collection = resultsDoc.DescendantNodes();
                 e.Remove();
                 resultsDoc.Save(Datacontext.GetInstance().CorporateFavoriteFile);
                 return(1);
             }
         }
     }
     catch (Exception ex)
     {
         _logger.Error("Error in creating removing XMLFile : " + ex.Message.ToString());
     }
     return(0);
 }
コード例 #51
0
        public void CreateVDX(Elements.Drawing vdoc, SXL.XDocument dom, string output_filename)
        {
            if (output_filename == null)
            {
                throw new System.ArgumentNullException(nameof(output_filename));
            }

            // Validate that all Document windows refer to an existing page
            foreach (var window in vdoc.Windows)
            {
                if (window is Elements.DocumentWindow)
                {
                    var docwind = (Elements.DocumentWindow)window;
                    docwind.ValidatePage(vdoc);
                }
            }
            this.CreateVDX(vdoc, dom);

            // important to use DisableFormatting - Visio is very sensitive to whitespace in the <Text> element when there is complex formatting
            var saveoptions = SXL.SaveOptions.DisableFormatting;

            dom.Save(output_filename, saveoptions);
        }
コード例 #52
0
        //------------------------------------------------------------------------------------------------
        //DataGridviewのデータをXmlに書き込む
        //------------------------------------------------------------------------------------------------
        public void WriteXml()
        {
            int RowCount  = dataGridView1.RowCount;
            var Root      = "";
            var Degree    = "";
            var Position1 = "";
            var Position2 = "";
            var Position3 = "";
            var Position4 = "";
            var BarreFlg  = "";
            var Barre     = "";
            var High      = "";

            XElement query;

            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database(), LoadOptions.PreserveWhitespace);

            //Xmlファイルに書き込み
            for (int i = 0; i < RowCount; i++)
            {
                Root      = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
                Degree    = Convert.ToString(dataGridView1.Rows[i].Cells[2].Value);
                Position1 = Convert.ToString(dataGridView1.Rows[i].Cells[3].Value);
                Position2 = Convert.ToString(dataGridView1.Rows[i].Cells[4].Value);
                Position3 = Convert.ToString(dataGridView1.Rows[i].Cells[5].Value);
                Position4 = Convert.ToString(dataGridView1.Rows[i].Cells[6].Value);
                BarreFlg  = Convert.ToString(dataGridView1.Rows[i].Cells[7].Value);
                Barre     = Convert.ToString(dataGridView1.Rows[i].Cells[8].Value);
                High      = Convert.ToString(dataGridView1.Rows[i].Cells[9].Value);

                try
                {
                    var writeXml = new XElement("Data",
                                                new XAttribute("ID", i + 1),
                                                new XElement("Root", ""),
                                                new XElement("Degree", ""),
                                                new XElement("Position1", ""),
                                                new XElement("Position2", ""),
                                                new XElement("Position3", ""),
                                                new XElement("Position4", ""),
                                                new XElement("BarreFlg", ""),
                                                new XElement("Barre", ""),
                                                new XElement("High", ""));

                    XmlDoc.Elements().First().Add(writeXml);
                    XmlDoc.Save(createConfigXML.CurrentPath_database());

                    //データグリッドビューの値をXmlに書き込み
                    query = (from y in XmlDoc.Descendants("Chord")
                             where y.Attribute("ID").Value == Convert.ToString(i + 1)
                             select y).Single();

                    query.Element("Root").Value      = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
                    query.Element("Degree").Value    = Convert.ToString(dataGridView1.Rows[i].Cells[2].Value);
                    query.Element("Position1").Value = Convert.ToString(dataGridView1.Rows[i].Cells[3].Value);
                    query.Element("Position2").Value = Convert.ToString(dataGridView1.Rows[i].Cells[4].Value);
                    query.Element("Position3").Value = Convert.ToString(dataGridView1.Rows[i].Cells[5].Value);
                    query.Element("Position4").Value = Convert.ToString(dataGridView1.Rows[i].Cells[6].Value);
                    query.Element("BarreFlg").Value  = Convert.ToString(dataGridView1.Rows[i].Cells[7].Value);
                    query.Element("Barre").Value     = Convert.ToString(dataGridView1.Rows[i].Cells[8].Value);
                    query.Element("High").Value      = Convert.ToString(dataGridView1.Rows[i].Cells[9].Value);



                    XmlDoc.Save(createConfigXML.CurrentPath_database());
                }
                catch (Exception ex)
                {
                }
            }
        }
コード例 #53
0
        //------------------------------------------------------------------------------------------------
        //選択されているデータをXmlから消去する。
        //------------------------------------------------------------------------------------------------
        public void ChoiceDelete()
        {
            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database(), LoadOptions.PreserveWhitespace);

            int idxRows;

            foreach (DataGridViewCell c in dataGridView1.SelectedCells)
            {
                try
                {
                    idxRows = c.RowIndex;

                    var query = (from y in XmlDoc.Descendants("Chord")
                                 where y.Attribute("ID").Value == Convert.ToString(idxRows + 1)
                                 select y).Single();

                    switch (c.ColumnIndex)
                    {
                    case 1:
                        query.Element("Root").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;

                    case 2:
                        query.Element("Degree").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;

                    case 3:
                        query.Element("Position1").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;

                    case 4:
                        query.Element("Position2").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;


                    case 5:
                        query.Element("Position3").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;

                    case 6:
                        query.Element("Position4").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;


                    case 7:
                        query.Element("BarreFlg").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;

                    case 8:
                        query.Element("Barre").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;

                    case 9:
                        query.Element("High").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
コード例 #54
0
        private List <string> UpdateShortCutXML(string sysConfigText)
        {
            List <string> returnAttachments = new List <string>();

            if (string.IsNullOrWhiteSpace(sysConfigText))
            {
                return(returnAttachments);
            }

            System.Xml.Linq.XDocument sysConfigDoc = System.Xml.Linq.XDocument.Parse(sysConfigText, LoadOptions.PreserveWhitespace);
            sysConfigDoc.Declaration = new XDeclaration("1.0", "utf-8", null);

            // Find the <Shortcut> Node so we can update its values
            XElement shortcutNode = sysConfigDoc.Descendants("Shortcut").FirstOrDefault();

            if (shortcutNode == null) // Create the node if missing
            {
                if (sysConfigDoc.Element("configuration") == null)
                {
                    sysConfigDoc.Add(new XElement("configuration"));
                }

                sysConfigDoc.Element("configuration").Add(new XElement("Shortcut"));
                shortcutNode = sysConfigDoc.Element("configuration").Element("Shortcut");
            }

            shortcutNode.SetElementValue("Company", ((Session)oTrans.Session).CompanyID);
            shortcutNode.SetElementValue("Plant", ((Session)oTrans.Session).PlantID);
            shortcutNode.SetElementValue("AppServerURL", ((Session)oTrans.Session).AppServer);

            shortcutNode.SetElementValue("DateTime", DateTime.Now.ToString());
            shortcutNode.SetElementValue("Originator", ((Session)oTrans.Session).UserID);

            // Set the <Process> child nodes
            XElement processNode = shortcutNode.Element("Process");

            if (processNode == null)
            {
                shortcutNode.Add(new XElement("Process"));
                processNode = shortcutNode.Element("Process");
            }

            processNode.SetElementValue("ProcessID", "ITAR001"); // MenuID is normally stored in XXXDef.SysCharacter01
            processNode.SetElementValue("Description", "UD01 Notify");

            // Set the RecordIDS node and its child elements
            XElement recordIDsElement = shortcutNode.Element("RecordIDS");

            if (recordIDsElement == null)
            {
                shortcutNode.Add(new XElement("RecordIDS"));
                recordIDsElement = shortcutNode.Element("RecordIDS");
            }

            var keyFieldsValues = GetKeyValues();
            var keyFieldTypes   = GetKeyTpes();
            var keyFields       = GetKeyFields();

            recordIDsElement.SetAttributeValue("KeyFields", keyFields);
            recordIDsElement.SetAttributeValue("KeyFieldsType", "System.String");
            recordIDsElement.SetAttributeValue("TableName", "UD001List");
            recordIDsElement.SetAttributeValue("DataSourceType", "UD01ListDataSet");
            recordIDsElement.SetElementValue("RecordID", keyFieldsValues);
            StringBuilder sb = new StringBuilder();

            //StringWriter swriter = new StringWriter(sb);
            using (StringWriter writer = new Utf8StringWriter(sb))
            {
                sysConfigDoc.Save(writer);
            }
            returnAttachments.Add(sb.ToString());
            return(returnAttachments);
        }
コード例 #55
0
ファイル: FH.cs プロジェクト: kguo0427/TLink
        public void exportXML()
        {
            //output to the xml file
            string path = this.xmlPath;

            linq.XNamespace ns = "http://www.edi.com.au/EnterpriseService/";

            linq.XDocument doc = linq.XDocument.Load(path);

            linq.XElement rateEntries = new linq.XElement(ns + "RateEntries");
            foreach (RateEntry r in reList)
            {
                linq.XElement entry = new linq.XElement(ns + "RateEntry");
                if (r.category != "")
                {
                    entry.Add(new linq.XElement(ns + "Category", r.category));
                }
                entry.Add(new linq.XElement(ns + "Mode", "SEA"));
                if (r.startDate != "")
                {
                    entry.Add(new linq.XElement(ns + "StartDate", r.startDate));
                }
                if (r.endDate != "")
                {
                    entry.Add(new linq.XElement(ns + "EndDate", r.endDate));
                }
                if (r.ContainerCode != "")
                {
                    linq.XElement ct = new linq.XElement(ns + "ContainerType");
                    ct.Add(new linq.XElement(ns + "ContainerCode", r.ContainerCode));
                    entry.Add(ct);
                }
                if (r.contractNum != "")
                {
                    entry.Add(new linq.XElement(ns + "ContractNumber", r.contractNum));
                }
                if (r.origin != "")
                {
                    entry.Add(new linq.XElement(ns + "Origin", r.origin));
                }
                if (r.destination != "")
                {
                    entry.Add(new linq.XElement(ns + "Destination", r.destination));
                }
                if (r.commodityCode != "")
                {
                    entry.Add(new linq.XElement(ns + "CommodityCode", r.commodityCode));
                }
                linq.XElement rls = new linq.XElement(ns + "RateLines");
                foreach (RateLine rl in r.rl)
                {
                    linq.XElement rateline = new linq.XElement(ns + "RateLine");
                    rateline.Add(new linq.XElement(ns + "Description", "Ocean Freight"));
                    rateline.Add(new linq.XElement(ns + "Currency", "USD"));
                    rateline.Add(new linq.XElement(ns + "ChargeCode", "FRT"));
                    linq.XElement rc  = new linq.XElement(ns + "RateCalculator");
                    linq.XElement unt = new linq.XElement(ns + "UNTCalculator");
                    unt.Add(new linq.XElement(ns + "PerUnitPrice", rl.price));
                    linq.XElement notes = new linq.XElement(ns + "Notes");
                    linq.XElement note  = new linq.XElement(ns + "Note");
                    note.Add(new linq.XElement(ns + "NoteType", "TradeLaneChargeInformation"));
                    note.Add(new linq.XElement(ns + "NoteData", rl.note));
                    rc.Add(unt);
                    notes.Add(note);
                    rateline.Add(rc);
                    rateline.Add(notes);
                    rls.Add(rateline);
                }
                entry.Add(rls);
                rateEntries.Add(entry);
            }
            var ele = doc.Descendants(ns + "Rate").FirstOrDefault();

            if (doc.Descendants(ns + "RateEntries").Any())
            {
                doc.Descendants(ns + "RateEntries").FirstOrDefault().Remove();
            }
            ele.Add(rateEntries);
            doc.Save(path);
        }
コード例 #56
0
        public void SaveDepot(Depot _D)
        {
            if (!File.Exists(DepotStorage))
            {
                XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
                xmlWriterSettings.Indent = true;
                xmlWriterSettings.NewLineOnAttributes = true;
                using (XmlWriter xmlWriter = XmlWriter.Create(DepotStorage, xmlWriterSettings))
                {
                    xmlWriter.WriteStartDocument();
                    xmlWriter.WriteStartElement("Depots");

                    xmlWriter.WriteStartElement("Depot");
                    xmlWriter.WriteElementString("DID", _D.ID);
                    xmlWriter.WriteElementString("Owner", _D.Owner.ID);
                    xmlWriter.WriteStartElement("Stocks");


                    foreach (KeyValuePair <Stock, uint> _s in _D.Stocks)
                    {
                        xmlWriter.WriteStartElement("Stock");
                        xmlWriter.WriteAttributeString("SID", _s.Key.ID);
                        xmlWriter.WriteAttributeString("Amount", _s.Value.ToString());
                        xmlWriter.WriteEndElement();
                    }
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("IssuedOrders");


                    foreach (Order _o in _D.IssuedOrders)
                    {
                        xmlWriter.WriteStartElement("IssuedOrder");
                        xmlWriter.WriteAttributeString("OID", _o.id);
                        xmlWriter.WriteAttributeString("BoerseID", _o.idBoerse);
                        xmlWriter.WriteAttributeString("Type", _o.type);
                        xmlWriter.WriteAttributeString("Amount", _o.amount.ToString());
                        xmlWriter.WriteEndElement();
                    }

                    xmlWriter.WriteEndElement();
                    xmlWriter.WriteElementString("TimeStamp", DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString());
                    xmlWriter.WriteElementString("Worth", _D.Worth.ToString());
                    xmlWriter.WriteEndElement();
                    xmlWriter.WriteEndElement();
                    xmlWriter.WriteEndDocument();
                    xmlWriter.Flush();
                    xmlWriter.Close();
                }
            }
            else
            {
                System.Xml.Linq.XDocument xDocument = XDocument.Load(DepotStorage);
                XElement root = xDocument.Element("Depots");
                IEnumerable <XElement> rows      = root.Descendants("Depot");
                IEnumerable <XElement> stockrows = rows.Descendants("Stocks");
                XElement firstRow = rows.First();
                //firstRow.AddBeforeSelf(
                //   new XElement("Depot",
                //   new XElement("DID", _D.ID),
                //   new XElement("Owner", _D.Owner.ID),
                //   new XElement("Stocks",
                //   _D.Stocks.Select( stock => new XElement("kjasddkljsdafkj", stock.Key.ID) ),
                //   _D.Stocks.Select(stock => new XAttribute("Amount", stock.Value.ToString()))),
                //   new XElement("TimeStamp", DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString())));
                firstRow.AddBeforeSelf(
                    new XElement("Depot",
                                 new XElement("DID", _D.ID),
                                 new XElement("Owner", _D.Owner.ID),
                                 new XElement("Stocks",
                                              _D.Stocks.Select(stock => new XElement("Stock",
                                                                                     new XAttribute("SID", stock.Key.ID),
                                                                                     new XAttribute("Amount", stock.Value.ToString())))),
                                 new XElement("IssuedOrders",
                                              _D.IssuedOrders.Select(order => new XElement("IssuedOrder",
                                                                                           new XAttribute("OID", order.id),
                                                                                           new XAttribute("BoerseID", order.idBoerse),
                                                                                           new XAttribute("Type", order.type),
                                                                                           new XAttribute("Amount", order.amount)))),
                                 new XElement("TimeStamp", DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString()),
                                 new XElement("Worth", _D.Worth.ToString())));


                xDocument.Save(DepotStorage);
            }
        }