예제 #1
0
        public XElement ProcessRequest(XElement QBXmlMsgsRq)
        {
            var doc = new XDocument(
                        new XProcessingInstruction("qbxml", string.Format("version=\"{0}\"", _qbXmlVersion)),
                        new XElement("QBXML",
                            new XElement("QBXMLMsgsRq", new XAttribute("onError", "stopOnError"),
                                QBXmlMsgsRq)));

            if (_log.IsDebugEnabled) 
                _log.Debug("QBXmlMsgsRq:\n" + doc.ToString());

            XElement response = null;
            try
            {
                response = _sessionFactory.ProcessRequest(_ticket,
                    "<?xml version=\"1.0\"?>" + doc.ToString(SaveOptions.DisableFormatting));
            }
            catch (COMException e)
            {
                if (e.Message == "QuickBooks found an error when parsing the provided XML text stream.")
                {
                    _log.ErrorFormat("Error parsing QBXML: \n<?xml version=\"1.0\"?>\n{0}", doc.ToString());
                    throw new QBException(e.Message, "", doc);
                }
                else
                    throw e;
            }
            return response;
        }
예제 #2
0
        private string consultaNFe()
        {
            XmlSchemaCollection myschema = new XmlSchemaCollection();
            string sxdoc = "";
            XNamespace pf = "http://www.portalfiscal.inf.br/nfe";

            try
            {
                XDocument xdoc = new XDocument(new XElement(pf + "consSitNFe", new XAttribute("versao", sversaoLayoutCons),//sversaoLayoutCons),
                                                  new XElement(pf + "tpAmb", Acesso.TP_AMB.ToString()),
                                                   new XElement(pf + "xServ", "CONSULTAR"),
                                                   new XElement(pf + "chNFe", objPesquisa.sCHAVENFE)));

                string sCaminhoConsulta = Pastas.PROTOCOLOS + "Consulta_" + objPesquisa.sCHAVENFE + ".xml";
                if (File.Exists(sCaminhoConsulta))
                {
                    File.Delete(sCaminhoConsulta);
                }
                StreamWriter writer = new StreamWriter(sCaminhoConsulta);
                writer.Write(xdoc.ToString());
                writer.Close();
                //belValidaXml.ValidarXml("http://www.portalfiscal.inf.br/nfe", Pastas.SCHEMA_NFE + "\\2.01\\consSitNFe_v2.01.xsd", sCaminhoConsulta);
                sxdoc = xdoc.ToString();

            }
            catch (XmlException x)
            {
                throw new Exception(x.Message.ToString());
            }
            catch (XmlSchemaException x)
            {
                throw new Exception(x.Message.ToString());
            }
            return sxdoc;
        }
예제 #3
0
 public XmlDocument GetXmlDocument()
 {
     XDocument document = new XDocument(this.GetXElement());
     document.Declaration = new XDeclaration("1.0", "utf-8", "yes");
     var xmlDoc = new XmlDocument();
     var xmlAsString = document.ToString();
     xmlDoc.LoadXml(document.ToString());
     return xmlDoc;
 }
예제 #4
0
        public ContentResult Index()
        {
            //Scraping SO feed
            var url = "http://stackoverflow.com/feeds";
            XmlReader reader = XmlReader.Create(url);
            SyndicationFeed feed = SyndicationFeed.Load(reader);

            var q = from item in feed.Items
                    select new {
                        Title = item.Title,
                        URL = item.Id,
                        Date = item.PublishDate
                    };

            //Build the SiteMap
            XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
            var sitemap = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XElement(ns + "urlset",
                    from i in q
                    select
                        new XElement(ns + "url",
                          new XElement(ns + "loc", i.URL),
                              new XElement(ns + "lastmod", String.Format("{0:yyyy-MM-dd}", i.Date)),
                          new XElement(ns + "changefreq", "monthly"),
                          new XElement(ns + "priority", "0.5")
                          )
                        )
                      );

            return Content(sitemap.ToString(), "text/xml");
        }
예제 #5
0
        static void Main(string[] args)
        {
            //根目录
            string rootPath = @"E:\";
            var dir = new DirectoryInfo(rootPath);
            //递归获得目录树
            var doc = new XDocument(GetDirectoryXml(dir));
            //将目录树存入文件haha.txt
            System.IO.File.WriteAllText("haha.txt", doc.ToString());

            //读入目录树文件
            XDocument xdoc = XDocument.Load("haha.txt");
            //获得文件中第一级的所有XElements,也就是我们的根目录E
            List<XElement> els = xdoc.Elements().ToList<XElement>();
            //获得文件中第一级第一个Element的子Elements(也就是第二级)
            List<XElement> es = els[0].Elements().ToList<XElement>();
            for (int i = 0; i < es.Count; i++)
            {//遍历第二级
                XElement   currElement = es[i];
                //按照文件结构的设计,每一个element都只有一个attribute
                XAttribute currElementsAttribute = currElement.FirstAttribute;
                //name也就是当前element的名字,或者是dir,或者是file,如果是dir那就可以继续展开这个element,得到他的子elements
                string name = currElement.Name.ToString();
                //当前element的attribute的value存了文件名或文件夹名
                string path = currElementsAttribute.Value.ToString();
                Console.WriteLine(name + ":" + path);
            }
            Console.ReadLine();
        }
예제 #6
0
        /// <summary>
        /// Updates the underlying store with this as the new representation of the identified resource
        /// </summary>
        /// <param name="resourceUri">The resource for whom this is the representation</param>
        /// <param name="resourceDescription">The rdf xml document that describes the resource</param>
        public override void ApplyFragment(string resourceUri, XDocument resourceDescription)
        {
            try
            {
                var wr = WebRequest.Create(_endpoint + "?" + _resourceParameterName + "=" + resourceUri);
                wr.Method = "POST";
                wr.ContentType = "application/rdf+xml";
                var reqstream = wr.GetRequestStream();
                using (var strwriter = new StreamWriter(reqstream))
                {
                   strwriter.WriteLine(resourceDescription.ToString());
                }

                // get response
                var resp = wr.GetResponse() as HttpWebResponse;
                if (resp.StatusCode != HttpStatusCode.OK || resp.StatusCode != HttpStatusCode.Accepted)
                {
                    Logging.LogError(1, "Error in apply fragment. Remote server returned code {0}", resp.StatusCode);
                }
                resp.Close();
            } catch(Exception ex)
            {
                Logging.LogError(1, "Error in apply fragment {0}", ex.Message);
            }
        }
 public PostFile(string setFilePath)
 {
     filePath = setFilePath;
     file = XDocument.Load(filePath);
     FilesLoaded++;
     TotalTextCharactersProcessed += file.ToString().Length;
 }
 /// <summary>
 /// 获取XDocument转换后的IResponseMessageBase实例(通常在反向读取日志的时候用到)。
 /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常
 /// </summary>
 /// <returns></returns>
 public static IResponseMessageBase GetResponseEntity(XDocument doc)
 {
     ResponseMessageBase responseMessage = null;
     ResponseMsgType msgType;
     try
     {
         msgType = MsgTypeHelper.GetResponseMsgType(doc);
         switch (msgType)
         {
             case ResponseMsgType.Text:
                 responseMessage = new ResponseMessageText();
                 break;
             case ResponseMsgType.Image:
                 responseMessage = new ResponseMessageImage();
                 break;
             case ResponseMsgType.Voice:
                 responseMessage = new ResponseMessageVoice();
                 break;
             case ResponseMsgType.Video:
                 responseMessage = new ResponseMessageVideo();
                 break;
             case ResponseMsgType.News:
                 responseMessage = new ResponseMessageNews();
                 break;
             default:
                 throw new UnknownRequestMsgTypeException(string.Format("MsgType:{0} 在ResponseMessageFactory中没有对应的处理程序!", msgType), new ArgumentOutOfRangeException());
         }
         EntityHelper.FillEntityWithXml(responseMessage, doc);
     }
     catch (ArgumentException ex)
     {
         throw new WeixinException(string.Format("ResponseMessage转换出错!可能是MsgType不存在!,XML:{0}", doc.ToString()), ex);
     }
     return responseMessage;
 }
예제 #9
0
        /**
         * Speichert den Score
         */
        public void writeScore(ErrorCallback ecb, string playerName, int score, int level, long time, int mode)
        {
            time /= 10000;
            this.ecb = ecb;
            XDocument doc = new XDocument(
                new XElement("scoreentry",
                    new XElement("playername", playerName),
                    new XElement("score", score),
                    new XElement("level", level),
                    new XElement("time", time),
                    new XElement("mode", mode)
                )
            );
            postData = doc.ToString();
            try
            {
                WebRequest request = WebRequest.Create(proxy);
                request.Method = "POST";

                request.ContentType = "text/xml";
                request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);
            }
            catch (Exception e)
            { ecb(e.Message); }
        }
예제 #10
0
        public void GetSiteMapXml(Uri uri, string path, ISet<string> urls)
        {
            IndexedPagesCount = urls.Count;

            XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
            
            var sitemap = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XElement(ns + "urlset",
                    from i in urls
                    select
                        //Add ns to every element.
                    new XElement(ns + "url",
                      new XElement(ns + "loc", i)
                      )
                    )
                  );
            string headerXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n";
            Byte[] info = new UTF8Encoding(true).GetBytes(headerXml + sitemap.ToString());
            using (FileStream fs = File.Create(path + uri.Authority + ".xml"))
            {
                // Add some information to the file.
                fs.Write(info, 0, info.Length);
            }
        }
예제 #11
0
        public ActionResult SiteMap()
        {
            var _Pages = PageService.GetSitemap(APP._SiteID, Request.Url.Authority);
            XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
            var _Q = from i in _Pages.Pages
                     select
                     new XElement(ns + "url",
                         new XElement(ns + "loc", Request.Url.Scheme + "://" + Request.Url.Authority + "/" + i.FriendlyUrl)
                         , new XElement(ns + "changefreq", "always"));

            if (_Pages.Blog)
            {
                _Q = _Q.Union((from i in _Pages.Posts
                               select
                               new XElement(ns + "url",
                                   new XElement(ns + "loc", Url.Action("detail", "blog", new { BlogPostID = i.BlogPostID, FriendlyUrl = i.FriendlyUrl }, Request.Url.Scheme))
                                   , new XElement(ns + "changefreq", "always"))))
                                   .Union((from i in _Pages.BlogCategories
                                           select
                                           new XElement(ns + "url",
                                               new XElement(ns + "loc", Url.Action("index", "blog", new { BlogCategoryFriendlyUrl = i.FriendlyUrl }, Request.Url.Scheme))
                                               , new XElement(ns + "changefreq", "always"))))
                                               .Union((from i in _Pages.BlogTags
                                                       select
                                                       new XElement(ns + "url",
                                                           new XElement(ns + "loc", Url.Action("tag", "blog", new { BlogTagName = i.BlogTagName }, Request.Url.Scheme))
                                                           , new XElement(ns + "changefreq", "always"))));
            }
            var sitemap = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement(ns + "urlset", _Q));
            return Content("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + sitemap.ToString(), "text/xml");
        }
예제 #12
0
        //<?xml version="1.0" encoding="utf-8"?>
        //<xml>
        //  <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName>
        //  <FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName>
        //  <CreateTime>1357986928</CreateTime>
        //  <MsgType><![CDATA[text]]></MsgType>
        //  <Content><![CDATA[中文]]></Content>
        //  <MsgId>5832509444155992350</MsgId>
        //</xml>

        /// <summary>
        /// 获取XDocument转换后的IRequestMessageBase实例。
        /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常
        /// </summary>
        /// <returns></returns>
        public static IRequestMessageBase GetRequestEntity(XDocument doc, PostModel postModel = null)
        {
            RequestMessageBase requestMessage = null;
            RequestInfoType infoType;

            try
            {
                infoType = InfoTypeHelper.GetRequestInfoType(doc);
                switch (infoType)
                {
                    case RequestInfoType.component_verify_ticket:
                        requestMessage = new RequestMessageComponentVerifyTicket();
                        break;
                    case RequestInfoType.unauthorized:
                        requestMessage = new RequestMessageUnauthorized();
                        break;
                    default:
                        throw new UnknownRequestMsgTypeException(string.Format("InfoType:{0} 在RequestMessageFactory中没有对应的处理程序!", infoType), new ArgumentOutOfRangeException());//为了能够对类型变动最大程度容错(如微信目前还可以对公众账号suscribe等未知类型,但API没有开放),建议在使用的时候catch这个异常
                }
                EntityHelper.FillEntityWithXml(requestMessage, doc);
            }
            catch (ArgumentException ex)
            {
                throw new WeixinException(string.Format("RequestMessage转换出错!可能是InfoType不存在!,XML:{0}", doc.ToString()), ex);
            }
            return requestMessage;
        }
        public ActionResult Rsd(string blogPath) {
            Logger.Debug("RSD requested");

            BlogPart blogPart = _blogService.Get(blogPath);

            if (blogPart == null)
                return HttpNotFound();

            const string manifestUri = "http://archipelago.phrasewise.com/rsd";

            var urlHelper = new UrlHelper(ControllerContext.RequestContext, _routeCollection);
            var url = urlHelper.Action("", "", new { Area = "XmlRpc" });

            var options = new XElement(
                XName.Get("service", manifestUri),
                new XElement(XName.Get("engineName", manifestUri), "Orchard CMS"),
                new XElement(XName.Get("engineLink", manifestUri), "http://orchardproject.net"),
                new XElement(XName.Get("homePageLink", manifestUri), "http://orchardproject.net"),
                new XElement(XName.Get("apis", manifestUri),
                    new XElement(XName.Get("api", manifestUri),
                        new XAttribute("name", "MetaWeblog"),
                        new XAttribute("preferred", true),
                        new XAttribute("apiLink", url),
                        new XAttribute("blogID", blogPart.Id))));

            var doc = new XDocument(new XElement(
                                        XName.Get("rsd", manifestUri),
                                        new XAttribute("version", "1.0"),
                                        options));

            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            return Content(doc.ToString(), "text/xml");
        }
예제 #14
0
 public void WriteConfig(ConfigurationCollection conf)
 {
     var paths = this.GetPaths(conf.Paths);
     var overrides = this.GetOverrides(conf.Overrides);
     var document = new XDocument(new XElement("configuration", paths, overrides));
     File.WriteAllText(Path, document.ToString());
 }
예제 #15
0
        // TODO: should accept RootFolder
        public string Export(IEnumerable<Feed> feeds)
        {
            var x = new XDocument(new XElement("opml",
                 new XAttribute("version", "1.0"),
                    new XElement("head",
                        new XElement("title", "subscriptions")),
                            new XElement("body",
                                new XElement("outline",
                                    new XAttribute("title", "home"),
                                        new XAttribute("text", "home"),
                                           from f in feeds
                                           select new XElement("outline",
                                                               new XAttribute("text", f.Title),
                                                               new XAttribute("title", f.Title),
                                                               new XAttribute("type", "rss"),
                                                               new XAttribute("xmlUrl", f.FeedUri.ToString()),
                                                               new XAttribute("htmlUrl", f.HtmlUri.ToString())
                                               )
                                  )
                            )
                )
            );

            return x.ToString();
        }
예제 #16
0
        public static void PersistXML()
        {
            XDocument customer =
            new XDocument(
            new XDeclaration("1.0", "UTF-16", "yes"),
            new XElement("customer",
            new XAttribute("id", "C01"),
            new XElement("firstName", "Paolo"),
            new XElement("lastName", "Pialorsi"),
            new XElement("addresses",
            new XElement("address",
            new XAttribute("type", "email"),
            "*****@*****.**"),
            new XElement("address",
            new XAttribute("type", "url"),
            "http://www.devleap.it/"),
            new XElement("address",
            new XAttribute("type", "home"),
            "Brescia - Italy"))));

            String st = customer.ToString();
            Console.WriteLine(st);


            foreach(XElement a in customer.Descendants("addresses").Elements()) 
            {
                  Console.WriteLine(a);
            }

           

        }
 public static object GetAllComments(WmlDocument doc, CommentFormat format)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
     using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
     {
         IEnumerable<XElement> comments = null;
         WordprocessingCommentsPart commentsPart = document.MainDocumentPart.WordprocessingCommentsPart;
         if (commentsPart != null)
         {
             XDocument commentsPartDocument = commentsPart.GetXDocument();
             comments = commentsPartDocument.Element(W.comments).Elements(W.comment);
         }
         if (comments != null)
         {
             XDocument commentsDocument =
                 new XDocument(
                     new XElement(W.comments,
                         new XAttribute(XNamespace.Xmlns + "w", W.w),
                         comments
                     )
                 );
             switch (format)
             {
                 case CommentFormat.PlainText:
                     return commentsDocument.ToString();
                 case CommentFormat.Xml:
                     return commentsDocument;
                 case CommentFormat.Docx:
                     return CreateCommentsDocument(comments);
             }
         }
         return null;
     }
 }
예제 #18
0
        static void Main(string[] args)
        {
            string fileName1 = "C:\\xdoc1.xml";
            string fileName2 = "C:\\xdoc2.xml";

            XDocument xdoc1 = new XDocument(
                new XElement("Employees",
                    new XElement("Employee", "Matt"),
                    new XElement("Employee", "Dan")
                )
            );

            xdoc1.Save(fileName1);
            Console.WriteLine(string.Format("Saving XML to {0}", fileName1));
            Console.WriteLine(xdoc1.ToString());
            Console.WriteLine("");
            Console.WriteLine(string.Format("Reading XML from {0}", "URL"));

            var xdoc2 = XDocument.Load("http://blog.pluralsight.com/new-releases/feed");
            //Console.WriteLine(xdoc2.ToString());
            //Console.WriteLine("");
            Console.WriteLine(string.Format("Saving XML to {0}", fileName2));
            xdoc2.Save(fileName2);

            //var xelem1 = xdoc2.Root.Elements("item\\title");
            //foreach (var el in xelem1) {
            //string txt1 = (string) el;
            //Console.WriteLine(txt1);
            //    }
            
            //Console.WriteLine(xdoc.ToString(SaveOptions.DisableFormatting));
        }
예제 #19
0
        public string ToXml()
        {
            var xdoc = new XDocument(
                new XDeclaration("1.0", "UTF-8", null),
                new XElement("caps",
                    new XElement("searching",
                        new XElement("search",
                            new XAttribute("available", SearchAvailable ? "yes" : "no"),
                            new XAttribute("supportedParams", "q")
                        ),
                        new XElement("tv-search",
                            new XAttribute("available", TVSearchAvailable ? "yes" : "no"),
                            new XAttribute("supportedParams", SupportedTVSearchParams)
                        )
                    ),
                    new XElement("categories",
                        from c in Categories
                        select new XElement("category",
                            new XAttribute("id", c.ID),
                            new XAttribute("name", c.Name),
                            from sc in c.SubCategories
                            select new XElement("subcat",
                                new XAttribute("id", sc.ID),
                                new XAttribute("name", sc.Name)
                            )
                        )
                    )
                )
            );

            return xdoc.Declaration.ToString() + Environment.NewLine + xdoc.ToString();
        }
예제 #20
0
		public void DisassembleXmlFromEndpointTest()
		{
			// Goal: Send in bytes (from stream) and get an XML document out
			var disassembler = new XmlDisassembler();

			XDocument document = new XDocument(new XElement("body",
				new XElement("level1",
					new XElement("level2", "text"),
					new XElement("level2", "other text"))));
			document.Declaration = new XDeclaration("1.0", "UTF-8", "yes");

			byte[] data = Encoding.GetEncoding(document.Declaration.Encoding).GetBytes(document.ToString());

			disassembler.Disassemble(data);
			Message message = disassembler.NextMessage();

			Assert.IsNull(disassembler.NextMessage(), "Expected only one message back");

			Assert.IsNotNull(message);
			Assert.IsNotNull(message.Stream);
			Assert.IsTrue(XNode.DeepEquals(document, XDocument.Parse(message.GetString())));
			Assert.IsTrue(XNode.DeepEquals(document, XDocument.Load(message.GetStream())));

			// Move these to MessageTest instead
			Assert.IsTrue(XNode.DeepEquals(document, message.RetrieveAs<XDocument>()));
			Assert.IsTrue(XNode.DeepEquals(document, message.RetrieveAs<XNode>()));
			Assert.IsTrue(XNode.DeepEquals(document, XDocument.Parse(message.RetrieveAs<XmlDocument>().OuterXml)));
		}
        /// <summary>
        /// The generate xml.
        /// </summary>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GenerateXml(IContent page)
        {
            if (page == null)
            {
                return string.Empty;
            }

            XDocument xDocument = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new object[0]);

            XElement xElement = new XElement("content");
            xElement.SetAttributeValue("name", XmlConvert.EncodeName(page.Name));

            List<KeyValuePair<string, string>> propertyValues = page.GetPropertyValues();

            foreach (KeyValuePair<string, string> content in propertyValues)
            {
                XElement xElement3 = new XElement(XmlConvert.EncodeName(content.Key));
                xElement3.SetValue(TextIndexer.StripHtml(content.Value, content.Value.Length));
                xElement.Add(xElement3);
            }

            xDocument.Add(xElement);

            return xDocument.ToString();
        }
        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();
        }
예제 #23
0
        // function that build the XML tree for dependency relationship
        public static void Dependendcy(Dictionary<string, List<Elem>> LocationsTable )
        {
            XDocument xml = new XDocument();
            XElement typedependency = new XElement("TypeDependency");

            foreach (string filename in LocationsTable.Keys)
            {
                foreach(Elem e in LocationsTable[filename])
                {
                    if(e.dependency.Length > 2)
                    {
                        XElement type = new XElement(e.name);
                        while (e.dependency.Length > 2)
                        {
                            e.dependency = e.dependency.Substring(2);
                            int start = e.dependency.IndexOf(' ');
                            string name = e.dependency.Substring(0, start);
                            XElement dep = new XElement(name);
                            type.Add(dep);
                            e.dependency = e.dependency.Substring(start-1);
                        }
                        typedependency.Add(type);
                    }
                }
            }
            xml.Add(typedependency);
            xml.Save( "Result"+ ".xml");
            Console.Write(xml.ToString());
            Console.Write("\n\n\n   .xml file is saved in ...\\WpfExecutive\\bin\\Debug\n");
        }
예제 #24
0
        public static Message MsSqlSelect(this Message message, MsSqlConnectionConfig config, string selectStatement)
        {
            Logger.Debug("Step");

            var adapter = new SqlDataAdapter(selectStatement, config.ToConnectionString());
            var dataSet = new DataSet();
            adapter.Fill(dataSet, "ResultTable");
            var result = new XDocument(new XElement("MsSqlSelectResult"));
            foreach (DataTable table in dataSet.Tables)
            {
                var doc = new XElement(table.TableName);
                foreach (DataRow row in table.Rows)
                {
                    var xmlRow = new XElement("Row");
                    foreach (DataColumn column in table.Columns)
                    {
                        xmlRow.Add(new XElement(column.ColumnName, row[column.Ordinal].ToString()));
                    }
                    doc.Add(xmlRow);
                }
                result.Root.Add(doc);
            }
            message.SetPayload(result.ToString());
            return message;
        }
예제 #25
0
        public ContentResult SiteMap()
        {
            List<Page> pages = Page.Collection.Find(Page.ActiveScope).ToList();
            List<Post> posts = Post.Collection.Find(Post.ActiveScope)
                .SetSortOrder(Post.DefaultSortByScope)
                .ToList();

            var sitemap = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                new XElement(AppSettings.SiteMapNamespace + "urlset",
                        from p in pages
                        select
                          new XElement(AppSettings.SiteMapNamespace + "url",
                            new XElement(AppSettings.SiteMapNamespace + "loc", string.Format(AppSettings.PageUrlFormat, Request.Url.Host, p.Url)),
                                new XElement("lastmod", String.Format("{0:yyyy-MM-dd}", p.UpdatedOn))
                                ),
                            new XElement("changefreq", "monthly"),
                            new XElement("priority", "0.5"),
                        from p in posts
                        select
                            new XElement(AppSettings.SiteMapNamespace + "url",
                            new XElement(AppSettings.SiteMapNamespace + "loc", string.Format(AppSettings.PostUrlFormat, Request.Url.Host, p.TitleTransliterated)),
                                new XElement("lastmod", String.Format("{0:yyyy-MM-dd}", p.UpdatedOn))
                                ),
                            new XElement("changefreq", "monthly"),
                            new XElement("priority", "0.5")
                        )
                );

            return Content(sitemap.ToString(), "text/xml");
        }
예제 #26
0
        public override string ToString()
        {
            var xml = new XDocument();
            var methodCall = new XElement("methodCall");
            methodCall.Add(new XElement("methodName", Method));
            xml.AddFirst(methodCall);

            if (Parameters.Count > 0)
            {
                var structi = new XElement("struct");
                var paramss = new XElement("params",
                                           new XElement("param",
                                                        new XElement("value", structi)));

                foreach (var xmlParameter in Parameters)
                {
                    var member = new XElement("member", new XElement("name", xmlParameter.Name), GetParameterValue(xmlParameter.Value));
                    structi.Add(member);
                }

                methodCall.Add(paramss);
            }

            return xml.ToString();
        }
예제 #27
0
        public SettingsPage()
        {
            InitializeComponent();

            #if !DEBUG
            _xmlDoc = string.IsNullOrEmpty(_settings.XmlThemes) ? XDocument.Load("Themes.xml") : XDocument.Parse(_settings.XmlThemes);
            #else
            _xmlDoc = XDocument.Load("Themes.xml");
            #endif
            if (_xmlDoc != null)
            {
                if (string.IsNullOrEmpty(_settings.XmlThemes)) _settings.XmlThemes = _xmlDoc.ToString();

                _themeNames = _xmlDoc.Descendants("theme").Attributes("name").Select(a => a.Value).ToList();
                ThemeList.ItemsSource = _themeNames;
                ThemeList.SelectedItem = _startTheme = _settings.ThemeName;

                ThemeList.SelectionChanged += (_, __) =>
                {
                    string name = ThemeList.SelectedItem as string;
                    if (!string.IsNullOrEmpty(name) && _xmlDoc != null && name != _settings.ThemeName)
                    {
                        _settings.ThemeName = name;
                        var node = _xmlDoc.Descendants("theme").Where(d => d.Attribute("name").Value == name).FirstOrDefault();
                        if (node != null) _settings.Theme = node.ToString();
                    }
                };
            }
            bytesUsed.Text = string.Format("Used space: {0}", GetStoreUsedSize().ToSize());
        }
예제 #28
0
        public void Save(int tenant)
        {
            SetupProgress(tenant);

            using (var backupWriter = new ZipWriteOperator(backup))
            {
                var doc = new XDocument(new XElement(ROOT, new XAttribute("tenant", tenant)));
                foreach (var provider in providers.Values)
                {
                    try
                    {
                        var elements = provider.GetElements(tenant, configs, backupWriter);
                        if (elements != null)
                        {
                            doc.Root.Add(new XElement(provider.Name, elements));
                        }
                    }
                    catch (Exception ex)
                    {
                        OnProgressError(ex);
                    }
                }

                var data = Encoding.UTF8.GetBytes(doc.ToString(SaveOptions.None));
                var stream = backupWriter.BeginWriteEntry(XML_NAME);
                stream.Write(data, 0, data.Length);
                backupWriter.EndWriteEntry();
            }
        }
예제 #29
0
        public ContentResult RSS()
        {
            List<Post> posts = Post.Collection.Find(Post.ActiveScope)
                .SetSortOrder(Post.DefaultSortByScope)
                .ToList();

            var rss = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("rss",
                  new XAttribute("version", "2.0"),
                        new XElement("channel",
                          new XElement("title", AppSettings.RSSTitle),
                          new XElement("link", AppSettings.RSSLink),
                          new XElement("description", AppSettings.RSSDescription),
                          new XElement("copyright", AppSettings.RSSCopyright),
                        from p in posts
                        select
                        new XElement("item",
                              new XElement("title", p.Title),
                              new XElement("description", p.Description),
                              new XElement("link", String.Format(AppSettings.PostUrlFormat, Request.Url.Host, p.TitleTransliterated)),
                              new XElement("pubDate", p.PublishedOn.ToString("R")),
                              new XElement("guid", String.Format(AppSettings.PostUrlFormat, Request.Url.Host, p.TitleTransliterated))
                              )
                          )
                     )
                );

            return Content(rss.ToString(), "text/xml");
        }
예제 #30
0
        private XDocument PostRest(string url, string username, string password, XDocument element)
        {
            string postData = element.ToString();

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password)));
            request.Method = "POST";
            request.ContentLength = postData.Length;
            request.ContentType = "text/xml";

            var writer = new StreamWriter(request.GetRequestStream());
            writer.Write(postData);
            writer.Close();

            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                using (var responseStream = new StreamReader(response.GetResponseStream()))
                {
                    return XDocument.Parse(responseStream.ReadToEnd());
                }
            }
            catch (WebException ex)
            {
                var response = (HttpWebResponse)ex.Response;
                if (response.StatusCode == HttpStatusCode.Unauthorized)
                    throw new Exception("Invalid Credentials");
                using (var responseStream = new StreamReader(ex.Response.GetResponseStream()))
                {
                    XNamespace ns = "http://schemas.microsoft.com/ws/2005/05/envelope/none";
                    XDocument doc = XDocument.Parse(responseStream.ReadToEnd());
                    throw new Exception(doc.Root.Element(ns + "Reason").Element(ns + "Text").Value);
                }
            }
        }
예제 #31
0
        public void XDocumentTypeConverterTests()
        {
            PrimitiveTypeConverter converter = new XDocumentTypeConverter();

            System.Xml.Linq.XDocument xdoc = (System.Xml.Linq.XDocument)converter.Parse("<?xml version=\"1.0\" encoding=\"iso-8859-1\" standalone=\"yes\"?><feed></feed>");
            Assert.AreEqual("<feed></feed>", xdoc.ToString());
            Assert.AreEqual("<feed></feed>", converter.ToString(xdoc));
        }
예제 #32
0
파일: Isv.cs 프로젝트: zwkjgs/XKD
 private void WriteReturnCode(int status, string msg)
 {
     System.Xml.Linq.XDocument xDocument = new System.Xml.Linq.XDocument(new System.Xml.Linq.XDeclaration("1.0", "utf-8", "no"), new object[]
     {
         new System.Xml.Linq.XElement("rsp", new object[]
         {
             new System.Xml.Linq.XElement("code", status.ToString()),
             new System.Xml.Linq.XElement("msg", msg)
         })
     });
     System.Web.HttpContext.Current.Response.ContentType = "text/xml";
     System.Web.HttpContext.Current.Response.Write(xDocument.ToString());
     System.Web.HttpContext.Current.Response.End();
 }
예제 #33
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());
            }
        }
예제 #34
0
        public static string ToString(this XDocument d, bool includeDeclaration)
        {
            if (!includeDeclaration)
            {
                return(d.ToString());
            }

            StringBuilder sb = new StringBuilder(2048);

            using (var sw = new StringWriter <UTF8Encoding>(sb))
            {
                try
                {
                    d.Save(sw);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }

            return(sb.ToString());
        }
예제 #35
0
    private List <List <int> > cTileMap = new List <List <int> >(); //holds the final array of collision data

    public static string ToOuterXml(System.Xml.Linq.XDocument xmlDoc)
    {
        return(xmlDoc.ToString());
    }