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
Related
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!
Any body say how can we convert a data-table to XML format.
I tried the below one but is is not saving or exporting the data
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<DLReports.FCBuySellDetail>));
using (StreamWriter wr = new StreamWriter("customers.xml"))
{
xs.Serialize(wr, DetailReportFCBuySell1);
}
DataTable dtSample = new DataTable();
dtSample.WriteXml(fileName); //Pass the path of the XML file.
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.
How do I consume my WordPress blog's RSS feed to display my latest blog posts on my homepage? I ran into the following piece of code to do this:
Function GetRSSFeed(strURL as String) as DataTable
'Get the XML data
Dim reader as XmlTextReader = New XmlTextReader(strURL)
'return a new DataSet
Dim ds as DataSet = New DataSet()
ds.ReadXml(reader)
Return ds.Tables(2)
End Function
But it errors out at this line: 'ds.ReadXml(reader)' with the following error:
A column named 'comments' already belongs to this DataTable.
Perhaps it doesn't work since this code is from 2003? Does anyone have a working code sample? Many thanks in advance!
You can use LINQ to XML to read a WordPress RSS feed.
First get the feed. Make a Uri instance out of it.
var rssFeed = new Uri("https://github.com/geersch/feed/");
Then perform a GET request.
var request = (HttpWebRequest) WebRequest.Create(rssFeed);
request.Method = "GET";
var response = (HttpWebResponse) request.GetResponse();
Get the response stream and read it to download the contents of the feed.
using (var reader = new StreamReader(response.GetResponseStream()))
{
var feedContents = reader.ReadToEnd();
//...
}
Still within the above using statement use LINQ to XML to parse the downloaded content and extract the information you need.
var document = XDocument.Parse(feedContents);
var posts = (from p in document.Descendants("item")
select new
{
Title = p.Element("title").Value,
Link = p.Element("link").Value,
Comments = p.Element("comments").Value,
PubDate = DateTime.Parse(p.Element("pubDate").Value)
}).ToList();
Now you can iterate over the results.
foreach(var post in posts)
{
Console.WriteLine(post.Title);
Console.WriteLine(post.Link);
Console.WriteLine(post.Comments);
Console.WriteLine(post.PubDate);
}
Here I just used an anonymous type to capture the output in, but feel free to create your own BlogPost class or something similar which you can use in the LINQ query.
I'm used to C#, so that's why I've used it in my reply. But you can easily convert it. There are some online converters which you can use.
Regarding your issue with the DataSet (which I personally would not use to implement this), it is caused by an item (blog post) having nodes with the same name.
For example:
<comments>...</comments>
<slash:comments>5</slash:comments>
Sure the second one has a different namespace (slash), but DataSet's ReadXml(...) method does not care about namespaces. It tries to create a second column named "comments". That is why you get the exception.
You can still use a DataSet / DataTable if you want to. Just extract the data from the feed using LINQ to XML as shown above.
Then create a DataSet and add a new table to it.
var dataSet = new DataSet();
var blog = new DataTable("Blog");
blog.Columns.Add("Title", typeof(string));
blog.Columns.Add("Link", typeof(string));
blog.Columns.Add("Comments", typeof(string));
dataSet.Tables.Add(blog);
Iterate over the extracted data and add it to the DataTable:
foreach (var post in posts)
{
var newRow = blog.NewRow();
newRow["Title"] = post.Title;
newRow["Link"] = post.Link;
newRow["Comments"] = post.Comments;
blog.Rows.Add(newRow);
}
Voila, we've now fixed your issue by no longer relying on the DataSet's ReadXml(...) method. Download the feed, extract the data you are interested in and persist it.
I would start in the System.ServiceModel.Syndication namespace, there are classes to directly manipulate RSS feeds. In particular, this looks promising:
XmlReader reader = XmlReader.Create("http://your.uri.here/feed.xml");
SyndicationFeed feed = SyndicationFeed.Load(reader);
Then explore the SyndicationFeed class, in particular the Items collection should contain the RSS entries.
I'd start off with the built in classes for RSS/Atom: SyndicationFeed
using (XmlReader reader = XmlReader.Create(url))
{
return SyndicationFeed.Load(reader);
}
This is simply #Christophe Geers's great solution converted to VB, as a function:
Protected Function getWordPressFeed(ByVal strUrl As String) As DataTable
Dim rssFeed = New Uri(strUrl)
Dim request = DirectCast(WebRequest.Create(rssFeed), HttpWebRequest)
request.Method = "GET"
Dim response = DirectCast(request.GetResponse(), HttpWebResponse)
Dim feedContents As String
Using reader = New StreamReader(response.GetResponseStream())
feedContents = reader.ReadToEnd()
End Using
Dim document = XDocument.Parse(feedContents)
Static Dim dcNamespace As XNamespace
dcNamespace = "http://purl.org/dc/elements/1.1/"
Dim posts = (From p In document.Descendants("item") Select New With { _
Key .Title = p.Element("title").Value, _
Key .Link = p.Element("link").Value, _
Key .Author = p.Element(dcNamespace + "creator").Value, _
Key .Description = p.Element("description").Value, _
Key .PubDate = DateTime.Parse(p.Element("pubDate").Value) _
}).ToList()
Dim dataSet = New DataSet()
Dim blog = New DataTable("Blog")
blog.Columns.Add("Title", GetType(String))
blog.Columns.Add("Link", GetType(String))
blog.Columns.Add("Description", GetType(String))
blog.Columns.Add("Author", GetType(String))
blog.Columns.Add("PubDate", GetType(DateTime))
dataSet.Tables.Add(blog)
For Each post In posts
Dim newRow = blog.NewRow()
newRow("Title") = post.Title
newRow("Link") = post.Link
newRow("Description") = post.Description
newRow("Author") = post.Author
newRow("PubDate") = post.PubDate
blog.Rows.Add(newRow)
Next
Return blog
End Function
This is what I use for my wordpress feed reader.
private async void ReadFeed() {
var rssFeed = new Uri("http://truestrengthmd.com/category/blog/feed");
var request = (HttpWebRequest)WebRequest.Create(rssFeed);
request.Method = "GET";
var _response = await request.GetResponseAsync();
var response = (HttpWebResponse)_response;
using (var reader = new StreamReader(response.GetResponseStream()))
{
var feedContents = reader.ReadToEnd();
var document = XDocument.Parse(feedContents);
var posts = (from p in document.Descendants("item")
select new
{
Title = p.Element("title").Value
}).ToList();
foreach (var post in posts)
{
Debug.WriteLine(post.Title);
}
}
}
You can use my Library for this: wprssapi.marcogriep.de
Just a few lines of code. Very easy to do:
//Get an Instance of Wordpress Controller (Singleton)
WordPressFeedController wp = WordPressFeedController.Instance;
//Load all the RSS Articles
wp.LoadRSS("http://www.its-all-about.de/rss");
//Get the Newest Article (Check Docs for other functions)
var rssItem = wp.GetNewestItem();
this.label1.Text = rssItem.Title;
//Text Only, Remove all the HTML Tags - Limit too 300 Chars
this.richTextBox1.Text = wp.RemoveHTMLFromText(rssItem.Summary.Substring(0, 300)) + "...";
//Open RSS Article on Button Click
this.button1.Click += (s, e) => {
Process.Start(rssItem.Id);
};
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