issharp
issharp

Reputation: 320

Call another website's api with webjobs

I'm new to azure webjobs, but I'm trying to use them to make an api call to the bing maps api when I need it. Eventually this will be triggered by a request on my website, but at the moment I'm just trying to figure out webjobs. I created a console app and manually added it as a webjob to a sample website. All of my test webjobs (simple hello world type things) have worked fine, but when I try to call the bing maps api, the webjob says it completed successfully but only part of the code executed. Here is the code for the webjob:

class Program
{
    static void Main(string[] args)
    {
         Program p = new Program();
         p.MakeAsync();
    }

    public async void MakeAsync()
    {
        Console.WriteLine("I'm about to call");
        CallMe c = new CallMe();
        bool x = await c.CallBingMapsAsync(49931);
        Console.WriteLine("I called and the result was {0}", x);
    }
}

public class CallMe
{
    public async Task<bool> CallBingMapsAsync(int zip)
    {       
       RootOb lookups = await BingMaps.GetLocations(zip);
       Resource here = lookups.resourceSets[0].resources[0];
       string city = here.address.locality;
       double lat = here.point.coordinates[0];
       double lon = here.point.coordinates[1]; 
       Console.WriteLine("I looked up {0} and found it at ({1} N, {2} W).",city, lat, lon); 
       return true;
    }
}

BingMaps.GetLocations() retrieves the data and converts it to an object format. When I run this in visual studio, everything works fine and the correct things are printed to the console, etc.

When I zip this and add it as a webjob, the api call either does not occur, or the webjob finishes before it does occur. When I view the log after running, I see the console message "I'm about to call" occurred, and then the status is changed to success and the webjob finishes without running any of the rest of the code. Does a webjob like this not work with an api call, or am I just doing something wrong and there is a fix? Again, I'm new to webjobs, so any simple advice would be awesome. Thanks!

Upvotes: 1

Views: 1141

Answers (1)

Justin Patten
Justin Patten

Reputation: 1069

You probably need to wait for the response to happen. You are calling in to "async" methods, but the static entry point doesn't natively support waiting for those to finish before closing the executable. Try this:

static void Main(string[] args)
{
     Program p = new Program();
     p.MakeAsync().Wait();
}

public async Task MakeAsync()
{
    Console.WriteLine("I'm about to call");
    CallMe c = new CallMe();
    bool x = await c.CallBingMapsAsync(49931);
    Console.WriteLine("I called and the result was {0}", x);
}

Upvotes: 3

Related Questions