I am simply trying to load a dataset and output it on a webpage as XML with the schema being written as well. I have been researching to find a way to achieve this without any luck.
The code I am using is:
string str =
"SELECT Name,Members,MaxLvl,Faction,Government,Score FROM dim5orgs where faction =
'Omni' order by Score DESC";
// Connection string for a typical local MySQL installation
string cnnString = "Server=xxxxxxxnet;Port=3306;Database=xxx;Uid=xxxxx;Pwd=xxxx";
// Create a connection object and data adapter
MySqlConnection cnx = new MySqlConnection(cnnString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
// Create a SQL command object
string cmdText = str;
MySqlCommand cmd = new MySqlCommand(cmdText, cnx);
// Create a fill a Dataset
DataSet ds = new DataSet();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
StringWriter sw = new StringWriter();
ds.WriteXml(sw,XmlWriteMode.WriteSchema);
string result = sw.ToString();
Response.Write(result);
Right now I am getting output like:
Punk732220OmniRepublic1644786805740
Paradise754220OmniDepartment1633903815782
I would like the output to be in proper XML form somehow using the column names in the dataset.
Like:
<data>
<name>Punk</name>
<members>732</members>
<Maxlvl>220</MaxLvl>...etc
</data>
I would like to be in proper XML form, with the XML headers written properly.
Thank you.
Look into the documentation of the XmlSerializer Class. I think you could use it something like this:
StreamWriter streamWriter = new StreamWriter(fileLocation);
XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(ds.GetType());
xml.Serialize(streamWriter, ds);
streamWriter.Close();
I have not tried it with DataSets so I'm not sure.
When you say "I am getting output like", does that mean you are seeing that in your webpage, or that is what "result" contains when you debug the program?
If the former, you are probably missing setting the response type:
Response.ContentType = "text/xml";
and optionally the encoding:
Response.ContentEncoding = System.Text.Encoding.UTF8;
before you write your response.
EDIT: Also, make sure you are not returning any html from your page template or master page (assuming you are using .aspx files). You can check this by looking at your page source in your browser (right click and "view source" in IE). Apologies if this teaching you to suck eggs, from your question I didn't know if you have already checked these things or not.
Edit 2: I've tested your code, and if you set the response ContentType to text/xml it works for me.
Related
I'm trying to build a method in C# to get SSRS Reportviewer to generate a PDF output.
There are lots of information about the subject so it seemed to be an easy task.
The issue appears when my DataSource come from an XML URL.
This is my method:
private void GetPDF(Stream RDL)
{
Warning[] warnings = null;
string[] streamIds = null;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
string filetype = string.Empty;
ReportViewer RPT = new ReportViewer();
RPT.ProcessingMode = ProcessingMode.Local;
RPT.LocalReport.LoadReportDefinition(RDL);
RPT.LocalReport.Refresh();
byte[] Bytes = RPT.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
using (FileStream PDF = new FileStream("test.PDF", FileMode.Create))
{
PDF.Write(Bytes, 0, Bytes.Length);
}
}
The report works just fine from the ReportBuilder desktop app. As you can see, I removed all the dynamic content (Report URL, Parameters, etc) to simplify and detect the problem source.
On desperation I also tried embedding the XML data in the report.
The error is always the same:
Cannot create a data reader for dataset (the name of the first dataset on the report)
The dataset Query looks like this:
<Query>
<ElementPath IgnoreNamespaces='true'>
Object1 {
Element1,
Element2
}
</ElementPath>
</Query>
Please Help!!
SOLUTION:
I got this solved and I want to share my solution so you don't invest so much time on the same.
The problem was generated by the Report Viewer Control as it has no "Query" capabilities.
Then, my solution was to build a Dataset with the exact data needed in the report.
The XML was downloaded by te C# Class. The data was collected, filtered and sent to the RDL as a Dataset.
The final Method went like this:
private MemoryStream RenderPDFFromXML(Stream RDL, Stream XML)
{
Warning[] warnings = null;
string[] streamIds = null;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
string filetype = string.Empty;
ReportViewer RPT = new ReportViewer();
RPT.ProcessingMode = ProcessingMode.Local;
RPT.LocalReport.LoadReportDefinition(RDL);
DataSet DS = new DataSet();
XML.Position = 0;
DS.ReadXml(XML);
ReportDataSource RDS;
foreach (DataTable DT in DS.Tables)
{
RDS = new ReportDataSource(DT.TableName, DT);
RPT.LocalReport.DataSources.Add(RDS);
}
RPT.LocalReport.Refresh();
byte[] Bytes = RPT.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
return new MemoryStream(Bytes);
}
For me, I was passing wrong dataset name which was mentioned in .rdl file. For example
<DataSet Name="TestAbc"> </DataSet>
from model I was adding
new ReportDataSource("Abc", listOfModel),
You have to pass same name which you mentioned in .rdl file and which you passing as data source Name.
i want to display 7 days of the weeks. weather information
this is api i used to for getting 7 days result of london
http://api.apixu.com/v1/forecast.xml?key=[APIKEY]&q=india&days=7
if i write code in c# below i should be no problem
StringBuilder sb = new StringBuilder();
sb.Append("http://api.apixu.com/v1/forecast.xml?key=[APIKEY]&q=");
sb.Append(txtbox.Text);
sb.Append("&days=");
sb.Append("7");
this is code i written to display on data grid view but no result display
can any one fix the code for me to display 7 days weather information will display on data grid view
XmlReader xmlFile;
xmlFile = XmlReader.Create(sb);
DataSet ds = new DataSet();
ds.ReadXml(xmlFile);
dataGridView1.DataSource = ds.Tables[0];
Just ToString() the StringBuilder:
XmlReader xmlFile;
xmlFile = XmlReader.Create(sb.ToString());
DataSet ds = new DataSet();
ds.ReadXml(xmlFile);
You might want to however checkout HttpClient as consuming a web service with XmlReader.Create feels just plain dirty
https://dotnetfiddle.net/ZSTOhq
We have two xml files and need to find the diff of it. For this we are using XMLDiff library. We are able to get the difference but now wanted to have a UI which shows modified nodes. So used XmlDiffView class. Code is as below
XmlDiffView dv = new XmlDiffView();
//Load the original file again and the diff file.
XmlTextReader orig = new XmlTextReader(oldXML);
XmlTextReader diffGram = new XmlTextReader(diffXML);
dv.Load(orig,
diffGram);
//Wrap the HTML file with necessary html and
//body tags and prepare it before passing it to the GetHtml method.
string tempFile = #"C:\Users\ABC\Desktop\diffView.html";
StreamWriter sw1 = new StreamWriter(tempFile);
sw1.Write("<html><body><table width='100%'>");
dv.GetHtml(sw1);
sw1.Write("</table></body></html>");
sw1.Close();
dv = null;
orig.Close();
diffGram.Close();
From above code, dv.GetHtml(sw1); this statement gives html file which shows all modified and non modified nodes, but we need to get only modified nodes information.
How can we get only modified modes information?
Any hint, reference would be great help.
Thank You!
I am trying to build a dynamic web page with changing controls using an SQL database.
I can't insert in to a sql per control cause that doesn't add up on the SQL tables since I also need the tables and divs. Basically I tried to copy the whole html and putting it in a row but that doesn't seem to work and I can't get it out as pure text. Maybe some suggestions for this?
I am looking in to any Object SQL so I can just insert the whole form as bytes or any other way.
Is there any library for OSQL on C#?(I want to do this server side) Or any tips on how to do this properly?
I was trying to insert the HTML code to SQL for future use but this gave me errors
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
Form1.RenderControl(w);
string s = sw.GetStringBuilder().ToString();
string command = "INSERT INTO `htmltables`(`Company`, `Type`, `HTML`) VALUES ('TestCompany','TestType','" + s + "')";
In any case I'd really want to insert Objects instead of pure HTML cause this will ease my work in the future.
Thank you in advance.
Try to fix your query:
"INSERT INTO `htmltables`(`Company`, `Type`, `HTML`) VALUES
('TestCompany','TestType','" + s + "')"
Try to remove the characters from the string.
"INSERT INTO htmltables(Company, Type, HTML) VALUES ('TestCompany','TestType','" + s +
"')"
and try using Parameters such as:
"INSERT INTO htmltables(Company, Type, HTML) VALUES (#0,#1,#2)", "The Company", "TestType", s
And make the query up.
For me there is only this error.
Adding the divs to the database
This is isn't an issue, the issue might be that the server isn't allowing such characters thinking they might be potential. For this you can try this:
Request.Unvalidated["name"];
This way, the server would get the div or any other HTML markup being inserted.
Basically I tried to copy the whole html and putting it in a row but that doesn't seem to work and I can't get it out as pure text.
It should work when you will use the term I suggested, but wait, you're saying it doesn't seem to work so how can you get the text? Nothing would be provided unless there is some data. Your question is a bit confusing. Sorry for this.
Reference:
http://technet.microsoft.com/en-us/library/aa214012(v=sql.80).aspx
MSDN would be your best buddy in this issue! :)
Your html text may include improper characters for Sql. Safest way is to use parameters.
For Example:
string connectionString = "";
string html = "<div id=\'loremIpsum\'><div/>";
using (SqlCommand command = new SqlConnection(connectionString).CreateCommand())
{
command.CommandText = "insert into YourTable (YourColumn) values(#yourParameter)";
command.Parameters.Add(new SqlParameter("yourParameter", html));
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
finally
{
command.Connection.Close();
}
}
Serialise your class and put the xml object in the database, here is an example of a serialised class and functions for serialisation to and from the object/xml:
VB.net
Imports System.Runtime.Serialization
Imports System.Xml
Imports System.IO
Imports System.Text
Namespace NamespaceGoesHere
<DataContract()> _
Public Class ClassNameGoesHere
'All your properties go here, for example:
<DataMember> Property PropertyName As String = "test"
'Note the use of <DataMember> and <DataContract()>
#Region "Serialisation"
Public Function Serialise() As String
Dim s As New System.IO.MemoryStream
Dim x As New DataContractSerializer(GetType(ClassNameGoesHere))
x.WriteObject(s, Me)
s.Position = 0
Dim sw As New StreamReader(s)
Dim str As String
str = sw.ReadToEnd()
Return str
End Function
Public Shared Function DeSerialise(xmlDocument As String) As ClassNameGoesHere
Dim doc As New XmlDocument
Dim ser As New DataContractSerializer(GetType(ClassNameGoesHere))
Dim stringWriter As New StringWriter()
Dim xmlWriter As New XmlTextWriter(stringWriter)
doc.LoadXml(xmlDocument)
doc.WriteTo(xmlWriter)
Dim stream As New MemoryStream(Encoding.UTF8.GetBytes(stringWriter.ToString()))
stream.Position = 0
Dim reader As XmlDictionaryReader = XmlDictionaryReader.CreateTextReader(stream, New XmlDictionaryReaderQuotas())
Return DirectCast(ser.ReadObject(reader, True), ClassNameGoesHere)
End Function
#End Region
End Class
End Namespace
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Xml;
using System.IO;
using System.Text;
namespace NamespaceGoesHere
{
[DataContract()]
public class ClassNameGoesHere
{
//All your properties go here, for example:
[DataMember()]
public string PropertyName { get; set; }
//Note the use of [DataMember()] and [DataContract()]
#region "Serialisation"
public string Serialise()
{
System.IO.MemoryStream s = new System.IO.MemoryStream();
DataContractSerializer x = new DataContractSerializer(typeof(ClassNameGoesHere));
x.WriteObject(s, this);
s.Position = 0;
StreamReader sw = new StreamReader(s);
string str = null;
str = sw.ReadToEnd();
return str;
}
public static ClassNameGoesHere DeSerialise(string xmlDocument)
{
XmlDocument doc = new XmlDocument();
DataContractSerializer ser = new DataContractSerializer(typeof(ClassNameGoesHere));
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
doc.LoadXml(xmlDocument);
doc.WriteTo(xmlWriter);
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(stringWriter.ToString()));
stream.Position = 0;
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
return (ClassNameGoesHere)ser.ReadObject(reader, true);
}
#endregion
}
}
Once you have created your class you can serialise it into an xml string using the serialise function. Store this in the database (I would use an XML datatype but you can store it as NVARCHAR(MAX).
When returning from the database simply call the deserialise function passing in the string and you'll get your object back again.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Create Excel (.XLS and .XLSX) file from C#
I have some code that generates a zip file that contains multiple CSV files and streams it back to the user (no file is saved on the server). However, I want to create an excel workbook instead (can be traditional xls or Office Open XML xlsx format) with each CSV 'file' being a spreadsheet.
How can I do this, without resorting to Office Automation on the server or a commercial 3rd party component?
You can use OleDB to generate simple tables in Excel files.
Note that you will need to generate a temp file on the server.
Example.
Note that their example is incorrect and needs to use an OleDbConnectionStringBuilder, like this:
OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();
if (isOpenXML)
builder.Provider = "Microsoft.ACE.OLEDB.12.0";
else
builder.Provider = "Microsoft.Jet.OLEDB.4.0";
builder.DataSource = fileName;
builder["Extended Properties"] = "Extended Properties=\"Excel 8.0;HDR=YES;\""
using (var con = new OleDbConnection(builder.ToString())) {
...
}
The XML format for Excel is quite simple and there's absolutely no need to do any automation.
The full reference is up on MSDN: http://msdn.microsoft.com/en-us/library/aa140066(office.10).aspx
Response.ContentType = "application/vnd.ms-excel";
The ContentType property specifies the HTTP content type for the response. If no ContentType is specified, the default is text/HTML.
Get all your data in a DataGrid and then get it from it can be done with:
DataGrid.RenderControl
Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled.
SqlConnection cn = new SqlConnection("yourconnectionstring");
cn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Users", cn);
DataTable dt = new DataTable();
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
dg.RenderControl(hw);
cn.Close();
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
You can write the excel xml by yourself. Here is a nice lib for the task, maybe it is something for you.
// Edit
Link: http://www.carlosag.net/Tools/ExcelXmlWriter/Generator.aspx