PhantomM
PhantomM

Reputation: 845

DownloadString not getting executed

I am new to C#.Net programming and facing a problem. When I am calling getLocation function, I always get "location" empty. I know I am doing things in wrong manner. But It would be great if someone can help me to do it in correct way. I want getLocation function to return location value. So, it should return only when wc.downloadString gets executed before returning location value.

public String getLocation()
{
    RetrieveFormatedAddress(latitude, longitutde);
    location = returnVal;
    return location;
}

static void RetrieveFormatedAddress(string lat, string lng)
{
    string requestUri = string.Format(baseUri, lat, lng);

    using (WebClient wc = new WebClient())
    {
        wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
        wc.DownloadString(new Uri(requestUri));
        //wc.DownloadStringAsync(new Uri(requestUri));
    }
}

private static void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    var xmlElm = XElement.Parse(e.Result);

    var status = (from elm in xmlElm.Descendants()
                  where elm.Name == "status"
                  select elm).FirstOrDefault();
    if (status.Value.ToLower() == "ok")
    {
        var res = (from elm in xmlElm.Descendants()
                   where elm.Name == "formatted_address"
                   select elm).FirstOrDefault();
        returnVal = res.Value;
    }
    else
    {
        returnVal = "No Address Found";
    }

}

Upvotes: 0

Views: 662

Answers (2)

Caleb Kiage
Caleb Kiage

Reputation: 1432

The DownloadString() method is a synchronous version of DownloadStringAsync() method. It returns data downloaded from the server as a string. In your code, you're not reading this value anywhere. Try var data = wc.DownloadString(new Uri(requestUri)); to get the data.

Upvotes: 1

Andorbal
Andorbal

Reputation: 880

public String getLocation()
{
    return RetrieveFormatedAddress(latitude, longitutde);
}

static string RetrieveFormatedAddress(string lat, string lng)
{
    string requestUri = string.Format(baseUri, lat, lng);

    using (WebClient wc = new WebClient())
    {
        var result = wc.DownloadString(new Uri(requestUri));
        var xmlElm = XElement.Parse(result);

        var status = (from elm in xmlElm.Descendants()
              where elm.Name == "status"
              select elm).FirstOrDefault();
        if (status.Value.ToLower() == "ok")
        {
        var res = (from elm in xmlElm.Descendants()
               where elm.Name == "formatted_address"
               select elm).FirstOrDefault();
            return res.Value;
        }
        else
        {
            return "No Address Found";
        }
    }
}

Upvotes: 2

Related Questions