1

I have written a azure webjob which has timerTrigger. The static method gets called every minute and it has to make http POST request. I want to access the appSettings.json file within the timerTrigger static method. How can I access it?

I see examples where static method for QueueTrigger have ExecutionContext and TextWriter as parameters. Please see below example:

    public static void ProcessOrder(
    [QueueTrigger("orders")] Order order,
    TextWriter log,
    ExecutionContext context)
{
    log.WriteLine("InvocationId: {0}", context.InvocationId);
}

How can I inject similar current execution context and TextWriter logger into my timerTrigger static method - "TimerTick"? Below is my TimerTrigger static method :

        public class Test
        {
            private static IConfiguration _config;
            private static IHttpHandler _httpHandler;
            public Test(IConfiguration configuration, IHttpHandler httpHandler)
            {
                _config = configuration;
                _httpHandler = httpHandler;
            }

      [Singleton]
            public static void TimerTick([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer)
            {
                string baseUrl = _config?.GetSection("WebJobConfiguration:url")?.Value;
                string API = _config.GetSection("WebJobConfiguration:API")?.Value;
                Console.WriteLine("URL: " + baseUrl + API);
                _httpHandler.PostAsync(baseUrl + API, null);
            }
}

======================================================================= Updating the question:

I updated the method which has TimerTrigger to be:

public async static Task TriggerNotification([TimerTrigger("%Job%")]TimerInfo myTimer, ExecutionContext context)
    {....}

Reading the %Job% from config file using NameResolver.

When I try to pass the current execution context within TriggerNotification method, I get the following error: enter image description here

How can I solve this?

The webjob is configured using HostBuilder. Below is the code. I'm using Azure webjob version 3.0.3.

 static void Main(string[] args)
    {
        try
        {
            var builder = new HostBuilder()
                    .ConfigureAppConfiguration(SetupConfiguration)
                    .ConfigureLogging(SetupLogging)
                    .ConfigureServices(SetupServices)
                    .ConfigureWebJobs(webJobConfiguration =>
                    {
                        webJobConfiguration.AddTimers();
                        webJobConfiguration.AddAzureStorageCoreServices(); 
                    })
                    .UseSerilog()
                .Build();
            builder.Run();
        } catch { ... }

}

user2439903
  • 1,277
  • 2
  • 34
  • 68

1 Answers1

4

I want to access the appSettings.json file within the timerTrigger static method. How can I access it?

I used Microsoft.Extensions.Configuration.Json to implement it, in most situation we use this package to configure settings in Json . And I tried it could be used to read json. And here is complete code. You could have a try.

public static void Run([TimerTrigger("0 */1 * * * *")] TimerInfo timer,
        ILogger logger)
    {
        logger.LogInformation("Doing some timely work ...");
        IConfigurationRoot configurationRoot = BuildConfiguration();
        string connectString= configurationRoot.GetSection("ConnectionStrings")["AzureWebJobsDashboard"];
        logger.LogInformation(connectString);


        // and other stuff .....
    }

    private static IConfigurationRoot BuildConfiguration()
    {
        var builder = new ConfigurationBuilder()
             .SetBasePath(Directory.GetCurrentDirectory())
             .AddJsonFile("appsettings.json");

        IConfigurationRoot configurationRoot = builder.Build();
        return configurationRoot;
    }

And you could show it in Logger. enter image description here

As for ExecutionContext, you could refer to this wiki, or you could go to official doc, it has examples about how to use it.

Hope this could help you , if you still have other questions, please let me know.

Update : The Program.cs pic.

enter image description here

George Chen
  • 13,703
  • 2
  • 11
  • 26
  • thanks for the answer. I added "ExecutionContext context" parameter in TimerTrigger method and never seems to work. I get an error. Can you please help me with how I can access executionContext within timerTrigger? – user2439903 Jan 16 '19 at 17:52
  • I have updated the question. Please check the code sample I have posted below the delimiter "===" – user2439903 Jan 17 '19 at 19:07
  • @user2439903, I tested the code and get the same code, then I found I miss something in Program.cs. You add config.UseCore(); then it will work. I will update the pic in my answer. – George Chen Jan 18 '19 at 02:25
  • @user2439903, any problem now? If my answer works, you could mark it as the answer. Thanks! – George Chen Jan 18 '19 at 08:39
  • I am using webjob 3.0.3 and can't find a method in hostBuilder which has UseCore(). I have updated the question with code snippet. Can you please tell me what is missing? – user2439903 Jan 18 '19 at 17:45
  • @user2439903, it's not about webjob 3.0.3, method, it's in Microsoft.Azure.WebJobs.Extensions, you could find its description in this official doc.https://learn.microsoft.com/en-us/azure/app-service/webjobs-sdk-how-to#usecore And you could find ExecutionContext is defined in this binding. But it binds to JobHostConfiguration and I don't find it's defined in HostBuilder. – George Chen Jan 21 '19 at 02:20
  • @user2439903, and i found in this answer config.UseXXX extension methods migrated to IHostBuilder builder.AddXXX methods. https://github.com/Azure/azure-webjobs-sdk/issues/1871#issuecomment-432347037Maybe you could try with it. – George Chen Jan 21 '19 at 03:05
  • @user2439903 , you could add AddExecutionContextBinding ib the hostbuilder. Check out: https://learn.microsoft.com/en-us/azure/app-service/webjobs-sdk-how-to#executioncontext – Koen van der Linden Sep 03 '19 at 13:18