Best method to populate XML from SQL query in ASP.NET? - asp.net

I need to create a service that will return XML containing data from the database. So I am thinking about using an ASHX that will accept things like date range and POST an XML file back. I have dealt with pages pulling data from SQL Server and populating into a datagrid for visual display but never into XML for delivery, what is the best way to do this? Also if an ASHX and POST isn't the best method for delivery let me know... thanks!
EDIT: These answers are great and pointing me in the right direction. I should have also mentioned that the XML format has already been decided so I can't use any automatically generated one.

Combining linq2sqlwith the XElement classes, something along the lines:
var xmlContacts =
new XElement("contacts",
(from c in context.Contacts
select new XElement("contact",
new XElement
{
new XElement("name", c.Name),
new XElement("phone", c.Phone),
new XElement("postal", c.Postal)
)
)
).ToArray()
)
);
Linq2sql will retrieve the data in a single call to the db, and the processing of the XML will be done at the business server. This splits the load better, since you don't have the sql server doing all the job.

Have you tried DataSet.WriteXml()?
You could have this be the output of a web service call.

Sql Server 2005 and above has a "FOR XML AUTO" command that will convert your recordset to XML for you. Then you just have to return a string from your ASHX.

Beginning with SQL Server 2000, you can return query results as XML. For absolute control of them, use the "FOR XML EXPLICIT" command. You can use any format you desire that way.
http://msdn.microsoft.com/en-us/library/ms189068.aspx
It's as easy as writing your result to the raw output then. For added points, you can return the result set to a XPathDocument, pass it through an XSL transformation, and send the results out in any format you choose (HTML vs XML at the click of a button perhaps).

you can obtained that to a datatable and then call myTable.WriteXML()
if you are populating classes with the your database results then add the serializable attribute to the header your classes, and use the XMLSerializer

Converting an automatically generated format into a specified one is a job for xslt. Just find a way to run the output from the tool through an xslt filter.
Oracle has a great product for doing exactly this job - the oracle XDK. But it's a java thing, not ASP as far as I know.
For an example, this XHTML
http://www.anbg.gov.au/abrs/online-resources/flora/stddisplay.xsql?pnid=2524
is generated automatically from this XML, which is generated by oracle
http://www.anbg.gov.au/abrs/online-resources/flora/stddisplay.xsql?pnid=2524&xml-stylesheet=none
Of course, you are not after XHTML, but some other XML format. But XSLT will do the job.

Related

xmlreader.Create return none

i am trying to read from xml string But ,
` XmlReader reader=XmlReader.Create(new StringReader(stringXml)`
reader is always none. why is reader objest none ?
You have to call the read function.
reader.Read();
Here is the answer for your question. There seems to be no problem and the XmlReader is ready to be utilized.
Actually, if you are open to use .NetFramework 3.5 and higher you could benefit from using Linq To Xml:
XElement x = XElement.Load(new StringReader(s));
this happened to me in code that had been working for years. there were two paths for populating the xml string used in creating the xReader. The first pulled xml from a text parameter. If the text parameter was empty then it would fetch the string from sql server. If the text parameter was null, however, then I was getting "none" from the xReader. This despite the fact that SQL return perfectly formed xml. If the text parameter was an empty zero-length string, however, then everything worked fine, that is, the fetch to SQL ran, fetch xml and loaded the reader. It was like the runtime .net engine was running both paths simultaneously and giving me the worst possible outcome, instead of the desired outcome.

parsing simple xml with jquery from asp.net webservice

I'm breaking my head over this for a while now and I have no clue what I do wrong.
The scenario is as followed, I'm using swfupload to upload files with a progressbar
via a webservice. the webservice needs to return the name of the generated thumbnail.
This all goes well and though i prefer to get the returned data in json (might change it later in the swfupload js files) the default xml data is fine too.
So when an upload completes the webservice returns the following xml as expected (note I removed the namespace in webservice):
<?xml version="1.0" encoding="utf-8"?>
<string>myfile.jpg</string>
Now I want to parse this result with jquery and thought the following would do it:
var xml = response;
alert($(xml).find("string").text());
But I cannot get the string value. I've tried lots of combinations (.html(), .innerhtml(), response.find("string").text() but nothing seems to work. This is my first time trying to parse xml via jquery so maybe I'm doing something fundemantally wrong. The 'response' is populated with the xml.
I hope someone can help me with this.
Thanks for your time.
Kind regards,
Mark
I think $(xml) is looking for a dom object with a selector that matches the string value of XML, so I guess it's coming back null or empty?
The First Plugin mentioned below xmldom looks pretty good, but if your returned XML really is as simply as your example above, a bit of string parsing might be quicker, something like:
var start = xml.indexOf('<string>') + 8;
var end = xml.indexOf('</string>');
var resultstring = xml.substring(start, end);
From this answer to this question: How to query an XML string via DOM in jQuery
Quote:
There are a 2 ways to approach this.
Convert the XML string to DOM, parse it using this plugin or follow this tutorial
Convert the XML to JSON using this plugin.
jQuery cannot parse XML. If you pass a string full of XML content into the $ function it will typically try to parse it as HTML instead using standard innerHTML. If you really need to parse a string full of XML you will need browser-specific and not-globally-supported methods like new DOMParser and the XMLDOM ActiveXObject, or a plugin that wraps them.
But you almost never need to do this, since an XMLHttpRequest should return a fully-parsed XML DOM in the responseXML property. If your web service is correctly setting a Content-Type response header to tell the browser that what's coming back is XML, then the data argument to your callback function should be an XML Document object and not a string. In that case you should be able to use your example with find() and text() without problems.
If the server-side does not return an XML Content-Type header and you're unable to fix that, you can pass the option type: 'xml' in the ajax settings as an override.

Adding XML Attributes to a DataSet

I want to add an attribute to the dataset declared below whose value is the value of one of the field in the row.
So I want to add the id as shown below.
<root>
<Table id="GAS-405">
<apple>2009FA</apple>
<orange>3.00</orange>
<pear>BGPR</pear>
<banana>GAS-405</banana>
</Table>
</root>
This will help me identify the node later in my application.
Is this possible? Is this easier to do using XMLDocument?
Dim sdaFoo As SqlDataAdapter = New SqlDataAdapter("SELECT BLAH FROM BLAHBLAH", conn)
Dim dsFoo As DataSet = New DataSet()
dsFoo.DataSetName = "apple"
sdaFoo.Fill(dsFoo)
dsFoo.WriteXml("C:\Inetpub\wwwroot\foo.xml")
Dataset.WriteXml() is really a convenience method rather than a flexible way of dealing with XML.
You'll need to take another approach. There are a few options:
If you're just adding a single attribute, you could hack it into the resulting xml by re-opening the file as an XDocument, adding the attribute to the necessary element, and saving it again. Not too elegant, but easy, and sometimes easy is best. Even better, just use WriteXml() to put your xml into a string, then load the string as your XDocument.
Generate the XML from your query directly, rather than as a dataset. Sql Server 2005 and 2008 have some good XML methods that allow you to select a set of rows as XML (SELECT ... FOR XML) and specify what it looks like.
Use XmlSerialization for your dataset and inject the attribute using custom control of the serialization process.... which will be way more trouble than it's worth.
Store the attribute somewhere else outside of your XML and use some kind of object to keep track of it. Not really sure what your code is like, but that might be a great option.
Use GetXML() method of DataSet to get whole XML as a string. Then add your custom attributes and write that string into xml file using StreamWriter.

How can I query a Word docx in an ASP.NET app?

I would like to upload a Word 2007 or greater docx file to my web server and convert the table of contents to a simple xml structure. Doing this on the desktop with traditional VBA seems like it would have been easy. Looking at the WordprocessingML XML data used to create the docx file is confusing. Is there a way (without COM) to navigate the document in more of an object-oriented fashion?
I highly recommend looking into the Open XML SDK 2.0. It's a CTP, but I've found it extremely useful in manipulating xmlx files without having to deal with COM at all. The documentation is a bit sketchy, but the key thing to look for is the DocumentFormat.OpenXml.Packaging.WordprocessingDocument class. You can pick apart the .docx document if you rename the extension to .zip and dig into the XML files there. From doing that, it looks like a Table of Contents is contained in a "Structured Document" tag and that things like the headings are in a hyperlink from there. Putzing around with it a bit, I found that something like this should work (or at least give you a starting point).
WordprocessingDocument wordDoc = WordprocessingDocument.Open(Filename, false);
SdtBlock contents = wordDoc.MainDocumentPart.Document.Descendants<SdtBlock>().First();
List<string> contentList = new List<string>();
foreach (Hyperlink section in contents.Descendants<Hyperlink>())
{
contentList.Add(section.Descendants<Text>().First().Text);
}
Here is a blog post on querying Open XML WordprocessingML documents using LINQ to XML. Using that code, you can write a query as follows:
using (WordprocessingDocument doc =
WordprocessingDocument.Open(filename, false))
{
foreach (var p in doc.MainDocumentPart.Paragraphs())
{
Console.WriteLine("Style: {0} Text: >{1}<",
p.StyleName.PadRight(16), p.Text);
foreach (var c in p.Comments())
Console.WriteLine(
" Comment Author:{0} Text:>{1}<",
c.Author, c.Text);
}
}
Blog post: Open XML SDK and LINQ to XML
-Eric
See XML Documents and Data as a starting point. In particular, you'll want to use LINQ to XML.
In general, you do not want to use COM in a .NET application.

Exporting a HTML Table to Excel from ASP.NET MVC

I am currently working with ASP.NET MVC and I have an action method that displays few reports in the view in table format.
I have a requirement to export the same table to an Excel document at the click of a button in the View.
How can this be achieved? How would you create your Action method for this?
In your controller action you could add this:
Response.AddHeader("Content-Disposition", "filename=thefilename.xls");
Response.ContentType = "application/vnd.ms-excel";
Then just send the user to the same view. That should work.
I'm using component, called Aspose.Cells (http://www.aspose.com/categories/.net-components/aspose.cells-for-.net/).
It's not free, though the most powerful solution I've tried +)
Also, for free solutions, see: Create Excel (.XLS and .XLSX) file from C#
Get data from database using your data access methods in dot net.
Use a loop to get each record.
Now add each record in a variable one by one like this.
Name,Email,Phone,Country
John,john#john.com,+12345,USA
Ali,ali#ali.com,+54321,UAE
Naveed,naveed#naveed.com,+09876,Pakistan
use 'new line' code at the end of each row (For example '\n')
Now write above data into a file with extension .csv (example data.csv)
Now open that file in EXCEL
:)

Resources