I have this code for working with GoogleMapsApi:
public void GoogleGeoCode(string address)
{
address = "Stockholm";
string url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=";
dynamic googleResults = new Uri(url + address).GetDynamicJsonObject();
//Code that lets me pick out values from googleresults
}
googleresults contains values (longitude/latitude) but how can i pich those out and use the for something else? I used this approach in a similar situation but it is not valid code in this case:
JObject o = JObject.Parse(googleresult);
string name = (string)o.SelectToken("longitude");
EDIT:
This seems to pick put the longitude and latitude:
public void GoogleGeoCode(string address)
{
address = "Stockholm";
string url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=";
dynamic googleResults = new Uri(url + address).GetDynamicJsonObject();
foreach (var result in googleResults.results)
{
double lng = result.geometry.location.lng;
double lat = result.geometry.location.lat;
}
//Do something else...
}
Your googleResults is not a string. It is a dynamic jason object. Try looking at this.
Code from here: Looking for a REST with JSON client library
public static void GoogleGeoCode(string address)
{
string url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=";
dynamic googleResults = new Uri(url + address).GetDynamicJsonObject();
foreach (var result in googleResults.results)
{
Console.WriteLine("[" + result.geometry.location.lat + "," +
result.geometry.location.lng + "] " +
result.formatted_address);
}
}
Related
As i'm trying to web scrape a part from the website. Here is an image below.
as the pagination is checked in red box i need to extract value of last in the image above it is 151. So the pagination is dynamic which is hard to extract when i check using view page source in only <div class="jsx-46358917 pagination-wrapper text-center"></div> is shown as inside its value is missing as i understand it is dynamic but i need the last value from the pagination example 151.
Here is a code which i have done so far to web scrape it.
public void parseItem(HtmlDocument doc, string zipCode)
{
//Getting json data
if (doc.DocumentNode.LastChild.HasChildNodes)
{
var siteScripts = doc.DocumentNode.SelectSingleNode("//script[#id='__NEXT_DATA__']").InnerText;
var result = JsonConvert.DeserializeObject<RealtorModel>(siteScripts);
if (result != null)
{
foreach (var realtor in result.Props.CriteriaData.SrpShell.LoadedData.SearchResults.HomeSearch.Results)
{
string propertyId = "M" + realtor.PropertyId;
string address = realtor.Location.Address.Line + ", " + realtor.Location.Address.City + ", " + realtor.Location.Address.StateCode + " " + realtor.Location.Address.PostalCode;
string listingURL = hostName + "/realestateandhomes-detail/" + realtor.Permalink;
var url = realtor.PrimaryPhoto;
listings.Add(new Listings { PropertyID = propertyId, Address = address, Price = realtor.ListPrice, ImageURL = realtor.PrimaryPhoto.Href.AbsoluteUri, ListingURL = listingURL });
}
}
pageNumber = pageNumber + 1;
string nextUrl = "https://www.realtor.com/realestateandhomes-search/" + zipCode + "/type-single-family-home" + "/pg-" + pageNumber;
AddTask(nextUrl, this.parseItem, zipCode);
}
else
{
System.Threading.Thread.Sleep(60000);
string nextUrl = "https://www.realtor.com/realestateandhomes-search/" + zipCode + "/type-single-family-home" + "/pg-" + pageNumber;
AddTask(nextUrl, this.parseItem, zipCode);
}
}
As i get the complete page through scraping only thing is the last value of the paginate which i cannot extract due to its dynamic nature. How can i achieve to do so any hint would be helpful.
I'm using google map API. I have 4 destinations and I want to get their locations ordered by nearest location first followed by second nearest. I have to show on Google Map which location is 1st being the nearest and then the next nearest and so on. So far I have only successfully calculated the distance between 2 locations by using below code:
private void button1_Click(object sender, EventArgs e)
{
getDistance("DECATUR FARM ROAD CHICHESTER PO20 8JT", "UNIT 01 CLIFF REACH GREENHITHE DA9 9SW");
}
public int getDistance(string origin, string destination)
{
System.Threading.Thread.Sleep(1000);
int distance = 0;
//string from = origin.Text;
//string to = destination.Text;
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
string requesturl = url;
//string requesturl = #"http://maps.googleapis.com/maps/api/directions/json?origin=" + from + "&alternatives=false&units=imperial&destination=" + to + "&sensor=false";
string content = fileGetContents(requesturl);
JObject o = JObject.Parse(content);
try
{
distance = (int)o.SelectToken("routes[0].legs[0].distance.value");
return distance;
}
catch
{
return distance;
}
return distance;
//ResultingDistance.Text = distance;
}
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("http:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
How do I show the destinations according to their distance on google map. Any tip or pointers will be appreciated.
Please see the image, this is what I am trying to accomplish
Happy :) Enjoy Coding..
ArrayList arraylist;
List<string> adddistance = new List<string>();
List<string> getfinallist = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
string s = "UNIT 01 CLIFF REACH GREENHITHE DA9 9SW,PINETOP BIRKLANDS LANE ST ALBANS AL1 1EE,HOLYWELL HILL ST ALBANS AL1 1BT,OLD RECTORY HOLYWELL HILL ST ALBANS AL1 1BY";
button("DECATUR FARM ROAD CHICHESTER PO20 8JT", s);
}
public void button(string orign , string destination)
{
string[] words = destination.Split(',');
foreach (string word in words)
{
getDistance(orign, word);
}
sorting();
}
public int getDistance(string origin, string destination)
{
System.Threading.Thread.Sleep(1000);
int distance = 0;
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
string requesturl = url;
string content = fileGetContents(requesturl);
JObject o = JObject.Parse(content);
string strdistance = (string)o.SelectToken("routes[0].legs[0].distance.value") + " , " + destination + " , ";
adddistance.Add(strdistance);
return distance;
}
public void sorting()
{
adddistance.Sort();
string getfirststring = adddistance.FirstOrDefault().ToString() ;
var vals = getfirststring.Split(',')[1];
getfinallist.Add(getfirststring.Split(',')[1]);
StringBuilder builder = new StringBuilder();
adddistance.RemoveAt(0);
foreach (string cat in adddistance) // Loop through all strings
{
builder.Append(cat); // Append string to StringBuilder
}
adddistance.Where((wors, index) => index % 2 == 0);
string result = builder.ToString();
string[] words = result.Split(',');
string[] even = words.Where((str, ix) => ix % 2 == 1).ToArray();
adddistance.Clear();
foreach (string word in even)
{ //string get = Regex.Match(word, #"^[" + numSet + #"]+$").ToString();
if (word != " ")
{
getDistance(vals, word);
}
}
sorting();
}
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("http:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
I am looking for the best way to compare XML data with a string.
the data is stored in a xml called test.xml, and must be compared with the name descendant, if there is a match more info from the xml must be added to a textbox and picture box.
My ( working ) code:
var xmlDocument = XDocument.Load("test.xml"); // XML koppellen
var key1 = xmlDocument.Descendants("NAME"); // XML filepath
var key2 = xmlDocument.Descendants("TITLE"); // XML titel
var key3 = xmlDocument.Descendants("BRAND"); // XML afbeelding
var key4 = xmlDocument.Descendants("TYPE"); // XML merk
var key5 = xmlDocument.Descendants("SOORT"); // XML type
var key6 = xmlDocument.Descendants("NAAM"); // XML naam
List<string> file = new List<string>();
List<string> title = new List<string>();
List<string> brand = new List<string>();
List<string> type = new List<string>();
List<string> soort = new List<string>();
List<string> naam = new List<string>();
int i = 0;
foreach (var key in key1)
{
file.Add(key.Value.Trim());
}
foreach (var key in key2)
{
title.Add(key.Value.Trim());
}
foreach (var key in key3)
{
brand.Add(key.Value.Trim());
}
foreach (var key in key4)
{
type.Add(key.Value.Trim());
}
foreach (var key in key5)
{
soort.Add(key.Value.Trim());
}
foreach (var key in key6)
{
naam.Add(key.Value.Trim());
}
foreach (var Name in naam)
{
if (textBox3.Text.ToString() == Name.ToString())
{
PDFLocation = file[i].ToString();
pictureBox1.Image = pdfhandler.GetPDFthumbNail(PDFLocation);
textBox4.Text =
title[i].ToString() + "\r\n" +
brand[i].ToString() + "\r\n" +
type[i].ToString() + "\r\n" +
soort[i].ToString() + "\r\n" +
textBox3.Text + "\r\n";
}
i++;
}
]
I think this is not the best way to do it, but cant see a better way....
Update: solution:
foreach (XElement element in xmlDocument.Descendants("PDFDATA"))
{
if (textBox3.Text.ToString() == element.Element("NAAM").Value.Trim())
{
PDFLocation = element.Element("NAME").Value.ToString();
pictureBox1.Image = pdfhandler.GetPDFthumbNail(PDFLocation);
textBox4.Text =
element.Element("TITLE").Value + "\r\n" +
element.Element("BRAND").Value + "\r\n";
break;
}
}
Instead of thinking of the xml and a bunch of individual lists of data, it helps to think of it more as objects. Then you can loop through each element one at a time and don't need to split it up into individual lists. This not only removes duplicate code but more importantly creates a better abstraction of the data you are working with. This makes it easier to read and understand what the code is doing.
foreach (XElement element in xmlDocument.Elements())
{
if (textBox3.Text.ToString() == element.Element("NAAM").Value)
{
PDFLocation = element.Element("NAAM").Value;
pictureBox1.Image = pdfhandler.GetPDFthumbNail(PDFLocation);
textBox4.Text =
element.Element("Title").Value + "\r\n" +
element.Element("Brand").Value + "\r\n" +
element.Element("Type").Value + "\r\n"
// access rest of properties...
}
}
I was trying to retrieve data from Amazon SimpleDB and currently it only displays data in text like domainName: {attribute1, value2} {attribute1, value2}.
How can I show the data in data grid view? My code is as follows:
public static List<String> GetItemByQuery(IAmazonSimpleDB simpleDBClient, string domainName)
{
List<String> Results = new List<String>(); ;
SelectResponse response = simpleDBClient.Select(new SelectRequest()
{
SelectExpression = "Select * from " + domainName
});
String res = domainName + " has: ";
foreach (Item item in response.Items)
{
res = item.Name + ": ";
foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attributes)
{
res += "{" + attribute.Name + ", " + attribute.Value + "}, ";
}
res = res.Remove(res.Length - 2);
Results.Add(res);
}
return Results;
}
How you an read here:
http://docs.aws.amazon.com/sdkfornet1/latest/apidocs/html/P_Amazon_SimpleDB_Model_SelectResult_Item.htm
your response.Items is
public List<Item> Item { get; set; }
so you should directly use to DataSource of your Grid, set autogenerate column to your grid to start to view the result
I am new to mvc. I have a controller with two methods. I want to return a list to a text
file on the click of a button. I have been trying to figure out a way how I can pass
the list to the CreateReportFile method but no luck. It works very well for stringbuilder objects.
Do you have an idea of how I can display the List in a text file?
#Html.ActionLink("Download File", "CreateReportFile");
public FileStreamResult CreateReportFile()
{
//todo: add some data from your database into that string:
var string_with_your_data = string.Empty;
var byteArray = Encoding.ASCII.GetBytes(string_with_your_data);
var stream = new MemoryStream(byteArray);
return File(stream, "text/plain", "Report" + DateTime.Now + ".txt");
}
public List<Student> GetStudents()
{
return new List<Student>()
{
new Student() {firstname="james",lastname="john",emailAddress="james.john#yahoo.com"},
new Student() {firstname="patric",lastname="swayze",emailAddress="patric.swayze#yahoo.com"},
new Student() {firstname="james",lastname="john",emailAddress="james.john#yahoo.com"},
new Student() {firstname="toy",lastname="gas",emailAddress="toy.gas#yahoo.com"}
};
}
If you are trying to get the students list into that string you are writing to the file you could try:
public FileStreamResult CreateReportFile()
{
List<Student> students = GetStudents();
StringBuilder sb = new StringBuilder();
foreach (Student s in students)
sb.AppendLine(s.firstname + ", " + s.lastname + ", " + s.emailAddress);
var string_with_your_data = sb.ToString();
var byteArray = Encoding.ASCII.GetBytes(string_with_your_data);
var stream = new MemoryStream(byteArray);
return File(stream, "text/plain", "Report" + DateTime.Now + ".txt");
}
All you should have to do is add this to make it a string and then send the data.
foreach(Student test in GetStudents())
{
string_with_your_data += test.firstname + ", " + test.lastname + ", " + test.emailAddress + "\r\n";
}
If you're asking how to convert List object into text you will need to create a method that does that OR you can use a Serializer, but that will format it into json or xml.
To convert the object yourself in your student object you can override ToString with something like this:
public override string ToString()
{
return String.Format("firstname={0}, lastname={1}, emailAddress={2}", firstname, lastname, emailAddress);
}
Then you can loop through your list
string mystring = string.Empty;
foreach(var student in Students)
mystring += student.ToString() + "\n";
Just some ideas that might get you started.