How to get output of http request in JSON file? - c#

I am making a http get request to a url and I am able to get data from that web page but I am not able to store it in JSON format and also not able to interpret data and get the required data.I am using ASP.NET and C# for it.
This is code for my CS file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace httprequest_web
{
public partial class req : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string baseu = "http://railenquiry.in/runningstatus/";
string url = string.Concat(baseu, TextBox1.Text);
var request = WebRequest.Create(url);
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
request.ContentType = "application/json; charset=utf-8";
text = sr.ReadToEnd();
}
Label1.Text = text;
}
catch
{
Label1.Text = "No Data Found";
}
}
}
}
and screenshot of output I am receiving is:
I want to take output in a well structured JSON file and only want name of station, time of arrival and time of departure in it. Please tell me how to do it?

Take a look at this project : HtmlAgilityPack But you need to ask the owner of the website before using his data

The URL you're requesting is just a normal web page, it doesn't return JSON.
You'll need to scrape the response, in order to do what you want.
Take a look at this question for examples using HtmlAgilityPack:
Parsing HTML Table in C#

Related

C# How to upload any file to a fileuploader?

I need upload my file to "https://file.io" and i tried this:
`private void buttonInput_Click(object sender, EventArgs e)
{
using (WebClient client = new WebClient())
{
var resStr = client.UploadFile("https://file.io", #"C:\data\test.txt");
var jObjResult = JObject.Parse(Encoding.UTF8.GetString(resStr));
var linkToFile = jObjResult["link"];
}
}`
It does upload target txt file to url.
But im taking that error:
Severity Code Description Project File Line Hide Status
Error CS01 'JObject' scope valid03
How to Fix it?
Btw im using them:
using System;
using System.Net;
using System.Text;
using System.Collections.Generic;

Perform a search on google and retrieve results on second page

I am using SharpDevelop platform and I want to do perform a google search for an expression, then generate a list of all web addresses in the first page, another list on the second page, etc. Using some sample code I found, I can retrieve results from the first page. How can I modify the code to get the results on the second page?
Maybe there are better methods than what I found, for example using google API?
Here is the code:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
using System.Collections.Specialized;
namespace GoogleSearch
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
void Button1Click(object sender, EventArgs e)
{
string uriString = "http://www.google.com/search";
string keywordString = "search expression";
WebClient webClient = new WebClient();
NameValueCollection nameValueCollection = new NameValueCollection();
nameValueCollection.Add("q", keywordString);
webClient.QueryString.Add(nameValueCollection);
textBox1.Text = webClient.DownloadString(uriString);
}
}
}

C# adding double quotes to start and end of JSON string results in server decoding error

I am writing a c# mechanism to upload a file to a Rails server, using Json.
Before getting to the file part, i am just trying to post to the server, and seem to be having some problems with the json string that is arriving at the server..
What might I be doing wrong ? I already tried two different ways of serializing the string, and even loading an already serialized string...
I wonder if it has anything to do with the double quotes both at beginning and end of the string apparently being sent to server, and how to remove them from the request (without the surrounding quotes and using RestClient from WizTools.org, it all goes fine...) :
MultiJson::DecodeError (757: unexpected token at '"{\"receipt\":{\"total\":100.0,\"tag_number\":\"xxxxx\",\"ispaperduplicate\":true},\"machine\":{\"serial_number\":\"111111\",\"safe_token\":\"1Y321a\"}}"')
My c# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RestSharp;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
namespace RonRestClient
{
class templateRequest
{
public Receipt receipt;
public class Receipt
{
public float total;
public String tag_number;
public bool ispaperduplicate = true;
public Receipt(float total, String tagnr)
{
this.total = total;
this.tag_number = tagnr;
}
};
public Machine machine;
public class Machine
{
public String serial_number;
public String safe_token;
public Machine(String machinenr, String safe_token)
{
this.serial_number = machinenr;
this.safe_token = safe_token;
}
};
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\file.pdf";
string tagnr = "p94tt7w";
string machinenr = "2803433";
string safe_token = "123";
float total = 100;
templateRequest req = new templateRequest();
req.receipt = new templateRequest.Receipt(total, tagnr);
req.machine = new templateRequest.Machine(machinenr, safe_token);
//string json_body = JsonConvert.SerializeObject(req);
//string json_body = new JavaScriptSerializer().Serialize(req);
string json_body = #"{""receipt"" : {""total"":"+total+#", ""tag_number"":"""+tagnr+#""",""ispaperduplicate"":true},""machine"":{""serial_number"": """+machinenr+#""", ""safe_token"": """+safe_token+#"""}}";
var client = new RestClient("http://localhost:3000");
var request = new RestRequest("/receipts",Method.POST);
//set request Body
request.AddHeader("Content-type", "application/json");
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
request.AddBody(json_body);
//request.AddParameter("text/json", json_body, ParameterType.RequestBody);
// easily add HTTP Headers
// add files to upload (works with compatible verbs)
//request.AddFile("receipt/receipt_file",path);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
if(response.ErrorMessage !="") content += response.ErrorMessage;
response_box.Text = content;
}
}
}
The problem is that the RestRequest.AddBody (source code) method actually presupposes that the content is not serialized to the correct format.
Meaning that it thinks that you are trying to pass the .NET string as a JSON string, instead of recognizing that you actually want to pass that string as a JSON object.
However, that means that you are actually doing too much work, by serializing the object to JSON yourself:
Replace line
request.AddBody(json_body);
with:
request.AddBody(req);
You can control the way that the serialization to JSON is done with the RestRequest.JsonSerializer property.
If you absolutely want to hold a JSON string, then I guess you might want to write:
request.AddParameter("application/json", json_body, ParameterType.RequestBody);
(I see that you have a line which is commented that practically does that - why did you comment it?)

Rss Reader in visual C# express edition

Hi I am trying to create a RSS reader in visual C# express. I need to read the rss feed into a text box when the form loads. I have never worked with RSS feeds before and all the examples I have come across are done in visual studio and it seems that I cant use this:
(XmlReader reader = XmlReader.Create(Url))
This is what I have got so far. It doesn't work.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var s = RssReader.Read("http://ph.news.yahoo.com/rss/philippines");
textBox1.Text = s.ToString();
}
public class RssNews
{
public string Title;
public string PublicationDate;
public string Description;
}
public class RssReader
{
public static List<RssNews> Read(string url)
{
var webResponse = WebRequest.Create(url).GetResponse();
if (webResponse == null)
return null;
var ds = new DataSet();
ds.ReadXml(webResponse.GetResponseStream());
var news = (from row in ds.Tables["item"].AsEnumerable()
select new RssNews
{
Title = row.Field<string>("title"),
PublicationDate = row.Field<string>("pubDate"),
Description = row.Field<string>("description")
}).ToList();
return news;
}
}
I am not sure what I should do. Please help.
Well your code is working as expected, since you are returning a List of RSSNews items, but you are assigning it to the textbox in a wrong way. Doing textBox1.Text = s.ToString(); will give System.Collections.Generic.List.... as a result.
Your method is reading RssNews items from the dataset and return around 23 items against the feed. You need to iterate through these items and display its text in the textbox, or better if you may use GridView or similar control to show these results.
You may try the following code in your Main method:
var s = RssReader.Read("http://ph.news.yahoo.com/rss/philippines");
StringBuilder sb = new StringBuilder();
foreach (RssNews rs in s)
{
sb.AppendLine(rs.Title);
sb.AppendLine(rs.PublicationDate);
sb.AppendLine(rs.Description);
}
textBox1.Text = sb.ToString();
This will create a string for each item of RssNews and will display the result in textBox1.

eBay Finding API .NET SDK 'findItemsAdvanced' returns null response

I'm trying to use the eBay Finding API to send an advanced search request and return the results. I have included my code below.
For some reason when I get to the following line:
FindItemsAdvancedResponse response = service.findItemsAdvanced(request);
the object called "response" is coming back as null.
I'm not sure where I'm going wrong and no exception is being thrown from the call to service.findItemsAdvanced()
If you could take a look and offer any advice at all I would be most grateful.
Here is my program.cs up until the problem
Progam.cs
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using EbayParser.com.ebay.developer;
using System.Net;
namespace EbayParser
{
class Program
{
static void Main(string[] args)
{
try
{
// Creating an object to the BestMatchService class
CustomFindingService service = new CustomFindingService();
service.Url = "http://svcs.sandbox.ebay.com/services/search/FindingService/v1";
com.ebay.developer.FindItemsAdvancedRequest request = new EbayParser.com.ebay.developer.FindItemsAdvancedRequest();
//Create Filter Objects
com.ebay.developer.ItemFilter filterEndTimeFrom = new EbayParser.com.ebay.developer.ItemFilter();
com.ebay.developer.ItemFilter filterEndTimeTo = new EbayParser.com.ebay.developer.ItemFilter();
com.ebay.developer.ItemFilter filterCatID = new EbayParser.com.ebay.developer.ItemFilter();
//Set Values for each filter
filterEndTimeFrom.name = EbayParser.com.ebay.developer.ItemFilterType.EndTimeFrom;
filterEndTimeFrom.value = new string[] { "" };
filterEndTimeTo.name = EbayParser.com.ebay.developer.ItemFilterType.EndTimeTo;
filterEndTimeTo.value = new string[] { "" };
filterCatID.name = EbayParser.com.ebay.developer.ItemFilterType.EndTimeFrom;
filterCatID.value = new string[] { "" };
//Create the filter array
com.ebay.developer.ItemFilter[] itemFilters = new EbayParser.com.ebay.developer.ItemFilter[3];
//Add Filters to the array
itemFilters[0] = filterCatID;
itemFilters[1] = filterEndTimeFrom;
itemFilters[2] = filterEndTimeTo;
request.itemFilter = itemFilters;
request.keywords = "ipod";
// Creating response object
FindItemsAdvancedResponse response = service.findItemsAdvanced(request);
and here is the code for the class called "CustomFindingService.cs"
CustomFindingService.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using EbayParser.com.ebay.developer;
namespace EbayParser
{
class CustomFindingService : FindingService
{
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
try
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
request.Headers.Add("X-EBAY-SOA-SECURITY-APPNAME", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
request.Headers.Add("X-EBAY-SOA-OPERATION-NAME", "findItemsByKeywords");
request.Headers.Add("X-EBAY-SOA-SERVICE-NAME", "FindingService");
request.Headers.Add("X-EBAY-SOA-MESSAGE-PROTOCOL", "SOAP11");
request.Headers.Add("X-EBAY-SOA-SERVICE-VERSION", "1.0.0");
request.Headers.Add("X-EBAY-SOA-GLOBAL-ID", "EBAY-US");
return request;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
I had exactly the same problem when I went from finding by keywords to using the advanced method. I spent a while scratching my head myself but it turned out to have a simple fix:
Your header X-EBAY-SOA-OPERATION-NAME reads findItemsByKeywords. Changing it to findItemsAdvanced should do the trick.
If you leave any of the filters blank in the filter array you will get the SOA Operation Header missing exception whether or not you have included the headers correctly.
You should check the filters are not null before applying them to your request.

Categories