How do I convert Console App's code block to Azure Function's code block?

695 Views Asked by At

I've written my sample console application and it's complied and get the data well. Now I want to test it as an Azure Function. The following are the code blocks in console app. How can I rewrite it as Azure's time-trigger function? Thanks.

using System;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;

namespace Google.Apis.Samples

internal class MyData
{
    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine("Blah Blah Blah");
        Console.WriteLine("==============");

        try
        {
            new MyData().Run().Wait();
        }
        catch (AggregateException ex)
        {
            foreach (var e in ex.InnerExceptions)
            {
                Console.WriteLine("Error: " + e.Message);
            }
        }
    }
    private async Task Run()
    {
    // I can either use service account or supply api key.
    // How do I read a JSON file from Azure function?
    // then I can Get data and display results.
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

So I got this finally.

I used Azure Function Template in VS2017.

I need to add NuGet Packages (I had to use Azure V2 to match dependency requirement). And I just have to put all the codes inside of private async Task Run() of Console App to Azure Function's public static void Run([TimerTrigger( ....

I have yet to publish and test it on Azure. And by the way, Azure Storage Emulator has to be initialized and started with Admin mode in Windows CMD.

Function's output

0
On

I'm not sure what is your intention, but if you want to encode your code in an azure function maybe this can help you.

in order to read a json file you can use :

  FileStream fs = new FileStream(@"your_json", FileMode.Open)

Here you code in one Azure Function

using System.Net;
using System.IO;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("Blah Blah Blah");
    log.Info("==============");

    try
        {
            await Run_Function();
        }
        catch (AggregateException ex)
        {
            foreach (var e in ex.InnerExceptions)
            {
                log.Info("Error: " + e.Message);
            }
        }


     return req.CreateResponse(HttpStatusCode.OK, "OK");
}

 private static Task Run_Function()
    {
    // I can either use service account or supply api key.
    // How do I read a JSON file from Azure function?
      using (FileStream fs = new FileStream(@"your_json", FileMode.Open))
        {
                // then I can Get data and display results.                
        }
    return null;
    }