public async Task WriteResponse(XElement feed)
        {
            ResponseContentType = "application/atom+xml; type=feed; charset=utf-8";

            MemoryStream stream = new MemoryStream();
            XmlWriter writer = XmlWriter.Create(stream);
            feed.WriteTo(writer);
            writer.Flush();
            byte[] data = stream.ToArray();

            await WriteResponseAsync(data);
        }
        protected string ParseXml2String(XElement doc)
        {
            using (StringWriter sw = new StringWriter())
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                {
                    settings.OmitXmlDeclaration = true;

                    using (XmlWriter writer = XmlWriter.Create(sw, settings))
                    {
                        if (doc != null)
                        {
                            doc.WriteTo(writer);
                        }
                    }
                }

                return sw.ToString();
            }
        }
示例#3
0
    void XmlTest()
    {
        XElement root = new XElement ("root");
        for (int i = 0; i < 3; i ++) {
            XElement item = new XElement ("item");
            item.Add (new XAttribute ("1item" + i.ToString (), i));
            item.Add (new XAttribute ("2item" + i.ToString (), i));
            item.Add (new XAttribute ("3item" + i.ToString (), i));
        }
        using (FileStream fs = new FileStream( Application.dataPath + "/test.xml",FileMode.Create)) {
            XmlWriterSettings setting = new XmlWriterSettings ();
            setting.Indent = true;
            setting.IndentChars = "\t";
            setting.NewLineChars = "\n";
            setting.Encoding = Encoding.UTF8;
            using (XmlWriter xw = XmlWriter.Create(fs, setting)) {
                root.WriteTo (xw);
            }
        }

        //		using(FileStream fs = new FileStream( FILE_DIR + "/" + "ServerConfig/terrainEditorConfig.xml", FileMode.Create ) )
        //		{
        //			XmlWriterSettings setting = new XmlWriterSettings();
        //			setting.Indent = true;
        //			setting.IndentChars = "\t";
        //			setting.NewLineChars = "\n";
        //			setting.Encoding = Encoding.UTF8;
        //			using (XmlWriter xw = XmlWriter.Create(fs, setting))
        //			{
        //				root.WriteTo(xw);
        //			}
        //		}
        //	}
    }
        public static string Create(CasperJsTestsResults casperJsTestsResults)
        {
            XNamespace testRunNamespace =
                XNamespace.Get("http://microsoft.com/schemas/VisualStudio/TeamTest/2010");

            var xml = new XElement("TestRun",
                new XAttribute("id", Guid.NewGuid().ToString()),
                new XElement("ResultSummary",
                    new XAttribute("outcome", "Completed"),
                    new XElement("Counters",
                        new XAttribute("total", (casperJsTestsResults.PassedTests.Count + casperJsTestsResults.FailedTests.Count).ToString()),
                        new XAttribute("passed", casperJsTestsResults.PassedTests.Count.ToString()),
                        new XAttribute("failed", casperJsTestsResults.FailedTests.Count.ToString()))),
                new XElement("TestDefinitions",
                    GetUnitTestsDefinitions(casperJsTestsResults)),
                new XElement("TestEntries",
                    GetUnitTestsEntries(casperJsTestsResults)),
                new XElement("Results",
                    GetUnitTestsResults(casperJsTestsResults))
                );

            var xDocument = new XDocument(xml);

            xDocument.Root.Name = testRunNamespace + xDocument.Root.Name.LocalName;

            using (var textWriter = new StringWriter())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(textWriter))
                {
                    xml.WriteTo(xmlWriter);
                }
                return textWriter.ToString();
            }
        }
示例#5
0
		internal static void WriteElement(XmlWriter writer, XElement element)
		{
			if (WriteWholeNode(element))
			{
				// Write entire element in one gulp, to avoid eating needed spaces in <Run> elements.
				element.WriteTo(writer);
			}
			else
			{
				writer.WriteStartElement(element.Name.LocalName);
				foreach (var attribute in element.Attributes())
				{
					writer.WriteAttributeString(attribute.Name.LocalName, attribute.Value);
				}
				if (element.HasElements)
				{
					foreach (var childNode in element.Elements().ToArray())
					{
						// Recurse on down to the bottom.
						WriteElement(writer, childNode);
						childNode.Remove();
					}
				}
				else
				{
					if (!string.IsNullOrEmpty(element.Value))
						writer.WriteString(element.Value);
				}
				writer.WriteEndElement();
			}
		}
        public static void WriteTo(Bundle bundle, XmlWriter writer, bool summary = false)
        {
            if (bundle == null) throw new ArgumentException("Bundle cannot be null");

            var root = new XElement(BundleXmlParser.XATOMNS + BundleXmlParser.XATOM_FEED);

            if (!String.IsNullOrWhiteSpace(bundle.Title)) root.Add(xmlCreateTitle(bundle.Title));
            if (SerializationUtil.UriHasValue(bundle.Id)) root.Add(xmlCreateId(bundle.Id));
            if (bundle.LastUpdated != null) root.Add(new XElement(BundleXmlParser.XATOMNS + BundleXmlParser.XATOM_UPDATED, bundle.LastUpdated));

            if (!String.IsNullOrWhiteSpace(bundle.AuthorName))
                root.Add(xmlCreateAuthor(bundle.AuthorName, bundle.AuthorUri));
            if (bundle.TotalResults != null) root.Add(new XElement(BundleXmlParser.XOPENSEARCHNS + BundleXmlParser.XATOM_TOTALRESULTS, bundle.TotalResults));

            if (bundle.Links != null)
            {
                foreach (var l in bundle.Links)
                    root.Add(xmlCreateLink(l.Rel, l.Uri));
            }

            if (bundle.Tags != null)
            {
                foreach (var tag in bundle.Tags)
                    root.Add(TagListSerializer.CreateTagCategoryPropertyXml(tag));
            }

            foreach (var entry in bundle.Entries)
                root.Add(createEntry(entry, summary));

            root.WriteTo(writer);
            //var result = new XDocument(root);
            //result.WriteTo(writer);
        }
示例#7
0
 public static string XElementToString(XElement xml)
 {
     var sw = new StringWriterUTF8(CultureInfo.CurrentCulture);
     var writer = XmlWriter.Create(sw, new XmlWriterSettings() { Indent = true, IndentChars = "\t", Encoding = Encoding.UTF8 });
     xml.WriteTo(writer);
     writer.Flush();
     writer.Close();
     return sw.ToString();
 }
示例#8
0
		public void Write(Interaction interaction) {
			var tree = new XElement("tape",
			    new XElement("interaction", 
					MapRequest(interaction.Request),
			        MapResponse(interaction.Response)
			    )
			);
			
			tree.WriteTo(writer);
		}
 private string SaveXElementUsingXmlWriter(XElement elem, NamespaceHandling nsHandling)
 {
     StringWriter sw = new StringWriter();
     using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = nsHandling, OmitXmlDeclaration = true }))
     {
         elem.WriteTo(w);
     }
     sw.Dispose();
     return sw.ToString();
 }
示例#10
0
		private void Write(XmlWriter writer)
		{
			writer.WriteStartDocument();

			XElement root = new XElement(Xmlns + "Image",
				new XAttribute("TileSize", AllTileDefaults.DziTileSize),
				new XAttribute("Overlap", _dziTileOverlap),
				new XAttribute("Format", AllTileDefaults.DziTileFormat),
				new XElement(Xmlns + "Size", new XAttribute("Width", _size.Width), new XAttribute("Height", _size.Height)));
			root.WriteTo(writer);

			writer.WriteEndDocument();
		}
示例#11
0
        // Private Methods
        //======================================================================

        private void Write(XmlWriter outputWriter)
        {
            outputWriter.WriteStartDocument();

            XElement root = new XElement(Xmlns + "Image",
                new XAttribute("TileSize", DefaultTileSize),
                new XAttribute("Overlap", DefaultOverlap),
                new XAttribute("Format", DefaultFormat),
                new XElement(Xmlns + "Size",
                        new XAttribute("Width", m_size.Width),
                        new XAttribute("Height", m_size.Height)));
            root.WriteTo(outputWriter);
        }
示例#12
0
        public virtual void Table(TextWriter writer)
        {
            var tab = new XElement("table"
                , new XAttribute("id", "postGrid")
                , new XAttribute("class", "list"));

            var th = TableHeader();
            tab.Add(th);

            foreach (object row in ReadData())
                tab.Add(row);

            tab.WriteTo(XmlWriter.Create(writer));
        }
        protected override void OnProcessRecord()
        {
            var netConfig = new XElement(
                NetconfigNamespace + "NetworkConfiguration",
                new XAttribute("xmlns", NetconfigNamespace.NamespaceName),
                new XAttribute(XNamespace.Xmlns + "xsi", InstanceNamespace.NamespaceName),
                new XElement(NetconfigNamespace + "VirtualNetworkConfiguration"));

            var stream = new MemoryStream();
            var writer1 = XmlWriter.Create(stream);
            netConfig.WriteTo(writer1);
            writer1.Flush();
            stream.Seek(0L, SeekOrigin.Begin);

            this.ExecuteClientActionInOCS(null, this.CommandRuntime.ToString(), s => this.Channel.SetNetworkConfiguration(s, stream));
        }
示例#14
0
        public static void Write()
        {
            var xmlConfig = new XElement("Jira",
                                new XElement("ServerUrl", ServerUrl),
                                new XElement("Username", Username),
                                new XElement("Password", Password));

            using (var xmlWriter = XmlWriter.Create(JiraOutput.PrefsPathWithFileName, new XmlWriterSettings()
            {
                Indent = true,
                IndentChars = " "
            }))
            {
                xmlConfig.WriteTo(xmlWriter);
            }
        }
示例#15
0
文件: Program.cs 项目: kiszu/ForBlog
        static void Main(string[] args)
        {
            //Write XML 1.1 file
            StringBuilder sb = new StringBuilder();
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.Encoding = Encoding.UTF8;
            xws.Indent = true;
            //Disable character checking
            xws.CheckCharacters = false;

            System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(sb, xws);
            //write your own header
            xw.WriteProcessingInstruction("xml", "version='1.1'");
            XElement doc = new XElement("root");
            doc.Add(
                    new XElement("test", 
                            new XAttribute("val", "\x03")));
            //use WriteTo instead of Save
            doc.WriteTo(xw);
            xw.Close();

            //Print XML contents to console
            Console.WriteLine(sb.ToString());
            

            //Read XML 1.1 file
            TextReader tr = new StringReader(sb.ToString());
            tr.ReadLine(); //skip Version number '1.1' is invalid. exception

            XmlReaderSettings xrs = new XmlReaderSettings();
            xrs.CheckCharacters = false;
            XmlReader xr = XmlReader.Create(tr, xrs);

            var xmldoc = XElement.Load(xr);
            foreach (var e in xmldoc.Elements())
            {
                Console.Write("Element: {0}", e.Name);
                foreach (var a in e.Attributes())
                    Console.Write(" Attribute: {0}={1}", a.Name, a.Value);
                Console.WriteLine();
            }
                
        }
            // ReSharper restore SuggestBaseTypeForParameter
            // ReSharper disable SuggestBaseTypeForParameter
            private static string SerializeXElement(XElement element)
            {
                using (var stringWriter = new StringWriter())
                {
                    var settings = new XmlWriterSettings
                        {
                            Indent = true,
                            IndentChars = "\t",
                            OmitXmlDeclaration = true,
                        };

                    using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
                    {
                        element.WriteTo(xmlWriter);
                        xmlWriter.Flush();

                        return stringWriter.ToString();
                    }
                }
            }
示例#17
0
        public static BuildScript New(IFormater formater, string name, IEnumerable<Target> targets)
        {
            XElement scriptRoot = new XElement("project",
                                                new XAttribute("name", Path.GetFileName(name)),

                                               	ImportsFor(targets),

                                                from t in targets
                                                select new	XElement("target", CollectDependencies(t, AttributesFor(t, formater))));

            AddDefaultTargetIfOneExists(scriptRoot, targets);

            Stream output = new MemoryStream();
            using(var xmlWriter = XmlWriter.Create(output, new XmlWriterSettings { OmitXmlDeclaration =  true, Indent = true}))
            {
                scriptRoot.WriteTo(xmlWriter);
            }
            output.Position = 0;

            return new BuildScript(name, output);
        }
		public string RemoveVirtualNetworkConfigProcess()
		{
			Action<string> action = null;
			object[] xAttribute = new object[3];
			xAttribute[0] = new XAttribute("xmlns", RemoveAzureVNetConfigCommand.netconfigNamespace.NamespaceName);
			xAttribute[1] = new XAttribute(XNamespace.Xmlns + "xsi", RemoveAzureVNetConfigCommand.instanceNamespace.NamespaceName);
			xAttribute[2] = new XElement(RemoveAzureVNetConfigCommand.netconfigNamespace + "VirtualNetworkConfiguration");
			XElement xElement = new XElement(RemoveAzureVNetConfigCommand.netconfigNamespace + "NetworkConfiguration", xAttribute);
			MemoryStream memoryStream = new MemoryStream();
			XmlWriter xmlWriter = XmlWriter.Create(memoryStream);
			xElement.WriteTo(xmlWriter);
			xmlWriter.Flush();
			memoryStream.Seek((long)0, SeekOrigin.Begin);
			using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
			{
				try
				{
					RemoveAzureVNetConfigCommand removeAzureVNetConfigCommand = this;
					if (action == null)
					{
						action = (string s) => base.Channel.SetNetworkConfiguration(s, memoryStream);
					}
					((CmdletBase<IServiceManagement>)removeAzureVNetConfigCommand).RetryCall(action);
					Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
					ManagementOperationContext managementOperationContext = new ManagementOperationContext();
					managementOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
					managementOperationContext.set_OperationId(operation.OperationTrackingId);
					managementOperationContext.set_OperationStatus(operation.Status);
					ManagementOperationContext managementOperationContext1 = managementOperationContext;
					base.WriteObject(managementOperationContext1, true);
				}
				catch (CommunicationException communicationException1)
				{
					CommunicationException communicationException = communicationException1;
					this.WriteErrorDetails(communicationException);
				}
			}
			return null;
		}
示例#19
0
 public static void Describe(this HttpResponse res, ClaimsPrincipal principal)
 {
     res.StatusCode = 200;
     res.ContentType = "text/xml";
     var xml = new XElement("xml");
     if (principal != null)
     {
         foreach (var identity in principal.Identities)
         {
             xml.Add(identity.Claims.Select(claim => 
                 new XElement("claim", new XAttribute("type", claim.Type), 
                 new XAttribute("value", claim.Value), 
                 new XAttribute("issuer", claim.Issuer))));
         }
     }
     using (var memory = new MemoryStream())
     {
         using (var writer = new XmlTextWriter(memory, Encoding.UTF8))
         {
             xml.WriteTo(writer);
         }
         res.Body.Write(memory.ToArray(), 0, memory.ToArray().Length);
     }
 }
 private static void WriteXml(Stream outputStream, XElement xml)
 {
     using (var writer = XmlWriter.Create(outputStream))
     {
         xml.WriteTo(writer);
     }
 }
示例#21
0
        void WriteElement(XElement element)
        {
            lock (writeLock) {
                Log.Debug ("GCM-XMPP: Sending: " + element);

                element.WriteTo (xml);
                xml.Flush ();
            }
        }
示例#22
0
 private static void Describe(HttpResponse res, AuthenticateContext result)
 {
     res.StatusCode = 200;
     res.ContentType = "text/xml";
     var xml = new XElement("xml");
     if (result != null && result.Principal != null)
     {
         xml.Add(result.Principal.Claims.Select(claim => new XElement("claim", new XAttribute("type", claim.Type), new XAttribute("value", claim.Value))));
     }
     if (result != null && result.Properties != null)
     {
         xml.Add(result.Properties.Select(extra => new XElement("extra", new XAttribute("type", extra.Key), new XAttribute("value", extra.Value))));
     }
     using (var memory = new MemoryStream())
     {
         using (var writer = new XmlTextWriter(memory, Encoding.UTF8))
         {
             xml.WriteTo(writer);
         }
         res.Body.Write(memory.ToArray(), 0, memory.ToArray().Length);
     }
 }
示例#23
0
        /// <summary>
        /// Writes the element to custom XML part.
        /// </summary>
        /// <param name="customXmlPart">The custom XML part.</param>
        /// <param name="rootElement">The root element.</param>
        public void WriteElementToCustomXmlPart(CustomXmlPart customXmlPart, XElement rootElement)
        {
            if (customXmlPart == null)
            {
                throw new ArgumentNullException("customXmlPart");
            }

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

            using (XmlWriter writer = XmlWriter.Create(customXmlPart.GetStream(FileMode.Create, FileAccess.Write)))
            {
                rootElement.WriteTo(writer);
                writer.Flush();
            }
        }
示例#24
0
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            //read the incoming JSON stream:
            var inStream = pInMsg.BodyPart.GetOriginalDataStream();
            var json = string.Empty;
            using (var reader = new StreamReader(inStream))
            {
                json = reader.ReadToEnd();
            }

            //convert to XML:
            var document = JsonConvert.DeserializeXNode(json, "root");
            var output = new XElement(XName.Get(RootElementName, TargetNamespace));
            output.Add(document.Root.Descendants());

            //fix up the namespaces:
            XNamespace ns = TargetNamespace;
            foreach (var element in output.Descendants())
            {
                element.Name = ns.GetName(element.Name.LocalName);
                var attributes = element.Attributes().ToList();
                element.Attributes().Remove();
                foreach (XAttribute attribute in attributes)
                {
                    if (!attribute.IsNamespaceDeclaration)
                    {
                        element.Add(new XAttribute(attribute.Name.LocalName, attribute.Value));
                    }
                }
            }

            //write to output body stream:
            var outStream = new MemoryStream();
            var writer = new XmlTextWriter(outStream, Encoding.Default);
            output.WriteTo(writer);
            writer.Flush();
            outStream.Flush();
            outStream.Position = 0;
            pInMsg.BodyPart.Data = outStream;

            //promote the message type:
            pInMsg.Context.Promote(_MessageTypeProperty.Name.Name, _MessageTypeProperty.Name.Namespace, string.Format("{0}#{1}", TargetNamespace, RootElementName));

            return pInMsg;
        }
示例#25
0
 /// <summary>
 /// Create an audio overlay for the page if appropriate.
 /// We are looking for the page to contain spans with IDs. For each such ID X,
 /// we look for a file _storage.FolderPath/audio/X.mp{3,4}.
 /// If we find at least one such file, we create pageDocName_overlay.smil
 /// with appropriate contents to tell the reader how to read all such spans
 /// aloud.
 /// </summary>
 /// <param name="pageDom"></param>
 /// <param name="pageDocName"></param>
 private void AddAudioOverlay(HtmlDom pageDom, string pageDocName)
 {
     var spansWithIds = pageDom.RawDom.SafeSelectNodes(".//span[@id]").Cast<XmlElement>();
     var spansWithAudio =
         spansWithIds.Where(x =>GetOrCreateCompressedAudioIfWavExists(x.Attributes["id"].Value) != null);
     if (!spansWithAudio.Any())
         return;
     var overlayName = GetOverlayName(pageDocName);
     _manifestItems.Add(overlayName);
     string smilNamespace = "http://www.w3.org/ns/SMIL";
     XNamespace smil = smilNamespace;
     string epubNamespace = "http://www.idpf.org/2007/ops";
     XNamespace epub = epubNamespace;
     var seq = new XElement(smil+"seq",
         new XAttribute("id", "id1"), // all <seq> I've seen have this, not sure whether necessary
         new XAttribute(epub + "textref", pageDocName),
         new XAttribute(epub + "type", "bodymatter chapter") // only type I've encountered
         );
     var root = new XElement(smil + "smil",
         new XAttribute( "xmlns", smilNamespace),
         new XAttribute(XNamespace.Xmlns + "epub", epubNamespace),
         new XAttribute("version", "3.0"),
         new XElement(smil + "body",
             seq));
     int index = 1;
     TimeSpan pageDuration = new TimeSpan();
     foreach (var span in spansWithAudio)
     {
         var spanId = span.Attributes["id"].Value;
         var path = GetOrCreateCompressedAudioIfWavExists(spanId);
         var dataDurationAttr = span.Attributes["data-duration"];
         if (dataDurationAttr != null)
         {
             pageDuration += TimeSpan.FromSeconds(Double.Parse(dataDurationAttr.Value));
         }
         else
         {
             //var durationSeconds = TagLib.File.Create(path).Properties.Duration.TotalSeconds;
             //duration += new TimeSpan((long)(durationSeconds * 1.0e7)); // argument is in ticks (100ns)
             // Haven't found a good way to get duration from MP3 without adding more windows-specific
             // libraries. So for now we'll figure it from the wav if we have it. If not we do a very
             // crude estimate from file size. Hopefully good enough for BSV animation.
             var wavPath = Path.ChangeExtension(path, "wav");
             if (RobustFile.Exists(wavPath))
             {
     #if __MonoCS__
                 pageDuration += new TimeSpan(new FileInfo(path).Length);	// TODO: this needs to be fixed for Linux/Mono
     #else
                 using (WaveFileReader wf = RobustIO.CreateWaveFileReader(wavPath))
                     pageDuration += wf.TotalTime;
     #endif
             }
             else
             {
                 NonFatalProblem.Report(ModalIf.All, PassiveIf.All,
                     "Bloom could not find one of the expected audio files for this book, nor a precomputed duration. Bloom can only make a very rough estimate of the length of the mp3 file.");
                 // Crude estimate. In one sample, a 61K mp3 is 7s long.
                 // So, multiply by 7 and divide by 61K to get seconds.
                 // Then, to make a TimeSpan we need ticks, which are 0.1 microseconds,
                 // hence the 10000000.
                 pageDuration += new TimeSpan(new FileInfo(path).Length*7*10000000/61000);
             }
         }
         var epubPath = CopyFileToEpub(path);
         seq.Add(new XElement(smil+"par",
             new XAttribute("id", "s" + index++),
             new XElement(smil + "text",
                 new XAttribute("src", pageDocName + "#" + spanId)),
                 new XElement(smil + "audio",
                     // Note that we don't need to preserve any audio/ in the path.
                     // We now mangle file names so as to replace any / (with _2f) so all files
                     // are at the top level in the ePUB. Makes one less complication for readers.
                     new XAttribute("src", Path.GetFileName(epubPath)))));
     }
     _pageDurations[GetIdOfFile(overlayName)] = pageDuration;
     var overlayPath = Path.Combine(_contentFolder, overlayName);
     using (var writer = XmlWriter.Create(overlayPath))
         root.WriteTo(writer);
 }
示例#26
0
 private void MakeSpine(XNamespace opf, XElement rootElt, string manifestPath)
 {
     // Generate the spine, which indicates the top-level readable content in order.
     // These IDs must match the corresponding ones in the manifest, since the spine
     // doesn't indicate where to actually find the content.
     var spineElt = new XElement(opf + "spine");
     rootElt.Add(spineElt);
     foreach (var item in _spineItems)
     {
         var itemElt = new XElement(opf + "itemref",
             new XAttribute("idref", GetIdOfFile(item)));
         spineElt.Add(itemElt);
     }
     using (var writer = XmlWriter.Create(manifestPath))
         rootElt.WriteTo(writer);
 }
示例#27
0
		string FormatProjectExtension(XElement element)
		{
			var settings = new XmlWriterSettings {
				Indent = true,
				IndentChars = "  ",
				NewLineChars = "\r\n      ",
				NewLineHandling = NewLineHandling.Replace,
				OmitXmlDeclaration = true
			};
			var formattedText = new StringBuilder();
			using (XmlWriter writer = XmlWriter.Create(new StringWriter(formattedText), settings)) {
				element.WriteTo(writer);
			}
			return formattedText.ToString();
		}
示例#28
0
		/// <summary>
		/// 	Writes the file.
		/// </summary>
		/// <param name="filename"> The filename. </param>
		/// <param name="e"> The e. </param>
		/// <remarks>
		/// </remarks>
		protected virtual void WriteFile(string filename, XElement e) {
			filename += ".xml";
			using (var xmlwriter = XmlWriter.Create(filename, _xmlsettings)) {
				e.WriteTo(xmlwriter);
			}
		}
        public static void PostBlogEntry(ConsumerBase consumer, string accessToken, string blogUrl, string title, XElement body)
        {
            string feedUrl;
            var getBlogHome = WebRequest.Create(blogUrl);
            using (var blogHomeResponse = getBlogHome.GetResponse()) {
                using (StreamReader sr = new StreamReader(blogHomeResponse.GetResponseStream())) {
                    string homePageHtml = sr.ReadToEnd();
                    Match m = Regex.Match(homePageHtml, @"http://www.blogger.com/feeds/\d+/posts/default");
                    Debug.Assert(m.Success, "Posting operation failed.");
                    feedUrl = m.Value;
                }
            }
            const string Atom = "http://www.w3.org/2005/Atom";
            XElement entry = new XElement(
                XName.Get("entry", Atom),
                new XElement(XName.Get("title", Atom), new XAttribute("type", "text"), title),
                new XElement(XName.Get("content", Atom), new XAttribute("type", "xhtml"), body),
                new XElement(XName.Get("category", Atom), new XAttribute("scheme", "http://www.blogger.com/atom/ns#"), new XAttribute("term", "oauthdemo")));

            MemoryStream ms = new MemoryStream();
            XmlWriterSettings xws = new XmlWriterSettings() {
                Encoding = Encoding.UTF8,
            };
            XmlWriter xw = XmlWriter.Create(ms, xws);
            entry.WriteTo(xw);
            xw.Flush();

            WebRequest request = consumer.PrepareAuthorizedRequest(new MessageReceivingEndpoint(feedUrl, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), accessToken);
            request.ContentType = "application/atom+xml";
            request.Method = "POST";
            request.ContentLength = ms.Length;
            ms.Seek(0, SeekOrigin.Begin);
            using (Stream requestStream = request.GetRequestStream()) {
                ms.CopyTo(requestStream);
            }
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
                if (response.StatusCode == HttpStatusCode.Created) {
                    // Success
                } else {
                    // Error!
                }
            }
        }
示例#30
0
 /// <summary>
 /// Write xml based on segment type
 /// </summary>
 /// <param name="x"></param>
 /// <param name="segmentType"></param>
 /// <returns></returns>
 /// <remarks></remarks>
 private static string InternalToString(XElement x, SegmentTypes segmentType)
 {
     var writer = new StringWriter();
     var cw = new XmlWriter(writer) {SegmentType = segmentType};
     //Strip Namespace if it's an Xelement
     x = StripNS(x);
     //write
     x.WriteTo(cw);
     return writer.GetStringBuilder().ToString();
 }