How to read dynamic rss feed - asp.net

In my application i will have dynamic rss feed url saved by users. so i want to know that how can i read that xml which will be returned by rss feed. what will be the structure of that xml ? I have reviewed some feed url and i noticed that most of them have title and description tags but i am not sure to this. if i get these two tags then i will parse xml but if they are not always available then how can i parse xml in that case.
these two contains title and description tag
http://rss.news.yahoo.com/rss/entertainment
http://xml.weather.yahoo.com/forecastrss?p=USCA1116

At first you need to read a XML file for that I recommend you to use XPath or Linq to XML, and as you already said there are three main elements that make up a feed; "title", "link" and "description".
Not a very long time ago I wrote a code to do that, I hope this works for you.
I created this two entities.
public class RssFeed
{
public string Title { get; set; }
public string Link { get; set; }
public string Description { get; set; }
public string PubDate { get; set; }
public string Language { get; set; }
public ObservableCollection<RssItem> RssItems { get; set; }
}
public class RssItem
{
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
}
Then on this method I read every element from the XML file by using Linq to XML
private static void ReadFeeds()
{
string uri = #"http://news.yahoo.com/rss/entertainment";
WebClient client = new WebClient();
client.DownloadStringAsync(new Uri(uri, UriKind.Absolute));
client.DownloadStringCompleted += (s, a) =>
{
if (a.Error == null && !a.Cancelled)
{
var rssReader = XDocument.Parse(a.Result);
var feed = (from rssFeed in rssReader.Descendants("channel")
select new RssFeed()
{
Title = null != rssFeed.Descendants("title").FirstOrDefault() ?
rssFeed.Descendants("title").First().Value : string.Empty,
Link = null != rssFeed.Descendants("link").FirstOrDefault() ?
rssFeed.Descendants("link").First().Value : string.Empty,
Description = null != rssFeed.Descendants("description").FirstOrDefault() ?
rssFeed.Descendants("description").First().Value : string.Empty,
PubDate = null != rssFeed.Descendants("pubDate").FirstOrDefault() ?
rssFeed.Descendants("pubDate").First().Value : string.Empty,
Language = null != rssFeed.Descendants("language").FirstOrDefault() ?
rssFeed.Descendants("language").First().Value : string.Empty
}).Single();
var rssFeeds = (from rssItems in rssReader.Descendants("item")
select new RssItem()
{
Title = null != rssItems.Descendants("title").FirstOrDefault() ?
rssItems.Descendants("title").First().Value : string.Empty,
Link = null != rssItems.Descendants("link").FirstOrDefault() ?
rssItems.Descendants("link").First().Value : string.Empty,
Description = null != rssItems.Descendants("description").FirstOrDefault() ?
rssItems.Descendants("description").First().Value : string.Empty,
}).ToList();
feed.RssItems = new ObservableCollection<RssItem>(rssFeeds);
}
};
}
And finally you have your feed to be displayed wherever you want.

Related

Passing Values from Page to Another page in List

this is mine model
public class QMSRejection
{
public string Date { get; set; }
public string Grade { get; set; }
public string Resd { get; set; }
public string Remarks { get; set; }
}
this is mine firstpage.xaml.cs from where I am passing a data to another page !
List<QMSRejection> DataToSave = new List<QMSRejection>();
var rej = new QMSRejection();
rej.Date = DateTime.Now.ToShortDateString();
rej.Grade = GradeID;
rej.Resd = ResdId;
DataToSave.Add(rej);
await Navigation.PushAsync(new Rejection2ndForm(DataToSave));
now on the second page I am receiving it, data is coming everything working fine !
public partial class Page2 : ContentPage
{
List<QMSRejection> DataToSave = new List<QMSRejection>();
public Rejection2ndForm(List<QMSRejection> models)
{
InitializeComponent ();
DataToSave = models;
}
}
var rej = new QMSRejection();
rej.Remarks = ent3.Text.ToString();
DataToSave.add(rej);
I have a fields Remarks which I am trying to add to existing data coming from page 1.But these lines are creating another IEnumerable in the datatoSave List and remarks field not getting added to previous data ! What should I do in place of these lines to do ?
As I have to add remarks field through page2.xaml.cs !
this creates a new QMSRejection object and adds it to your list
var rej = new QMSRejection();
rej.Remarks = ent3.Text.ToString();
DataToSave.add(rej);
if you instead want to modify an existing QMSRejection object
// [0] means the first object in the list
DataToSave[0].Remarks = ent3.Text.ToString();

How to separate JSON Data In ASP.NET Console Application?

I Create a one web API. its main aim is a request to another server and get the response from that server.
I successfully get the response for a particular server.
I get the response(its a JSON Format) is below.
{
"id": "test#gmail.com",
"active": 1,
"is_logged": true,
"token": "hsja3t56yJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3RAZHZlby5jb20iLCJwYXNzd29yZCI6InRlc3QyMDE4KyIsImV4cGlyZU9uIjoiMjAxOS0wNi0yMVQwNTozNzowOC4xODhaIn0.3wgGeL_HvcoEJJeEF7tj8jeXk2uIKpOoi9ewmK5yhteh",
"status": "OK",
"usertype": "TestUser",
"msg": "Login Successfull."
}
I try to separate using split function
string[] sep = response.Split(',');
foreach (string any in sep)
Console.WriteLine(any);
//string[] colon = sep[0].Split(':');
string[][] colon = sep.Select(x => x.Split(':')).ToArray();
//int count = colon.Count();
for (int i = 0; i <= colon.Length; i++)
{
Console.WriteLine(colon[i][0]);
Console.WriteLine(colon[i][1]);
}
Any other way to separate the response? I also use all the field in some other purpose.
Create a Class based on your response property:
public class UserData
{
public string id { get; set; }
public int active { get; set; }
public bool is_logged { get; set; }
public string token { get; set; }
public string status { get; set; }
public string usertype { get; set; }
public string msg { get; set; }
}
On reading the response data, use JsonConvert.DeserializeObject
string response = "{\"id\":\"test #gmail.com\",\"active\":1,\"is_logged\":true,\"token\":\"hsja3t56yJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3RAZHZlby5jb20iLCJwYXNzd29yZCI6InRlc3QyMDE4KyIsImV4cGlyZU9uIjoiMjAxOS0wNi0yMVQwNTozNzowOC4xODhaIn0.3wgGeL_HvcoEJJeEF7tj8jeXk2uIKpOoi9ewmK5yhteh\",\"status\":\"OK\",\"usertype\":\"TestUser\",\"msg\":\"Login Successfull.\"}";
var responseData = JsonConvert.DeserializeObject<UserData>(response);
//here the print in JSON Data
Console.WriteLine("id : " + responseData.id);
Console.WriteLine("active : " + responseData.active);
Console.WriteLine("is_logged : " + responseData.is_logged);
Console.WriteLine("token : " + responseData.token);
Console.WriteLine("status : " + responseData.status);
Console.WriteLine("usertype : " + responseData.usertype);
Console.WriteLine("msg : " + responseData.msg);
use Newtonsoft.json.dll by adding the NuGet package,
Then convert the response to json object
JObject jo = JObject.Parse(searchCondition);
foreach (JToken child in jo.Children()) {
var prop = child as JProperty;
if (prop.Value != null && !string.IsNullOrEmpty(prop.Value.ToString())) {
string name=prop.Name;
string value = prop.Value;
//You can now do whatever with the values like put in a list of object
}
}
This is My own example to get the properties from JSON string, you can use this.
But first, you need to install this package:-> Newtonsoft.Json.Linq to access JObject
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string jsonString = "{\"firstname\":\"Alex Wu\",\"lastname\":\"type\"}";
JObject jObject = JObject.Parse(jsonString);
string firstname = (string)jObject.SelectToken("firstname");
string lastname = (string)
Console.WriteLine("{0}", firstname);
Console.ReadLine();
}
}

Object value is null after deserialization (Xamarin with SQLite)

for an internship project I'm developping an app with Xamarin that will allow users to scan barcodes and create sheets of labels and purchases.
To prevent the scanned codes from being lost in case of crash etc, I've implemented SQLite to create a local backup that we could restore.
The structure is as follows : a ListOfLabelLines contains several LabelLine which each contain a Product and different other informations (such as packaging, quantity etc).
ListOfLabelLines.cs :
[Table("ListOfLabelLines")] // Indique le nom de la table qui sera générée par SQLite
public class ListOfLabelLines : BaseItem
{
private string _name { get; set; }
[TextBlob("LabelLinesBlob")]
public ObservableCollection<LabelLine> lines { get; set; }
[TextBlob("ListBlob")]
public List<String> TestList { get; set; }
public string LabelLinesBlob { get; set; } // serialized LabelLines
public string ListBlob { get; set; } // serialized TestList
public ListOfLabelLines()
{
}
public ListOfLabelLines(string name)
{
this._name = name;
lines = new ObservableCollection<LabelLine>();
TestList = new List<String>();
TestList.Add("Test1");
TestList.Add("Test2");
}
public string Name
{
get { return _name; }
set
{
_name = value;
}
}
}
}
These objects ListOfLabelLines contain an ObservableCollection<LabelLine> which I'm serializing by using the TextBlob property from SQLite-net-extensions.
However, when I retrieve the ListOfLabelLines I've stored, the ObservableCollection appears as null :
Example of null collections
Here are the methods I use to store the objects in SQlite :
public void SaveListOfLabelLines(ListOfLabelLines ShelfLabelInstance)
{
var query = from label in database.Table<ListOfLabelLines>()
where label.Name == ShelfLabelInstance.Name
select label;
var res = query.FirstOrDefault();
if (res != null)
{
database.UpdateWithChildren(ShelfLabelInstance);
Console.WriteLine("Label " + ShelfLabelInstance.Name + " updated");
}
else
{
database.InsertWithChildren(ShelfLabelInstance);
Console.WriteLine("Label " + ShelfLabelInstance.Name + " created");
}
}
and to retrieve them :
public void CheckProductsInLabelLine(string n)
{
var query = from LOLL in database.Table<ListOfLabelLines>()
where LOLL.Name == n
select LOLL;
ListOfLabelLines res = query.FirstOrDefault();
The string property linked to the TextBlob, however, contains the JSON object I need.
I thought the ObservableCollection would be obtainable when getting the object in DB since TextBlob is supposed to serialize AND deserialize.
Could anybody help ?
Thanks a lot !

How to show the JSON data in asp.net web form

I am Beginner at Asp.net so can anyone plz help me to show the data provided in the below shown JSON Api in Asp.net Step by Step.It be of great help if this is answered.
http://fantasy.premierleague.com/web/api/elements/180/
A good way to use Json in C# is with Json.NET
JSON.NET - Official site will help you work with it.
Example to use it
public class User {
public User(string json) {
JObject jObject = JObject.Parse(json);
JToken jUser = jObject["user"];
name = (string) jUser["name"];
teamname = (string) jUser["teamname"];
email = (string) jUser["email"];
players = jUser["players"].ToArray();
}
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
// Use
private void Run() {
string json = #"{""user"":{""name"":""asdf"",
""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
User user = new User(json);
Console.WriteLine("Name : " + user.name);
Console.WriteLine("Teamname : " + user.teamname);
Console.WriteLine("Email : " + user.email);
Console.WriteLine("Players:");
foreach (var player in user.players)
Console.WriteLine(player);
}

How to consume a RSS feed and read the dc:creator element

I am trying to get this to work
I am using this code and it works fine by itself, but now I am trying to get the following element to be read: dc:creator and are not able to.
class file:
public class RSSItem
{
XNamespace dc="http://purl.org/dc/elements/1.1/";
public string Title { get; set; }
public string Description { get; set; }
public string PubDate { get; set; }
public string Link { get; set; }
public string strGuid { get; set; }
public string Author { get; set; }
public string Dc_creator { get; set; }
// Next we’ll modify the constructor. First add a parameter list to the constructor:
public RSSItem(string title, string description, string link, string guid,
string pubDate, string (dc:creator) //<-- not working but what to use instead)
{
// This constructor will be used to parse the RSS xml. Add the following code to the constructor:
Title = title;
Description = description;
Link = link;
strGuid = guid;
PubDate = pubDate;
Dc_creator = dc:creator; <-- not working but what to use instead
Obviously this does not work:
string (dc:creator)) in the constructor
page.cshtml:
<div>
#{
XNamespace dc = XNamespace.Get("http://purl.org/dc/elements/1.1/");
XDocument rss = XDocument.Load("http://rss.xml");
var items = from elem in rss.Elements("rss").Elements("channel").Elements("item")
select elem;
foreach (var item in items)
{
RSSItem rssItem = new RSSItem(
item.Element("title").Value,
item.Element("link").Value,
item.Element("guid").Value,
item.Element("description").Value,
//item.Element("author").Value,
item.Element("pubDate").Value,
item.Element(dc + "creator").Value
);
<span class="rssStyle">
<div>
<b>#rssItem.Title</b>
</div>
etc etc
So how do I manage to have the class constructor read the dc:creator element?
Not the exact solution, but I had done this using XmlDocument. You will have to modify this according to your RssItem, I had similar object
XmlDocument doc = new XmlDocument();
doc.LoadXml(rss);
//Get Channel Node
XmlNode channelNode = doc.SelectSingleNode("rss/channel");
if (channelNode != null) {
//Add NameSpace
XmlNamespaceManager nameSpace = new XmlNamespaceManager(doc.NameTable);
nameSpace.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
nameSpace.AddNamespace("slash", "http://purl.org/rss/1.0/modules/slash/");
nameSpace.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
//Parse each item
foreach (XmlNode itemNode in channelNode.SelectNodes("item")) {
RssFeed rssItem = new RssFeed();
rssItem.Guid = itemNode.SelectSingleNode("guid").InnerText;
rssItem.Title = itemNode.SelectSingleNode("title").InnerText;
rssItem.CreatedBy = itemNode.SelectSingleNode("dc:creator", nameSpace).InnerText;
rssItem.Url = itemNode.SelectSingleNode("link").InnerText;
rssItem.PubDate = DateTime.Parse(itemNode.SelectSingleNode("pubDate").InnerText);
rssItem.CommentCount = itemNode.SelectSingleNode("slash:comments", nameSpace).InnerText;
rssItem.Description = itemNode.SelectSingleNode("content:encoded", nameSpace).InnerText;
}
}

Resources