I have been writing some Web services to be used by a few different client apps and i was trying to write a web service method that simply outputs an RSS XML Feed.
I can create the XML using an XmlTextWriter Object
Then i have tryed outputing to the Response (like i have done in the past when its an aspx page) but this only works it the return type is void (and still doesnt seem to output properly)
Then i tryed making the return type a string and using a StringWriter to output the xml from the XmlTextWriter but the output is then wrapped in a tag.
How can i do this?
Obviously create the interfaces and rest of the WCF service as normal.
Mark the class with the following attribute
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
And then this function
public Stream GetRSS()
{
string output;
//output = some_text;
MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(output));
WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
return ms;
}
I have some code for this, but it's more than will fit well in an SO post (about 1000 lines). It's really not that hard; the schema is simple enough you can do it yourself, but you don't have to: there are several components you can just plug in to create the xml for you.
You should see this question:
ASP.Net RSS feed
If you must use ASMX, then you can return an XmlDocument. Build the feed XML however you like, but then return the XmlDocument from your web method.
Related
I'm using Umbraco 4.5.2 and I have a node with a number of child nodes. Each child node represents a fragment of HTML that will be rendered in a control. The control loops over all the child nodes and renders them.
For the moment I have a bit of a dirty hack going in order to get the thing going (still fairly new to Umbraco) but I'd rather do this better.
The code I have at the moment looks like this:
private string GetItemHtml(Node node)
{
// Work out the URL of the HTML fragment
string url = "http://" + Context.Request.Url.Host +
":" + Context.Request.Url.Port +
node.Url;
// Get the fragment by making a call to the page
WebRequest req = WebRequest.Create(url);
WebResponse res = req.GetResponse();
using (Stream stream = res.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
return result;
}
}
As you can see, it is really rather ugly. I'm hoping there is some way to get this without having to make many HTTP calls, even if it is looping back to the same server - it can't be very efficient.
You can use the API to achieve what you are asking, try looking at the umbraco.library.RenderTemplate method. It accepts two parameters, the first is the id of the node to render and the second is the id of the template to use when rendering the node.
This is probably much easier to build using xslt in umbraco. If you want to do something that is not possible in xslt, you can create a XSLT extension function (implemented in C#, called from XSLT) to do that (see http://en.wikibooks.org/wiki/Umbraco/Create_xslt_exstension_like_umbraco.Library_in_C for more info).
For a sample XSLT that list child pages, see BlogListPosts.xslt in the umbraco blog package:
http://blog4umbraco.codeplex.com/SourceControl/changeset/view/54177#916032
I have some dynamically generated XML data that will be consumed by a few consumers (An ASPX page, a flash file and maybe another one as well).
I have implemented it as a custom handler. I construct the XML in the handler and output it using response.write.
Now If I set the DataFile property of my XMLDataSource to the handler, it tries to read the ashx file literally and does not call it through HTTP.
Any advice?
Place your XML generation code in a separate class. Have the handler use the class to create the XML and send the results to the client (BTW, don't use Response.Write what XML document tech are you using to build the XML in the first place?).
Make sure the class can expose the completed XML as a string.
In your ASPX page use the same class and assign the XML string to the data property of your XmlDataSource control.
Edit:
Since you are using a XmlTextWriter and from your comment the above is apparently a bit confusing I'll add these details.
You need to take the code that currently generates the XML and place it in a class in the App_Code folder (or possibly in a dll project). This class will have a method that takes as a parameter an XmlTextWriter.
public class XmlCreator
{
public void GenerateXml(XmlTextWriter writer)
{
//All your code that writes the XML
}
}
In your handler you then have this code:-
XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
XmlCreator creator = new XmlCreator();
XmlCreator.GenerateXml(writer);
Note no need for Response.Write and this gets the encoding done properly.
In your ASP.NET page you use:-
StringWriter source = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(source, Encoding.Unicode);
XmlCreator creator = new XmlCreator();
XmlCreator.GenerateXml(writer);
yourXmlDataSource.Data = source.ToString();
XmlCreator may not need to be instanced in which case you could use a static class it depends on what other data is need to feed the XM generation.
What's the ideal way of generating XML without creating and saving a file?
I'm thinking of using an ASP.NET page with code behind to generate the markup as XML.
Is this possible? Or would you have an alternative way?
I have a flash component that reads an XML file and I need to dynamically generate this file. I don't have write permission so I won't have the ability to create and save a file.
I was thinking of having an application page that grabs the data and provide property methods to generate the xml on the Settings.xml.aspx page with Settings.xml.aspx.cs codebehind.
Thanks.
The easiest way is to use System.Xml.XmlDocument or System.Xml.Linq.XDocument to build up the document. Both can be streamed out to the Response.OutputStream.
The smoothest approach (especially if you turn off buffering) is simply to create an XmlTextWriter round the Response.OutputStream. This is a forward only approach to generate XML but if the output is large it means you need less memory and content starts to arrive at the client earlier.
System.Xml.XmlDocument ?
In fact there are many ways to do it. It all depends on your needs. Maybe you could have a look at some examples of XDocument (or XmlDocument in .NET 2.0) and XmlWriter, none of these require you to save the XML to a file. You can either keep the object model in memory when using XDocument or write to a MemoryStream when using XmlWriter:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
using (XmlWriter writer = XmlWriter.Create (stream, settings))
{
writer.WriteStartElement ("customer");
writer.WriteElementString ("firstname", "Jim");
writer.WriteElementString ("lastname"," Bo");
writer.WriteEndElement();
}
// do further processing with the stream
}
The difference between the two is basically that the first one gives you access to the DOM whereas the second one simply writes out XML to an underlying stream.
Unfortunately, without knowing more details this question can only be answered vaguely.
Yes, it is perfectly feasible to generate XML "on the fly". Take a look at the XmlDocument class. And more info here.
I am playing around with ASP.NET MVC for the first time, so I apologize in advance if this sounds academic.
I have created a simple content management system using ASP.NET MVC. The url to retrieve a list of content, in this case, announcements, looks like:
http://www.mydomain.com/announcements/list/10
This will return the top ten most recent announcements.
My questions are as follows:
Is it possible for any website to consume this service? Or would I also have to expose it using something like WCF?
What are some examples, of how to consume this service to display this data on another website? I'm primarily programming in the .NET world, but I'm thinking if I could consume the service using javascript, or do something with Json, it could really work for any technology.
I am looking to dynamically generate something like the following output:
<div class="announcement">
<h1>Title</h1>
<h2>Posted Date</h3>
<p>Teaser</p>
More
</div>
For now ... is it possible to return an Html representation and display it in a webpage? Is this possible using just Javascript?
There is nothing to stop another client just scraping that particular page and parsing through your HTML.
However you would probably want another view using the same controller that generates the data that doesnt contain excess formatting HTML etc. Maybe look at using a well known format such as RSS?
You can return the result as JSON using something like below:
public JsonResult GetResults()
{
return Json(new { message = "SUCCESS" });
}
I think I would offer a view which contains the items as xml and another that returns JSON that way you have the best of both worlds.
I have a small post about how to call and return something using MVC, JQuery and JSON here.
Your ROUTE is perfectly fine and consumable by anyone. The trick is to how you want to expose your data for that route. You said XML. sure. You can even do JSon or Html or just plain ole text.
The trick would be in your controller Method and the view result object.
Here's the list of main view results :-
ActionResult
ContentResult
EmptyResult
JsonResult
RedirectResult
eg.
public <ContentResult> AnnouncmentIndex(int numberOfAnnouncements)
{
// Generate your Xml dynamically.
string xml = "<div class=\"announcement\"><h1>Title</h1><h2>Posted Date</h3><p>Teaser</p>More</div>"
Response.ContentType = "application/xml"; // For extra bonus points!
return Content(xml);
}
I have one JSON that is coming in a string format. I need to store it in a key-pair value or something like that. I am using asp.net 2.0 and can not use 3rd party DLL like Newtonsoft.Json.dll. I guess last option will be to use regular expression.
Can anybody please help me in this?
If you go to http://www.json.org/ and look towards the bottom of the page there are dozens of json libraries most of them open source, I believe they list 8 for C#. If you can not reference one of these libraries, I think your best bet would be to find one with a permissive license and simply add the code to your project.
Another idea is to look at the diagrams, grammer, and syntax at http://www.json.org/ and just write your own parser, but regex is NOT the way to do it. If you dont know how to write a parser you could look at one of the open source json libraries or start with something less complicated like a good CSV parser, here is a paper that looks pretty good: http://www.boyet.com/Articles/CsvParser.html
It is possible to serialize JSON using JScript in C# into key/value pairs. You need to add a few references to your project. They're part of the .NET framework, you just need to add the references to your project. You'll need:
Microsoft.JSript
Microsoft.Vsa
First, the usings at the top of your class:
using Microsoft.JScript;
using Microsoft.JScript.Vsa;
Then the Engine that will execute the script needs to be initialized somewhere in your 'Page' code-behind:
VsaEngine Engine = VsaEngine.CreateEngine();
Then you just create this method and call it by passing in your JSON object:
object EvalJScript(string JScript)
{
object result = null;
try
{
result = Microsoft.JScript.Eval.JScriptEvaluate(JScript, Engine);
}
catch (Exception ex)
{
return ex.Message;
}
return result;
}
The type of object returned (if JSON is passed in) is a 'JSObject'. You can access its values as key/value pairs. Read the MSDN documentation for more details on this object.
Here's an example of using the code:
string json = "({Name:\"Dan\",Occupation:\"Developer\"})";
JSObject o = EvalJScript(json) as JSObject;
string name = o["Name"] as string; // Value of 'name' will be 'Dan'
Could you use JScript.NET?
If so, should be easy enough with eval() - then just loop through the objects returned and translate into KeyValuePair's or whatever
You will need to use jscript.net as the code behind language, but other pages of your site should be fine to stay as c# if thats what you prefer.
As mentioned in previous comment, you will need to be aware of the security aspects and risks - only use eval if you trust the JSON you're parsing!