public XDocument Serialize(object obj)
        {
            var doc = new XDocument();

            var t = obj.GetType();
            var name = t.Name;

            var options = t.GetAttribute<SerializeAsAttribute>();
            if (options != null) {
                name = options.TransformName(name);
            }

            var root = new XElement(name.AsNamespaced(Namespace));

            Map(root, obj);

            if (RootElement.HasValue()) {
                var wrapper = new XElement(RootElement.AsNamespaced(Namespace), root);
                doc.Add(wrapper);
            }
            else {
                doc.Add(root);
            }

            return doc;
        }
Beispiel #2
0
        public void OnXElement()
        {
            _runWithEvents = (bool)Params[0];
            var numOfNodes = (int)Variation.Params[0];
            var xml = (string)Variation.Params[1];

            XElement e = XElement.Parse(xml);

            if (Variation.Params.Length > 2)
            {
                var doc = new XDocument();
                if ((bool)Variation.Params[2])
                {
                    doc.Add(new XElement("{nsxx}X", e));
                }
                else
                {
                    doc.Add(e);
                }
            }

            // not connected nodes
            TestReplacement(e, Data4XElem, numOfNodes);

            // connected node mix
            object[] copy = Data4XElem;
            var eTemp = new XElement("cc", copy);
            TestReplacement(e, copy, numOfNodes);
        }
        static void Main(string[] args)
        {
            Console.Write("\n  Create XML file using XDocument");
              Console.Write("\n =================================\n");

              XDocument xml = new XDocument();
              xml.Declaration = new XDeclaration("1.0", "utf-8", "yes");
             /*
              *  It is a quirk of the XDocument class that the XML declaration,
              *  a valid processing instruction element, cannot be added to the
              *  XDocument's element collection.  Instead, it must be assigned
              *  to the document's Declaration property.
              */
              XComment comment = new XComment("Demonstration XML");
              xml.Add(comment);

              XElement root = new XElement("root");
              xml.Add(root);
              XElement child1 = new XElement("child1", "child1 content");
              XElement child2 = new XElement("child2");
              XElement grandchild21 = new XElement("grandchild21", "content of grandchild21");
              child2.Add(grandchild21);
              root.Add(child1);
              root.Add(child2);

              Console.Write("\n{0}\n", xml.Declaration);
              Console.Write(xml.ToString());
              Console.Write("\n\n");
        }
Beispiel #4
0
 public XDocument Generate()
 {
     var mainDocument = new XDocument();
     mainDocument.Add(GetDocumentType(_documentStandard));
     mainDocument.Add(_htmlRoot.Generate());
     return mainDocument;
 }
        public bool ExportProjectToCofFile(DTO_Project info, string exportDir)
        {
            // OVERVIEW ======================================
            XElement rootElem = new XElement(BusinessLogic.Config.XML_KEY_COF_HEAD, info.Desc);
            rootElem.Add(new XAttribute(BusinessLogic.Config.XML_KEY_COF_ATTRIBUTE_PROJECT_NAME, info.ProjectName));
            XDocument doc = new XDocument(rootElem);

            // AUTHORS =======================================
            XElement authorElem = new XElement(BusinessLogic.Config.XML_KEY_COF_GROUP);
            authorElem.Add(new XAttribute(BusinessLogic.Config.XML_KEY_COF_GROUP_ATTRIBUTE_NAME, info.GroupName));
            foreach (DTO_Author author in info.Authors)
            {
                XElement authorDetail = new XElement(BusinessLogic.Config.XML_KEY_COF_AUTHOR);
                authorDetail.Add(new XAttribute(BusinessLogic.Config.XML_KEY_COF_AUTHOR_ATTRIBUTE_NAME, author.Name));
                authorDetail.Value = author.AdditionalInfo;
                authorElem.Add(authorDetail);
            }

            // NOTES =========================================
            XElement noteElem = new XElement(BusinessLogic.Config.XML_KEY_COF_NOTES);
            foreach (string noteDetail in info.Notes)
            {
                noteElem.Add(new XElement(BusinessLogic.Config.XML_KEY_COF_NOTE_DETAIL, noteDetail));
            }

            // SOURCE EXPORT =================================
            //TODO: copy project source to dir.

            // EXPORT COF ====================================
            doc.Add(authorElem);
            doc.Add(noteElem);
            return FileBusiness.XmlHandler.writeToFile(exportDir, doc, true);
        }
Beispiel #6
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            NpgsqlConnection conn = new NpgsqlConnection(String.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};",txtServer.Text,txtPort.Text,txtUser.Text,txtPassword.Text,txtDBName.Text));
            conn.Open();

            NpgsqlCommand command = new NpgsqlCommand("select * from report", conn);

            try
            {
                NpgsqlDataReader dr = command.ExecuteReader();

                XDocument xmlTS = new XDocument();

                // Données de base
                xmlTS.Add(new XDocumentType("TS",null,null,null));

                XElement ts = new XElement("TS",new XAttribute("version","2.0"));
                xmlTS.Add(ts);

                while (dr.Read())
                {
                    XDocument xmlReport = XDocument.Parse(dr["report_source"].ToString());

                    XElement context = new XElement("context", new XElement("name",xmlReport.Element("report").Element("name").Value));
                    ts.Add(context);

                    foreach (XElement label in from i in xmlReport.Element("report").Descendants("label") select i)
                    {
                        XElement message = new XElement("message",
                                    new XElement("source", label.Element("string").Value),
                                    new XElement("translation",
                                        new XAttribute("type", "unfinished"), "")
                                );

                      //  if (chkWidth.Checked) message.AddFirst(new XElement("width", label.Element("rect").Element("width").Value));

                        context.Add(message);

                    }

                }

                xmlTS.Save(txtTSFilename.Text);
                MessageBox.Show("Conversion terminée");
            }

            finally
            {
                conn.Close();
            }
        }
Beispiel #7
0
        public void Test()
        {
            //TODO: Make the parser add exception nodes when strings don't fully match

            Decoder decode;

            var masterDoc = new XDocument(new XElement("doc")).Root;
            if (masterDoc == null) throw new Exception(".NET stopped working!");

            decode = Decoder.FromPath("[*]");
            masterDoc.Add(decode.Element);
            Assert.AreEqual("a => a.Nodes()", decode.Local.ToString());
            decode.Local.Compile();

            decode = Decoder.FromPath("[*]{/note}");
            masterDoc.Add(decode.Element);
            Assert.AreEqual("a => a.Nodes()", decode.Local.ToString());
            decode.Local.Compile();
            Assert.AreEqual("a => a.Root.Nodes(\"note\")", decode.Data.ToString());
            decode.Data.Compile();

            decode = Decoder.FromPath("{/note}[entityRow]");
            masterDoc.Add(decode.Element);
            Assert.AreEqual("a => a.Nodes(\"entityRow\")", decode.Local.ToString());
            decode.Local.Compile();
            Assert.AreEqual("a => a.Root.Nodes(\"note\")", decode.Data.ToString());
            decode.Data.Compile();

            decode = Decoder.FromPath("{@descr}");
            masterDoc.Add(decode.Element);
            Assert.AreEqual("a => a.Attribute(\"descr\")", decode.Data.ToString());
            decode.Data.Compile();

            decode = Decoder.FromPath("{/dyn::rowSelector}");
            masterDoc.Add(decode.Element);
            //TODO: This is pretty sketchy.  I should consider a different approach to handling namespaces.
            //And how will I remember to update Decoder when I change the interfaces around?
            //I need to get decode to build itself from hardcoded interface calls, so they'll break when I change the interface
            //  and not jus during testing
            Assert.AreEqual("a => a.Root.Nodes(\"dyn\", \"rowSelector\")", decode.Data.ToString());
            decode.Data.Compile();

            decode = Decoder.FromPath("[:noteList/@rows]");
            masterDoc.Add(decode.Element);
            Assert.AreEqual("a => a.Root.NodeById(\"noteList\").Attribute(\"rows\")", decode.Local.ToString());
            decode.Local.Compile();

            decode = Decoder.FromPath("[@rows][1]");
            masterDoc.Add(decode.Element);
            Assert.AreEqual("a => a.Attribute(\"rows\")", decode.Expressions.First().ToString());
            Assert.AreEqual("a => a.ElementAtOrDefault(0)", decode.Expressions.Skip(1).First().ToString());
            decode.Local.Compile();

            decode = Decoder.FromPath("[../@rowSelector]{@body}");
            masterDoc.Add(decode.Element);
            Assert.AreEqual("a => a.get_Parent().Attribute(\"rowSelector\")", decode.Local.ToString());
            decode.Local.Compile();
            Assert.AreEqual("a => a.Attribute(\"body\")", decode.Data.ToString());
            decode.Data.Compile();
        }
        /// <summary>
        /// Serialize the object as XML
        /// </summary>
        /// <param name="obj">Object to serialize</param>
        /// <returns>XML as string</returns>
        public string PrestaSharpSerialize(object obj)
        {
            var doc = new XDocument();

            var t = obj.GetType();
            var name = t.Name;

            var options = t.GetAttribute<SerializeAsAttribute>();
            if (options != null)
            {
                name = options.TransformName(options.Name ?? name);
            }

            var root = new XElement(name.AsNamespaced(Namespace));

            if (obj is IList)
            {
                var itemTypeName = "";
                foreach (var item in (IList)obj)
                {
                    var type = item.GetType();
                    var opts = type.GetAttribute<SerializeAsAttribute>();
                    if (opts != null)
                    {
                        itemTypeName = opts.TransformName(opts.Name ?? name);
                    }
                    if (itemTypeName == "")
                    {
                        itemTypeName = type.Name;
                    }
                    var instance = new XElement(itemTypeName);
                    Map(instance, item);
                    root.Add(instance);
                }
            }
            else
                Map(root, obj);

            if (RootElement.HasValue())
            {
                var wrapper = new XElement(RootElement.AsNamespaced(Namespace), root);
                doc.Add(wrapper);
            }
            else
            {
                doc.Add(root);
            }

            return doc.ToString();
        }
        private void CreateXMLDocument()
        {
            XDocument document = new XDocument();
             document.Declaration = new XDeclaration( "1.0", Encoding.UTF8.ToString(), "yes" );
             document.Add( new XComment( "Current Inventory of AutoLot" ) );

             XElement inventory = new XElement( "Inventory" );
             inventory.Add( CarElement( "1", "Green", "BMW", "Stan" ) );
             inventory.Add( CarElement( "2", "Pink", "Yugo", "Melvin" ) );

             document.Add( inventory );

             Console.WriteLine( document );
             document.Save( "AutoLotInventory.xml" );
        }
Beispiel #10
0
        public SXL.XDocument CreateDocument()
        {
            var doc  = new SXL.XDocument();
            var root = new SXL.XElement("methodCall");

            doc.Add(root);

            var method = new SXL.XElement("methodName");

            root.Add(method);

            method.Add(this.Name);

            var params_el = new SXL.XElement("params");

            root.Add(params_el);

            foreach (var p in this.Parameters)
            {
                var param_el = new SXL.XElement("param");
                params_el.Add(param_el);

                p.AddXmlElement(param_el);
            }

            return(doc);
        }
        /// <remarks>Internal for testing.</remarks>
        internal static void RetargetWithMetadataConverter(XDocument xdoc, Version targetSchemaVersion, MetadataConverterDriver converter)
        {
            Debug.Assert(xdoc != null, "xdoc != null");
            Debug.Assert(EntityFrameworkVersion.IsValidVersion(targetSchemaVersion), "invalid target schema version");

            var inputXml = new XmlDocument { PreserveWhitespace = true };
            using (var reader = xdoc.CreateReader())
            {
                inputXml.Load(reader);
            }

            var outputXml = converter.Convert(inputXml, targetSchemaVersion);
            if (outputXml != null)
            {
                // Dev10 Bug 550594: There is a bug in XmlEditor that prevents from deleting the root node
                // unless the root node has previous sibling (like a comment or Xml declaration).
                if (xdoc.Root.PreviousNode == null)
                {
                    xdoc.Root.AddBeforeSelf(new XComment(""));
                }

                // update xml document with new root element
                xdoc.Root.Remove();
                using (var reader = new XmlNodeReader(outputXml))
                {
                    var newDoc = XDocument.Load(reader);
                    xdoc.Add(newDoc.Root);
                }

                // Do not reload artifact here
                // Until the transaction is commited, the XLinq representation of the parsed xml tree hasn't been generated yet.
            }
        }
        private void PerformCustomAction(XFormData data, string subject, string to, string from)
        {
            var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"));
            XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

            // This part uses the xform data to create a custom email with the data as an attachment
            var import = new XElement("Import", new XAttribute(XNamespace.Xmlns + "xsi", xsi));
            import.Add(new XElement("ElementInForm", data.GetValue("elementInForm")));
            doc.Add(import);

            var mailMessage = new MailMessage
            {
                BodyEncoding = Encoding.UTF8,
                SubjectEncoding = Encoding.UTF8,
                IsBodyHtml = false,
                Body = import.ToString(),
                Subject = subject,
            };

            mailMessage.From = new MailAddress(from);
            mailMessage.To.Add(to);

            var customXml = new MemoryStream();
            doc.Save(customXml);
            customXml.Position = 0;

            Attachment xml = new Attachment(customXml, "example.xml", MediaTypeNames.Text.Xml);
            mailMessage.Attachments.Add(xml);
            new SmtpClient().Send(mailMessage);
        }
 public override void SaveImages(Stream stream)
 {
     var xdocument = new XDocument();
     var xelement = new XElement("images");
     xdocument.Add(xelement);
     xdocument.Save(stream);
 }
        /// <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;
            }
        }
        public void Submit(Order order, XDocument document)
        {
            if (order == null)
            {
                throw new ArgumentNullException("order");
            }

            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            var ordersElement = document.Element("Orders");
            if (ordersElement == null)
            {
                ordersElement = new XElement("Orders");
                document.Add(ordersElement);
            }

            var orderElement = new XElement("Order",
                new XAttribute("OrderType", order.OrderType),
                new XAttribute("Shares", order.Shares),
                new XAttribute("StopLimitPrice", order.StopLimitPrice),
                new XAttribute("TickerSymbol", order.TickerSymbol),
                new XAttribute("TimeInForce", order.TimeInForce),
                new XAttribute("TransactionType", order.TransactionType),
                new XAttribute("Date", DateTime.Now.ToString(CultureInfo.InvariantCulture))
                );
            ordersElement.Add(orderElement);

            string message = String.Format(CultureInfo.CurrentCulture, Resources.LogOrderSubmitted,
                                           orderElement.ToString());
            logger.Log(message, Category.Debug, Priority.Low);
        }
        private void WriteConfigurationRoot(XDocument xDocument)
        {
            var xElement = new XElement("Configuration");
            xElement.SetAttributeValue("Name", XmlConfiguration.Name);

            xDocument.Add(xElement);
        }
        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");
        }
Beispiel #18
0
        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);
        }
        public override string ToString()
        {
            var configuration = new XDocument();

            configuration.Add(new XElement("vitreousCMS"));
            configuration.Root.Add(new XElement
            (
                "settings",
                new XAttribute("username", Settings.Username),
                new XAttribute("password", Settings.Password),
                new XAttribute("theme", Settings.Theme),
                new XAttribute("title", Settings.Title)
            ));

            configuration.Root.Add(new XElement
            (
                "pages",
                Pages.Select(p => new XElement
                (
                    "page",
                    new XAttribute("title", p.Title),
                    new XAttribute("name", p.Name),
                    new XAttribute("order", p.Order),
                    new XAttribute("isDraft", p.IsDraft),
                    new XAttribute("isPublished", p.IsPublished)
                )).ToArray()
            ));

            return configuration.ToString();
        }
        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);
            }
        }
Beispiel #21
0
        private static XDocument GenerateXDoc(IEnumerable<Project> projects)
        {
            XDocument xdoc = new XDocument();
            var rootElement = new XElement("projects");
            xdoc.Add(rootElement);
            foreach (var project in projects)
            {
                rootElement.Add(
                    new XElement("project",
                                 new XElement("name", project.Name),
                                 new XElement("fundingSucceeded", project.FundingSucceeded),
                                 new XElement("link", project.Link),
                                 new XElement("currency", project.Currency),
                                 new XElement("company", project.Company),
                                 new XElement("fundingGoal", project.FundingGoal),
                                 new XElement("backers", project.Backers),
                                 new XElement("totalFunding", project.TotalFunding),
                                 new XElement("description", project.Description),
                                 new XElement("startDate", project.StartDate),
                                 new XElement("endDate", project.EndDate),
                                 new XElement("category", project.Category),
                                 new XElement("levels", project.Levels.Select(
                                     x => new XElement("level",
                                                       new XElement("backers", x.Backers),
                                                       new XElement("maxBackersAllowed", x.MaxBackersAllowed),
                                                       new XElement("remainingBackersAllowed", x.RemainingBackersAllowed),
                                                       new XElement("isSoldOut", x.IsSoldOut),
                                                       new XElement("description", x.Description),
                                                       new XElement("totalFunding", x.TotalFunding),
                                                       new XElement("money", x.Money),
                                                       new XElement("moneyUSD", x.MoneyUSD))))));
            }

            return xdoc;
        }
Beispiel #22
0
 public bool Save(string filename)
 {
     XDocument xDoc = new XDocument();
     xDoc.Add(CurrentProject.CreateElement());
     xDoc.Save(filename);
     return true;
 }
Beispiel #23
0
        public static string GetAnswerFile(string formId, Dictionary <Guid, string> providedData)
        {
            XDocument xDocument = new System.Xml.Linq.XDocument();

            XElement answerFile   = new XElement("AnswerFile");
            XElement headerInfo   = new XElement("HeaderInfo");
            XElement templateInfo = new XElement("TemplateInfo");

            templateInfo.Add(new XAttribute("TemplateGroupId", formId.ToString()));
            templateInfo.Add(new XAttribute("RunId", Guid.NewGuid().ToString().ToString()));
            templateInfo.Add(new XAttribute("FirstLaunchTimeUtc", DateTime.UtcNow));
            headerInfo.Add(templateInfo);

            answerFile.Add(headerInfo);
            xDocument.Add(answerFile);

            if (providedData.Count > 0)
            {
                XElement providedDataElm = new XElement("ProvidedData");

                foreach (Guid key in providedData.Keys)
                {
                    XElement dataElm = new XElement("Data");
                    dataElm.Add(new XAttribute("Id", key.ToString()));
                    dataElm.Add(new XCData(providedData[key]));
                    providedDataElm.Add(dataElm);
                }

                answerFile.Add(providedDataElm);
            }

            return(answerFile.ToString());
        }
        public void Seve(IEnumerable<Book> iter)
        {
            XDocument doc = new XDocument();
            XElement library = new XElement("library");
            doc.Add(library);

            foreach (Book b in iter)
            {
                XElement book = new XElement("book");

                XElement author = new XElement("author");
                author.Value = b.Author;
                book.Add(author);
                
                XElement title = new XElement("title");
                title.Value = b.Title;
                book.Add(title);

                XElement genre = new XElement("genre");
                genre.Value = b.Genre;
                book.Add(genre);

                XElement year = new XElement("year");
                year.Value = b.Year.ToString();
                book.Add(year);

                doc.Root.Add(book);
            }

            doc.Save(path);
        }
Beispiel #25
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);
        }
Beispiel #26
0
 public XDocument ParseDocument(string text)
 {
     //System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
     XDocument doc = new XDocument();
     try
     {
         StringCounter sc = new StringCounter(text);
         sc.TrimStart();
         if (sc.StartsWith("<"))
         {
             while (!sc.IsAtEnd)
             {
                 XContainer childNode = this.ParseNode(sc, doc);
             }
             XElement[] enm = MyHelper.EnumToArray(doc.Elements());
             if (enm.Length > 1)
             {
                 XElement root = new XElement(XName.Get("root"));
                 foreach (XElement elem in enm)
                 {
                     root.Add(elem);
                 }
                 doc.Elements().Remove();
                 doc.Add(root);
             }
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.Message);
     }
     //sw.Stop();
     //System.Diagnostics.Debug.WriteLine(sw.Elapsed.TotalMilliseconds.ToString("N0"));
     return doc;
 }
        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");

        }
        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);
        }
        private XDocument CreatePayload(String roleName, String packageUrl, String pathToConfigurationFile, String label)
        {
            String configurationFile = File.ReadAllText(pathToConfigurationFile);
            String base64ConfigurationFile = ConvertToBase64String(configurationFile);

            String base64Label = ConvertToBase64String(label);

            XElement xMode = new XElement(wa + "Mode", "auto");
            XElement xPackageUrl = new XElement(wa + "PackageUrl", packageUrl);
            XElement xConfiguration = new XElement(wa + "Configuration", base64ConfigurationFile);
            XElement xLabel = new XElement(wa + "Label", base64Label);
            XElement xRoleToUpgrade = new XElement(wa + "RoleToUpgrade", roleName);
            XElement upgradeDeployment = new XElement(wa + "UpgradeDeployment");

            upgradeDeployment.Add(xMode);
            upgradeDeployment.Add(xPackageUrl);
            upgradeDeployment.Add(xConfiguration);
            upgradeDeployment.Add(xLabel);
            upgradeDeployment.Add(xRoleToUpgrade);

            XDocument payload = new XDocument();
            payload.Add(upgradeDeployment);
            payload.Declaration = new XDeclaration("1.0", "UTF-8", "no");

            return payload;
        }
Beispiel #30
0
        private XDocument GetPeopleXDoc(CultureInfo culture)
        {
            var doc = new XDocument();
            var root = new XElement("People");
            var element = new XElement("Person");

            var items = new XElement("Items");
            items.Add(new XElement("Item", new XElement("Name", "One"), new XElement("Value", 1)));
            items.Add(new XElement("Item", new XElement("Name", "Two"), new XElement("Value", 2)));
            items.Add(new XElement("Item", new XElement("Name", "Three"), new XElement("Value", 3)));
            element.Add(new XElement("Name", "Foo"),
                new XElement("Age", 50),
                new XElement("Price", 19.95m.ToString(culture)),
                new XElement("StartDate", new DateTime(2009, 12, 18, 10, 2, 23).ToString(culture)));

            element.Add(items);
            root.Add(element);
            element = new XElement("Person");

            element.Add(new XElement("Name", "Bar"),
                new XElement("Age", 23),
                new XElement("Price", 23.23m.ToString(culture)),
                new XElement("StartDate", new DateTime(2009, 12, 23, 10, 23, 23).ToString(culture)));

            element.Add(items);

            root.Add(element);
            doc.Add(root);

            return doc;
        }
Beispiel #31
0
        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));
        }
Beispiel #32
0
        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);

        }
Beispiel #33
0
        public XDocument ReportToXMLDOM()
        {
            var el_report = CreateReportXML();

            var doc = new System.Xml.Linq.XDocument();

            doc.Add(el_report);
            return(doc);
        }
Beispiel #34
0
 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();
 }
Beispiel #35
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));
        }
        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));
        }
Beispiel #37
0
        /// <summary>
        /// Método Público encargado de Obtener la Instancia por Defecto del Usuario Y Compania
        /// </summary>
        /// <param name="id_usuario"></param>
        /// <returns></returns>
        public string ObtienePatioDefaultUsuario(int id_usuario, int id_compania)
        {
            //Obteniendo Instancia de Usuario/Patio
            using (UsuarioPatio up = UsuarioPatio.ObtieneInstanciaDefault(id_usuario, id_compania))
            {
                //Declarando documento xml
                System.Xml.Linq.XDocument d = new System.Xml.Linq.XDocument(new System.Xml.Linq.XDeclaration("1.0", "UTF-8", "true"));

                //Creando elemento raíz
                System.Xml.Linq.XElement e = new System.Xml.Linq.XElement("UsuarioPatio");

                //Añadiendo atributos
                e.Add(new System.Xml.Linq.XElement("idPatio", up.id_patio));
                e.Add(new System.Xml.Linq.XElement("idAccesoDefault", up.id_acceso_default));

                //Añadiendo elemento raíz a documento
                d.Add(e);

                //Realizando Conversión de Objeto a XML
                return(d.ToString());
            }
        }
Beispiel #38
0
        } // 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);
        }
        private System.Xml.Linq.XDocument CreateHtmlDom()
        {
            var xdoc = new System.Xml.Linq.XDocument();

            var el_html = new System.Xml.Linq.XElement("html");

            xdoc.Add(el_html);

            var el_head = new System.Xml.Linq.XElement("head");

            el_html.Add(el_head);

            var el_style = new System.Xml.Linq.XElement("style");

            el_head.Add(el_style);

            el_style.Value = this.Options.StyleSheet;

            var el_body = new System.Xml.Linq.XElement("body");

            el_html.Add(el_body);
            return(xdoc);
        }
        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);
        }