Usuário com melhor resposta
Pegar valor em página da web.

Pergunta
-
Pessoal como podemos ver esse link: GeoipTool nos mostra algumas informações sobre o nosso IP.
Eu estou desenvolvendo uma aplicativo em silverlight para um client, cujo eu preciso pegar a latitude e longitude que é mostrado naquele site.
OBS: Em silverlight for web application, preciso pegar a longitude e latitude que mostra no site GeoipTool, quais seriam as maneiras possiveis para fazer isso? eu estou com muita urgencia, mas desde quando começei o projeto n consegui fazer praticamente nada por ter me deparado com esse problema!
Thiii =)
- Movido Levi Domingos terça-feira, 28 de agosto de 2012 18:24 (De:C#)
terça-feira, 28 de agosto de 2012 17:48
Respostas
-
Oi... eu faria algo mais ou menos assim:
using System; using System.IO; using System.Net; using System.Windows.Controls; namespace SilverlightApplication1 { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); GeoIpToolAsync("201.55.6.191", GeoIpToolCompleted); } private void GeoIpToolCompleted(decimal[] coords) { var longitute = coords[0]; var latitude = coords[1]; } public static void GeoIpToolAsync(string ip, Action<decimal[]> callback) { var client = new WebClient(); client.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) { using (var reader = new StringReader(e.Result)) { string linha = null; bool longitude = false, latitute = false; decimal[] retorno = new decimal[2]; while ((linha = reader.ReadLine()) != null) { if (longitude == true) { var inicio = linha.IndexOf('>') + 1; var final = linha.IndexOf('<', inicio) - inicio; var valor = linha.Substring(inicio, final); retorno[0] = decimal.Parse(valor); } if (latitute == true) { var inicio = linha.IndexOf('>') + 1; var final = linha.IndexOf('<', inicio) - inicio; var valor = linha.Substring(inicio, final); retorno[1] = decimal.Parse(valor); } longitude = linha.Contains("Longitude:"); latitute = linha.Contains("Latitude:"); } if (callback != null) callback(retorno); } }; client.DownloadStringAsync(new Uri("http://www.geoiptool.com/pt/?IP=" + ip, UriKind.Absolute)); } } }
Microsoft Community Contributor
- Marcado como Resposta Thiago de bona terça-feira, 28 de agosto de 2012 18:20
terça-feira, 28 de agosto de 2012 18:10
Todas as Respostas
-
Oi... eu faria algo mais ou menos assim:
using System; using System.IO; using System.Net; using System.Windows.Controls; namespace SilverlightApplication1 { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); GeoIpToolAsync("201.55.6.191", GeoIpToolCompleted); } private void GeoIpToolCompleted(decimal[] coords) { var longitute = coords[0]; var latitude = coords[1]; } public static void GeoIpToolAsync(string ip, Action<decimal[]> callback) { var client = new WebClient(); client.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) { using (var reader = new StringReader(e.Result)) { string linha = null; bool longitude = false, latitute = false; decimal[] retorno = new decimal[2]; while ((linha = reader.ReadLine()) != null) { if (longitude == true) { var inicio = linha.IndexOf('>') + 1; var final = linha.IndexOf('<', inicio) - inicio; var valor = linha.Substring(inicio, final); retorno[0] = decimal.Parse(valor); } if (latitute == true) { var inicio = linha.IndexOf('>') + 1; var final = linha.IndexOf('<', inicio) - inicio; var valor = linha.Substring(inicio, final); retorno[1] = decimal.Parse(valor); } longitude = linha.Contains("Longitude:"); latitute = linha.Contains("Latitude:"); } if (callback != null) callback(retorno); } }; client.DownloadStringAsync(new Uri("http://www.geoiptool.com/pt/?IP=" + ip, UriKind.Absolute)); } } }
Microsoft Community Contributor
- Marcado como Resposta Thiago de bona terça-feira, 28 de agosto de 2012 18:20
terça-feira, 28 de agosto de 2012 18:10 -
Tomara que de certo isso, pq é minha ultima salvação kk, mas ta acontecendo um probleminha ali, vc sabe oq é?
Thiii =)
terça-feira, 28 de agosto de 2012 18:21 -
Eu percebi que quando eu faço o downloadstring com a página geoiptool o aplicatico n consegue ler a página e de erro, pq se tentar com qualquer outro link da certo, porq será isso?Tomara que de certo isso, pq é minha ultima salvação kk, mas ta acontecendo um probleminha ali, vc sabe oq é?
Thiii =)
Thiii =)
terça-feira, 28 de agosto de 2012 19:18 -
Thiago,
Esta dando um erro de acesso a uma pagina fora do dominio da aplicação... existem formas de resolver isso.. mas simplificando... cria um WebService no mesmo Web Application do seu projeto e coloca a consulta dentro dele...:
using System.Web.Services; namespace WebApplication1 { /// <summary> /// Summary description for WebService1 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class WebService1 : System.Web.Services.WebService { [WebMethod] public decimal[] GeoIpTool(string ip) { var client = new System.Net.WebClient(); var html = client.DownloadString("http://www.geoiptool.com/pt/?IP=" + ip); using (var reader = new System.IO.StringReader(html)) { string linha = null; bool longitude = false, latitute = false; decimal[] retorno = new decimal[2]; while ((linha = reader.ReadLine()) != null) { if (longitude == true) { var inicio = linha.IndexOf('>') + 1; var final = linha.IndexOf('<', inicio) - inicio; var valor = linha.Substring(inicio, final); retorno[0] = decimal.Parse(valor); } if (latitute == true) { var inicio = linha.IndexOf('>') + 1; var final = linha.IndexOf('<', inicio) - inicio; var valor = linha.Substring(inicio, final); retorno[1] = decimal.Parse(valor); } longitude = linha.Contains("Longitude:"); latitute = linha.Contains("Latitude:"); } return retorno; } } } }
Ai vc referncia esse WebService ao seu silverligth e chama dentro dele o metodo:
using System; using System.Windows; using System.Windows.Controls; namespace SilverlightApplication2 { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { var service = new ServiceReference1.WebService1SoapClient(); service.GeoIpToolCompleted += new EventHandler<ServiceReference1.GeoIpToolCompletedEventArgs>(service_GeoIpToolCompleted); service.GeoIpToolAsync("201.55.6.191"); } void service_GeoIpToolCompleted(object sender, ServiceReference1.GeoIpToolCompletedEventArgs e) { MessageBox.Show(String.Format("Longitude: {0}, Latitude: {1}", e.Result[0], e.Result[1])); } } }
Microsoft Community Contributor
quarta-feira, 29 de agosto de 2012 17:23 -
Eu fiz isso aqui e deu certo, o webClient n conseguia fazer download da página geoiptool, n sei porque.
private void button1_Click(object sender, RoutedEventArgs e) { var client = new WebClient(); client.DownloadStringCompleted += ClientDownloadStringCompleted; client.DownloadStringAsync(new Uri("http://whatismyipaddress.com/ip/189.28.181.144", UriKind.RelativeOrAbsolute)); //label1.Content = DreamInCode.Snippets.IpFinder.GetExternalIp(); //lbldistancia.Content = "Distância de: " + GeoMath.Distance(td(latia.Text), td(longia.Text), td(latib.Text), td(longib.Text), GeoMath.MeasureUnits.Kilometers).ToString("#.##") + " Km"; } private void ClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { lbldistancia.Content = "Página baixada com sucesso!"; using (var reader = new StringReader(e.Result)) { string linha = null; bool longitude = false; bool latitude = false; string data_latitude = ""; string data_longitude = ""; while ((linha = reader.ReadLine()) != null) { if (linha.Contains("Latitude:") && linha.Contains("</th><td>")) { latitude = true; data_latitude = linha; } if (linha.Contains("Longitude:</th><td>") && linha.Contains("</th><td>")) { longitude = true; data_longitude = linha; } } if (latitude && longitude) { //<tr><th>Latitude:</th><td>-28.6667</td></tr> Regex exx = new Regex("<td>(.*)</td>"); if (exx.IsMatch(data_latitude)) { data_latitude = (exx.Match(data_latitude).Groups[1].Value); } data_latitude = data_latitude.Replace(".", ","); // Regex ex = new Regex("<td>(.*)</td>"); if (ex.IsMatch(data_longitude)) { data_longitude = (ex.Match(data_longitude).Groups[1].Value); } data_longitude = data_longitude.Replace(".", ","); // MinhaLatitude = Convert.ToDouble(data_latitude); MinhaLongitude = Convert.ToDouble(data_longitude); // latitude_c.Content = "Latitude atual: " + MinhaLatitude.ToString(); longitude_c.Content = "Longitude atual: " + MinhaLongitude.ToString(); canStart = true; } } }
Thiii =)
quarta-feira, 29 de agosto de 2012 17:27 -
Pro WebClient funcionar voce tem que configurar o acesso do silverlight a sites que possuem um dominio diferente do qual o silverlight esta rodando...
por exemplo se vc tem o seu client numa pagina: http://meu .servidor.com/meu_silverlight.html... ele so funciona(por default) para acessar paginas e arquivos q estao em "meu.servidor.com"...
Para acessa de outros servers.. como o do geoip acima... vc tem que configurar os arquivos de polices...:
http://msdn.microsoft.com/en-us/library/cc645032(v=vs.95).aspx
http://msdn.microsoft.com/en-us/library/cc197955(v=vs.95).aspx
Microsoft Community Contributor
segunda-feira, 3 de setembro de 2012 15:33