Dynamic XML - asp.net

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.

Related

Need an alternative to using StringBuilder when calling ExecuteXmlReader to return a very large XML file

Currently one my DAL methods uses the ExecuteXmlReader command to read and append to a StringBuilder object and return XML as a string. I realize this isn't the best way to handle very large files (200MB+) as when the ToString() method is called on StringBuilder it throws an out of memory exception.
There are certain constraints I need to adhere by - I cannot return a XMLReader out of the DAL (db connection stays open, etc), this XML will have to be written to file and keeping it's formatting for various reasons, currently using an XMLTextWriter's WriteRaw method for that purpose.
What would be the best data type to return from the DAL to make all this work with large XML files?
I explored the options of using a DataSet, Memory Stream and a Byte Array - but each have their shortfalls. I am looking for the best practice and some code samples would be helpful.
You can use XDocument the work with your xml files. You can use linq to xml to query through your elements. An example is below:
XDocument document = XDocument.Load("http://someurl.com/data.xml");
var elements = from element in document.Descendants("SomeElement")
select element;
Console.WriteLine(elements.First().Value);
If you also get the out of memory exception with this (i think you will), then you should take a look at the following post:
http://james.newtonking.com/archive/2007/12/11/linq-to-xml-over-large-documents.aspx
More information about the XDocument class can be found here:
http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx
and here
http://www.hookedonlinq.com/Print.aspx?Page=LINQtoXML5MinuteOverview
Good luck!

Programmatically Rendering an Umbraco Node

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

Make an ASP.NET Web service output an RSS Feed

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.

ASP.NET Localized web site -- updating on the fly

I think I have a solution to this, but is there a better way, or is this going to break on me?
I am constructing a localized web site using global/local resx files. It is a requirement that non-technical users can edit the strings and add new languages through the web app.
This seems easy enough -- I have a form to display strings and the changes are saved with code like this snippet:
string filename = MapPath("App_GlobalResources/strings.hu.resx");
XmlDocument xDoc = new XmlDocument();
XmlNode xNode;
xDoc.Load(filename);
xNode = xDoc.SelectSingleNode("//root/data[#name='PageTitle']/value");
xNode.InnerText = txtNewTitle.Text;
xDoc.Save(filename);
Is this going to cause problems on a busy site? If it causes a momentary delay for recompilation, that's no big deal. And realistically, this form won't see constant, heavy use. What does the community think?
I've used a similar method before for a very basic "CMS". The site wasn't massively used but it didn't cause me any problems.
I don't think changing a resx will cause a recycle.
We did something similar, but used a database to store the user modified values. We then provided a fallback mechanism to serve the overridden value of a localized key.
That said, I think your method should work fine.
Have you considered creating a Resource object? You would need to wrap your settings into a single object that all the client code would use. Something like:
public class GuiResources
{
public string PageTitle
{
get return _pageTitle;
}
// Fired once when the class is first created.
void LoadConfiguration()
{
// Load settings from config section
_pageTitle = // Value from config
}
}
You could make it a singleton or a provider, that way the object is loaded only one time. Also you could make it smart to look at the current thread to get the culture info so you know what language to return.
Then in your web.config file you can create a custom section and set restartOnExternalChanges="true". That way, your app will get the changed when they are made.

JSON string to list or other usable format in asp.net 2.0

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!

Resources