C# Pulling RSS LastBuildDate - c#

all.
I am interested in pulling the Last Build Date information from an RSS feed. I will use the information to let the user know when there is a new feed out.
Here is the RSS feed...
<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/"
xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>User's Facebook Notifications</title>
<link>https://www.facebook.com/notifications?id=USERIDHERE</link>
<description>User's Facebook Notifications</description>
<language>en-us</language>
<category domain="Facebook">NotificationSyndicationFeed</category>
<generator>Facebook Syndication</generator>
<docs>http://www.rssboard.org/rss-specification</docs>
<lastBuildDate>Thu, 13 Feb 2014 21:19:52 -0500</lastBuildDate>
<webMaster>webmaster#facebook.com</webMaster>
</channel>
<access:restriction relationship="deny" xmlns:access="http://www.bloglines.com/about/specs/fac-1.0" />
</rss>
On load, the application will pull the initial lastBuildDate and store it in a label then use a timer to compare the label to a newly pulled value every few minutes. For example:
private void frmFacebookRSS(object sender, EventArgs e)
{
getLastBuild();
DateTime now = DateTime.Now;
lblLastBuild.Text = LastBuild;
}
private void tmrUpdate_Tick(object sender, EventArgs e)
{
getLastBuild();
DateTime now = DateTime.Now;
if (lblLastBuild.text != LastBuild)
{
System.Beep // Or whatever desired output
lblLastBuild.Text = LastBuild;
}
I'm just not certain on how to pull the lastBuildDate in the private void getLastBuild(). I'm not great with the whole nodes thing. Any help would be great on this last piece of the puzzle. Thanks!

Use LINQ-to-XML:
from buildDate in xmlData.Descendants("lastBuildDate")
select buildDate.Value
Where xmlData is the rss string you loaded.

Related

How to display XML in a listbox and pass it to a textbox in C#?

I'm struggling to make a basic C# app that gets a number of items from an XML file, shows the "title" node in a listbox, and, when a title is selected, displays the other nodes of the item in a textbox. The textbox is meant to allow the user to edit the XML content and save the changes.
My problem is quite basic I think: The listbox works fine, but the textbox isn't updated when a new title is selected in the listbox. I guess it shouldn't be too complicated, but to me it is - I'm really stuck here.
I'm aware that questions like this one pop up frequently, but most of them seem to me to be imprecise or overly complicated: I'm (obviously) new to C# and really like to keep code as simple and transparent as possible.
My XML sample:
<?xml version='1.0'?>
<book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price>8.99</price>
</book>
<book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
</book>
<book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
<title>The Gorgias</title>
<author>
<name>Plato</name>
</author>
<price>9.99</price>
</book>
</bookstore>
The cs file
private void btnLireXML_Click(object sender, EventArgs e)
{
XmlDocument xDox = new XmlDocument();
xDoc.Load(books.xml);
XmlNodeList lst = xDoc.GetElementsByTagName("title");
foreach (XmlNode n in lst)
{
listBox1.Items.Add(n.InnerText);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = listBox1.SelectedItem.ToString();
}
Here, in the textbox part, I've tried almost everything...
The WFA file contains a button that loads the XML file, a listbox, and a textbox (perhaps it would be better to have a text box for each XML node)
When xml is loaded, put the books in the list.
Suggest to use linq2xml (XElement), as it is a more convenient than the legacy XmlDocument.
private void ButtonLoad_Click(object sender, EventArgs e)
{
var xml = XElement.Load("books.xml");
bookList = xml.Elements("book").ToList();
foreach (var book in bookList)
{
string title = book.Element("title").Value;
listBox.Items.Add(title);
}
}
Where List<XElement> bookList is a form field.
In the event handler retrieve the book from the list by index.
private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
var book = bookList[listBox.SelectedIndex];
textBox.Text =
"Genre: " + book.Attribute("genre").Value + Environment.NewLine +
"Price: " + book.Element("price").Value;
// Put other values to textbox (set Multiline = true)
}
Of course, you can use several textboxes (or labels).
textBoxGenre.Text = "Genre: " + book.Attribute("genre").Value;
textBoxPrice.Text = "Price: " + book.Element("price").Value;
And so on.

C# XDocument - Adding a Value to an existing xml

This is what i am using
private void dir_TextBox_TextChanged(object sender, EventArgs e)
{
string _DIR = dir_TextBox.Text.ToString();dir
XDocument _config = XDocument.Load(#"/ProgramData\app\appConfig.xml");
_config.Root.Element("root").Element("node1").Add(new XElement("value", _DIR));
_config.Save(#"/ProgramData\app\appConfig.xml");
}
I have an xml
<root>
<node1>
<value></value>
</node1>
</root>
and want to add
<root>
<node1>
<value>a string</value>
</node1>
</root>
I have tried several ways to do this but keep getting an error "Additional information: Object reference not set to an instance of an object."
Any help would be appreciated.
Thanks.
_config.Root has already got the "root" element.
And you have to set (update) a new value ("a string") to the existing element, "value" because your xml file already has the "value" element.
private void dir_TextBox_TextChanged(object sender, EventArgs e)
{
XDocument _config = XDocument.Load(#"/ProgramData\app\appConfig.xml");
_config.Root.Element("node1").Element("value").Value = "a string";
_config.Save(#"/ProgramData\app\appConfig.xml");
}

How to read the XML in a text file and append it to RichTextBox

I have the xml in a text file is
<text font='Bamini' color='#ffff80ff' font-size='8'>the </text>
<text font='Microsoft Sans Serif' color='#ff804000' font-size='8'>test </text>
<text font='Microsoft Sans Serif' color='#ff8000ff' font-size='8'>text </text>
<text font='Kal-72' color='#ff0080c0' font-size='8'>sample</text>
I would like to append the content of the text tag to the RichTextBox. i.e.,the content of the 1st text tag (the) will set the font type "Bamini",Co lor is "#ffff80ff" and the size is '8' like that the other tags also
You can use RichTextBox.Rtf to place RTF formatted text into the control for display or to extract the text of the control with the specified RTF formatting defined in the text of the control.
RTF encoding is different from HTML. You cannot do this straight away. I suggest WebBrowser control.
or try this ways from codeproject:
XHTML2RTF
An-extended-RichTextBox-to-save-and-load-quot-HTML
You should use one of the two
Create a valid xml document file in which you could store your text elements ( your current format isn't a valid xml ). For more about xml operations in C# Go here.
Create an app.config file and save / select values from that file. For more on this Go here.
Please try following code:
private void button1_Click(object sender, EventArgs e)
{
var textConfiguration = XDocument.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.xml"));
if (textConfiguration != null)
{
textConfiguration.Descendants("Configuration").Descendants("text").ToList().ForEach(text =>
{
font = text.Attribute("font").Value;
color = text.Attribute("color").Value;
fontsize = text.Attribute("font-size").Value;
textToAppend = text.Value;
});
}
richTextBox1.SelectionColor = Color.FromName(color);
richTextBox1.SelectionFont = new Font(font, int.Parse(fontsize), FontStyle.Regular);
richTextBox1.AppendText(textToAppend);
}
The XML file is like this:
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<text font='Verdana' color='Green' font-size='8'>The Formatted Text</text>
</Configuration>
I Hope this will give you an idea.
If you have more then one text block, you can modify the code as below:
private void button1_Click(object sender, EventArgs e)
{
var textConfiguration = XDocument.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.xml"));
if (textConfiguration != null)
{
textConfiguration.Descendants("Configuration").Descendants("text").ToList().ForEach(text =>
{
font = text.Attribute("font").Value;
color = text.Attribute("color").Value;
fontsize = text.Attribute("font-size").Value;
textToAppend = text.Value;
richTextBox1.SelectionColor = Color.FromName(color);
richTextBox1.SelectionFont = new Font(font, int.Parse(fontsize), FontStyle.Regular);
richTextBox1.AppendText(textToAppend);
});
}
}
And the XML will be like this
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<text font='Verdana' color='Green' font-size='8'>The </text>
<text font='Verdana' color='Red' font-size='8'>Formatted </text>
<text font='Verdana' color='Blue' font-size='8'>Text</text>
</Configuration>
I have again modified code and now you can have Hex coloe code in your XML file.
Replace
richTextBox1.SelectionColor = Color.FromName(color);
by
System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml(color);
richTextBox1.SelectionColor = col;
and replace
color='Green'
by
color='#ffff80ff'

FirstOrDefault not taking argument

I put reading barcode in separate method which reads the barcode and put it in a textbox named barcode. and created a button that will load data coresponding to that barcode , but facing problem
private void Load_Click(object sender, RoutedEventArgs e)
{
var str = #"<Books xmlns=""""> <book Barcode=""780672318863""><Serial>11</Serial>
<name>abc</name> <detail>Fantasy</detail></book>
<book Barcode=""780672318864""><Serial>12</Serial>
<name>abc</name><detail>Fantasy1</detail></book></Books>";
var strBarcode = barcode.Text;
MessageBox.Show(strBarCode);
XDocument docX = XDocument.Parse(str);
var s = docX.Descendants("book").FirstOrDefault(a => a.Attribute("Barcode").Value == strBarcode);
spnl.DataContext = s;
}
now Messagebox says strBarCode has correct value but it is not showing up in program and
s value is coming out to be null
on other hand if i put directly "780672318863" in place of strBarcode it is showing value correctly
can anyone tell me where i am going wrong ?
Not reproducable.
I ran your code with docX.Descendants("book")... and it produces the correct element.
You could try
string strBarcode = barcode.Text.Trim();
but for the rest you will just have to look around in the debugger.

How to insert data into an existing xml file in asp.net?

I'm using Visual Web Developer 2008 Express Edition and I need your assistance since I'm new to it. I'm trying to insert or write a data to my xml file so that I can display it into my xml control. Now, what I'm trying to do here is everytime the user enter a message into the textbox he has an option to save it so if he clicks the command button I want to save the text message from the textbox into any elements of my xml file. Let say, I want to insert it in the element of my xml file. How do I do it using C# or VB.Net codes? I have my xml file below and my C# code but the c# code doesn't work for me. I need the code for that either in c# or vb.net, either way will work for me.
Thank you very much and I greatly appreciate any help that could be shared.
myxmlfile.xml
<?xml version="1.0" encoding="utf-8" ?>
<comments>
<comment>
Your Comments Here: Please post your comments now. Thank you.
</comment>
<comment2>
Note: Please do not post any profane languages.
</comment2>
<comment3>
I don't like their service. It's too lousy.
</comment3>
<comment4>
Always be alert on your duty. Don't be tardy enough to waste your time.
</comment4>
</comments>
code
protected void Button1_Click(object sender, EventArgs e)
{
System.Xml.Linq.XDocument mydoc =
new System.Xml.Linq.XDocument(
new System.Xml.Linq.XDeclaration("1.0", "UTF-8", "yes"),
new System.Xml.Linq.XElement("comment",
new System.Xml.Linq.XComment(TextBox1.Text)));
mydoc.Save("myxmlfile.xml",System.Xml.Linq.SaveOptions .None);
}
#Joseph LeBrech and #AVD --Thank you very much for your reply. That code would add a new root element in myxmlfile so the problem is that the new root element is not showing on my xml control when the page is reloaded because the new root element is not included on my xslt file to show the myxmlfile on the xml control. I don't want to add a new root element on myxmlfile. I just want to insert the messages entered from the textbox into the existing element of myxmlfile which is the element so that it can be shown on the xml control where i intend to display the myxmlfile. I hope you can modify the code for me again. Thank you very for your help. I greatly appreciated it.
You have to specify the absolute file path using MapPath() to save the XML document and don't increment tag name like comment1,comment2.. etc.
Take a look at code-snippet:
protected void Button1_Click(object sender, EventArgs e)
{
string file = MapPath("~/comments.xml");
XDocument doc;
//Verify whether a file is exists or not
if (!System.IO.File.Exists(file))
{
doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
new System.Xml.Linq.XElement("comments"));
}
else
{
doc = XDocument.Load(file);
}
XElement ele = new XElement("comment",TextBox1.Text);
doc.Root.Add(ele);
doc.Save(file);
}
EDIT: If you want to insert <comment> tag into existing xml document then no need to create XDocument. Just load the existing document and add a new element at the root.
protected void Button1_Click(object sender, EventArgs e)
{
string file = MapPath("~/myxmlfile.xml");
XDocument doc = XDocument.Load(file);
XElement ele = new XElement("comment",TextBox1.Text);
doc.Root.Add(ele);
doc.Save(file);
}
To add another <comment> tag inside <comment>:
XElement ele = new XElement("comment",TextBox1.Text);
doc.Root.Element("comment").Add(ele);
doc.Save(file);
To replace the text value of <comment> tag:
doc.Root.Element("comment").Value = TextBox1.Text;
//doc.Root.Element("comment").Value += TextBox1.Text; //append text
doc.Save(file);
XML document :
<?xml version="1.0" encoding="utf-8" ?>
<comments> <!-- Root Node -->
<comment>First Child</comment>
<comment> <!-- Second Child -->
<comment>Nested</comment>
</comment>
</comments>
myDoc.Element("comments").Add(new xElement("comment5") { Value = "put the value in here"});
Design the page like this.In button click event write the following
code
protected void btnInsert_Click(object sender, EventArgs e)
{
System.Xml.XmlDocument myXml = new System.Xml.XmlDocument();
myXml.Load(Server.MapPath("InsertData.xml"));
System.Xml.XmlNode xmlNode = myXml.DocumentElement.FirstChild;
System.Xml.XmlElement xmlElement = myXml.CreateElement("entry");
xmlElement.SetAttribute("Name", Server.HtmlEncode(txtname.Text));
xmlElement.SetAttribute("Location", Server.HtmlEncode(txtlocation.Text));
xmlElement.SetAttribute("Email", Server.HtmlEncode(txtemail.Text));
xmlElement.SetAttribute("Gender", Server.HtmlEncode(ddlgender.SelectedItem.Text));
myXml.DocumentElement.InsertBefore(xmlElement,xmlNode);
myXml.Save(Server.MapPath("InsertData.xml"));
BindData();
lbldisplay.Text = "Record inserted into XML file successfully";
txtname.Text = "";
txtlocation.Text = "";
txtemail.Text = "";
}
private void BindData()
{
XmlTextReader xmlReader = new XmlTextReader(Server.MapPath("InsertData.xml"));
xmlReader.Close();
}
and also put events tag in xml file.
Now run the application and check the output

Categories

Resources