C# Returned .XML to class - c#

I am tring to give an information from friendfeed API.
As you see in code, I am using an HttpRequest to get information. It's ok.
After that I am reading XML just fine with LINQ.
But now I create a "feed" class and I want to create an object for every returned value (i from finaltoclass).
How can I do this?
Can you help me with this?
Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
class feed { }
public class entry {
string body;
string id;
string url;
public entry(string a, string b, string c)
{
body = a;
id = b;
url = c;
}
}
static void Main(string[] args)
{
string username = "semihmasat";
WebRequest ffreq = WebRequest.Create("http://friendfeed-api.com/v2/feed/" + username + "?format=xml");
WebResponse ffresp = ffreq.GetResponse();
Console.WriteLine(((HttpWebResponse)ffresp).StatusDescription);
Stream stream = ffresp.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string respfinal = reader.ReadToEnd();
reader.Close();
XElement final = XElement.Load("http://friendfeed-api.com/v2/feed/" + username + "?format=xml");
var finaltoclass = from i in final.Elements("entry")
select i;
foreach (XElement i in finaltoclass) {
string body= i.Element("body").Value;
string id= i.Element("id").Value;
string url= i.Element("url").Value;
Console.WriteLine("{0},{1},{2}", body, id, url);
}
Console.ReadLine();
}
}
}

If you think to read it this way (dynamic feed class - without declaring feed, entry, via and from classes ):
dynamic feed = new Uri("http://friendfeed-api.com/v2/feed/" + username + "?format=json").GetDynamicJsonObject();
foreach (var entry in feed.entries)
{
Console.WriteLine(entry.from.name + "> " + entry.body + " " + entry.url);
}
you will need Json.Net and this extension class

Let's try this code
var finaltoclass = from i in final.Elements("entry")
select new entry (i.Element("body").Value, i.Element("id").Value, i.Element("url").Value );

You need to add to an ObservableCollection of entry.

Related

File format could not be determined using Metadata Extractor 2.4.3

I'm trying to make a program that automatically copies and sorts the pictures from an SD card to an external hard drive using Metadata Extractor 2.4.3
I don't seem to find any prolem but every time I run the code, an unhandled exception prompts up.
Here's the error:
Unhandled Exception: MetadataExtractor.ImageProcessingException: File format could not be determined
at MetadataExtractor.ImageMetadataReader.ReadMetadata(Stream stream)
at MetadataExtractor.ImageMetadataReader.ReadMetadata(String filePath)
at file_sorter.File..ctor(String filepath) in
C:\Users\ropra\Documents\file_sorter\file_sorter\File.cs:line 27
at file_sorter.Program.Main(String[] args) in
C:\Users\ropra\Documents\file_sorter\file_sorter\Program.cs:line 27
Here's the code:
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MetadataExtractor;
namespace file_sorter
{
class Program
{
static void Main(string[] args)
{
// Define paths
string sandisk = #"Z:/Images/RAW";
string sd = #"Y:/DCIM/100_FUJI";
// Count elements in sd
string[] photoPaths = System.IO.Directory.GetFiles(sd);
Console.WriteLine("Counting elements in SD card...");
// Create object array
File[] photos = new File[photoPaths.Count()];
for (int i = 0; i < photos.Count(); i++)
{
photos[i] = new File(photoPaths[i]);
}
// Create tree and copy files
foreach (var item in photos)
{
string fileName = item.filename;
string sourcePath = item.sourcepath;
string targetPath = sandisk + "/" + item.year + "/" + item.month + "/" + item.day;
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
Console.WriteLine("Now copying: {0} into {1}", fileName, targetPath);
System.IO.Directory.CreateDirectory(targetPath);
System.IO.File.Copy(sourceFile, destFile, true);
}
}
}
}
File.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MetadataExtractor;
namespace file_sorter
{
public class File
{
public string filename;
public string path;
public string year;
public string month;
public string day;
public string sourcepath;
public File(string filepath)
{
path = filepath;
filename = path.Substring(path.LastIndexOf("\\") + 1);
sourcepath = path.Substring(0, path.LastIndexOf("\\"));
string rawDate = "";
var metadata = ImageMetadataReader.ReadMetadata(path);
for (int i = 0; i < metadata.Count(); i++)
{
for (int j = 0; j < metadata[i].TagCount; j++)
{
if (metadata[i].Name == "Exif IFD0" && metadata[i].Tags[j].Name == "Date/Time")
{
rawDate = metadata[i].Tags[j].Description;
}
}
}
int separator = rawDate.IndexOf(":");
year = rawDate.Substring(0, separator);
string sub = rawDate.Substring(separator + 1);
separator = sub.IndexOf(":");
month = sub.Substring(0, separator);
sub = sub.Substring(separator + 1);
separator = sub.IndexOf(" ");
day = sub.Substring(0, separator);
}
public void ShowFormatedDate()
{
Console.WriteLine("Path: {0}", path);
Console.WriteLine("File: {0}", filename);
Console.WriteLine("Dir: {0}", sourcepath);
Console.WriteLine("Year: {0}", year);
Console.WriteLine("Month: {0}", month);
Console.WriteLine("Day: {0}", day);
Console.WriteLine("");
}
}
}
Thank you in advance.
OK, so having given up and sorting all files manually, I came across an .xml file containing the metadata of a single .RAF file, I'm guessing my camera put it there.
This program does not handle MetadataExtractor non-supported files, hence the problem.
ImageProcessingException: File format could not be determined
This exception means that the library didn't identify the file it was given as anything it knows how to read. For example, if you give a text file to the library, you will see this exception.
Perhaps you could catch this exception type and use a different code path for such files.

Get the first and last cell in each row of CSV file using C#

I have a csv file like this:
1,2,3,4,5
6,7,8
9,10
How can I get the first and last cell to get the file like this:
1,5
6,8
9,10
This is a sample code that you may use to achieve your goal:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FirstLast
{
class Program
{
static void Main(string[] args)
{
String file = "C:\\samplec#programs\\FirstLast\\FirstLast\\bin\\Debug\\Test.csv";
using (StreamReader SR = new StreamReader(file))
{
while (!SR.EndOfStream) //best way to do it
{
//read a line of our file and split it into its separate values
var CSValues = SR.ReadLine().Split(',');
String first = CSValues.First();
String last = CSValues.Last();
Console.WriteLine("First val: " + first + " , Last val: " + last);
}
}
Console.ReadLine();
}
}
}
This is a simple sample in console, I believe you can understand from here. Take note of
String first = CSValues.First();
String last = CSValues.Last();

C# Find PHP Variable from URL Code

In C#, I want to find a PHP Variable from a URL Code.
Example: I want to find text out of www.domain.com/file.php?var=text
The main reason for this is that I want to parse the output of
youtube.com/get_video_info?video_id=, or System.IO.Path.GetTempPath() + #"\tempytinfo.txt", which is in the format of:
?var=value&var2=value&var3=value& ...
My efforts of trying to figure this out were sitting at Google, debugging other answers and either not working or just not what i'm looking for, and Here's my efforts so far (also with the help of the first awnser):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Paste A YouTube URL/URI to Download:");
string yturlstr = Console.ReadLine();
Uri yturl = new Uri(yturlstr);
Console.WriteLine("Finding ID in YouTube URL...");
string ytid = yturlstr.Split('?')[1];
ytid = ytid.Replace("v=", "");
Console.WriteLine("Found Watch ID.");
Console.WriteLine("The " + '"' + "Watch ID" + '"' + " is " + ytid);
Console.WriteLine("Getting Video Info...");
Download("http://youtube.com/get_video_info?video_id=" + ytid, System.IO.Path.GetTempPath() + #"\tempytinfo.txt");
Console.WriteLine("Got Info.");
Console.WriteLine("Reading Video Info...");
string viddata = System.IO.File.ReadAllText(System.IO.Path.GetTempPath() + #"\tempytinfo.txt");
Console.WriteLine("Parsing Video Info...");
Dictionary<string, string> videodata = new Dictionary<string, string>();
string vdt = viddata;
string[] vdata = vdt.Split('&');
foreach (char param in vdt)
{
string[] paramParts = char.ToString(param).Split('=');
videodata.Add(paramParts[0], paramParts[1]);
}
string uefsm = WebUtility.UrlDecode(videodata["url_encoded_fmt_stream_map"]);
Dictionary<string, string> videosubdata = new Dictionary<string, string>();
string[] vsdata = uefsm.Split('&');
foreach (char param2 in uefsm)
{
string[] paramParts2 = char.ToString(param2).Split('=');
videosubdata.Add(paramParts2[0], paramParts2[1]);
}
Uri downloadlink = new Uri(WebUtility.UrlDecode(videosubdata["url"]));
Console.WriteLine("Download Link: " + '"' + downloadlink + '"');
Console.ReadKey();
}
private static void Download(string URL, string WhereToDownload)
{
var client = new WebClient();
Uri downloadurl = new Uri(URL);
client.DownloadFile(downloadurl, WhereToDownload);
}
}
}
and my error is:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in ConsoleApplication2.exe
Additional information: Index was outside the bounds of the array.
I would parse all the parameters and store them in a collection to access them easily. Suppose you have the URL in yturl like you do on your code, you can create the collection:
Dictionary<string, string> parameters = new Dictionary<string, string>();
string tmpStr = yturl.Split('?')[1];
string[] params = tmpStr.Split('&');
foreach (string param in params)
{
string[] paramParts = param.Split('=');
parameters.Add(paramParts[0], paramParts[1]);
}
And get, following your example, "text", with:
string var = parameters["var"];
// var == "text"
And any other parameter value by it's name:
string var1 = parameters["var1"];
string var2 = parameters["var2"];

Accessing and displaying certain xml elements from a Service Reference

I'm writing a Stock Quote app in Silverlight and I can't figure out how to display only the information that I want from the xml, such as the price of the stock. It will display the tags and everything.
Here is my code:
private void getQuote_Click(object sender, RoutedEventArgs e)
{
bool check = NetworkInterface.GetIsNetworkAvailable();
if (check)
{
//available
GetQuote.StockQuoteSoapClient client = new StockQuoteSoapClient();
//call that method
client.GetQuoteAsync(symbolBox.Text);
//event handler response
client.GetQuoteCompleted +=client_GetQuoteCompleted;
}
else
{
return;
}
}
public void client_GetQuoteCompleted(object sender, GetQuoteCompletedEventArgs e)
{
result.Text = e.Result;
}
And here is the xml being returned by http://www.webservicex.net/stockquote.asmx?op=GetQuote
<string><StockQuotes><Stock><Symbol>msft</Symbol><Last>46.62</Last><Date>7/17/2015</Date><Time>4:00pm</Time><Change>-0.04</Change><Open>46.59</Open><High>46.78</High><Low>46.26</Low><Volume>29467107</Volume><MktCap>377.14B</MktCap><PreviousClose>46.66</PreviousClose><PercentageChange>-0.09%</PercentageChange><AnnRange>40.12 - 50.05</AnnRange><Earns>2.41</Earns><P-E>19.35</P-E><Name>Microsoft Corporation</Name></Stock></StockQuotes></string>
This is for a mobile app; it has to provide new, up-to-date information from the web service every time it is used, and I only need a few different pieces of the information. Also, the information shouldn't be specifically Microsoft, but any real company whose stock symbol is entered by the user.
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<string>" +
"<StockQuotes>" +
"<Stock>" +
"<Symbol>msft</Symbol>" +
"<Last>46.62</Last>" +
"<Date>7/17/2015</Date>" +
"<Time>4:00pm</Time>" +
"<Change>-0.04</Change>" +
"<Open>46.59</Open>" +
"<High>46.78</High>" +
"<Low>46.26</Low>" +
"<Volume>29467107</Volume>" +
"<MktCap>377.14B</MktCap>" +
"<PreviousClose>46.66</PreviousClose>" +
"<PercentageChange>-0.09%</PercentageChange>" +
"<AnnRange>40.12 - 50.05</AnnRange>" +
"<Earns>2.41</Earns>" +
"<P-E>19.35</P-E>" +
"<Name>Microsoft Corporation</Name>" +
"</Stock>" +
"</StockQuotes>" +
"</string>";
XDocument doc = XDocument.Parse(input);
var stocks = doc.Descendants("Stock").Select(x => new {
symbol = x.Element("Symbol").Value,
last = double.Parse(x.Element("Last").Value),
date = DateTime.Parse(x.Element("Date").Value),
time = DateTime.Parse(x.Element("Time").Value),
change = double.Parse(x.Element("Change").Value),
open = double.Parse(x.Element("Open").Value),
high = double.Parse(x.Element("High").Value),
low = double.Parse(x.Element("Low").Value),
volume = long.Parse(x.Element("Volume").Value),
mktcap = double.Parse(x.Element("MktCap").Value.Replace("B", "")),
previousClose = double.Parse(x.Element("PreviousClose").Value),
percentChange = double.Parse(x.Element("PercentageChange").Value.Replace("%", "")),
annRange = x.Element("AnnRange").Value,
earns = double.Parse(x.Element("Earns").Value),
p_e = double.Parse(x.Element("P-E").Value),
name = x.Element("Name").Value,
}).ToList();
}
}
}
​

MaasOne yahoo-finance-managed returning zero results for AlphabeticIDIndexResult

I am trying to use http://code.google.com/p/yahoo-finance-managed/ to retrieve a list of all stock ids
with the following code:
using MaasOne.Base;
using MaasOne.Finance.YahooFinance;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Elance___Yahoo_Finance_Symbols
{
class Program
{
static void Main(string[] args)
{
AlphabeticIDIndexDownload dl1 = new AlphabeticIDIndexDownload();
dl1.Settings.TopIndex = null;
Response<AlphabeticIDIndexResult> resp1 = dl1.Download();
Console.Write("Id|Isin|Name|Exchange|Type|Industry");
foreach (var alphabeticalIndex in resp1.Result.Items)
{
AlphabeticalTopIndex topIndex = (AlphabeticalTopIndex)alphabeticalIndex;
dl1.Settings.TopIndex = topIndex;
Response<AlphabeticIDIndexResult> resp2 = dl1.Download();
foreach (var index in resp2.Result.Items)
{
IDSearchDownload dl2 = new IDSearchDownload();
Response<IDSearchResult> resp3 = dl2.Download(index);
int i = 0;
foreach (var item in resp3.Result.Items)
{
Console.Write(item.ID + "|" + item.ISIN + "|" + item.Name + "|" + item.Exchange + "|" + item.Type + "|" + item.Industry);
}
}
}
}
}
}
but the
Response<AlphabeticIDIndexResult> resp1 = dl1.Download();
is always returning zero results...
Does anyone know what might be wrong please?
Thanks
I have an app using this API that's been working for about a year, and I see the same issue as of yesterday. :( Perhaps Yahoo changed their API, which would really suck.

Categories