Azure Function Timer Trigger Function.cs content

The content here is colated from hours of deep diving documentation along with numerous technical support calls with Microsoft, to derive the final product shown below. Hopefully by grabbing this content, I have saved you weeks of effort.

Obviously you need to edit the internal ip address and your timer interval.

Replace your function.cs with the following:

using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

namespace AllenTimeTriggerFunctionApp1
{
public class Function1
{
private TelemetryClient telemetryClient;

    /// Using dependency injection will guarantee that you use the same configuration for telemetry collected automatically and manually. <summary>

    public Function1(TelemetryConfiguration telemetryConfiguration)
    {
        telemetryClient = new TelemetryClient(telemetryConfiguration);
    }

    [FunctionName("Function2")]
    public async Task Run([TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, ExecutionContext context, ILogger log)
    {
        if (telemetryClient == null)
        {
            // Initializing a telemetry configuration for Application Insights based on connection string 

            var telemetryConfiguration = new TelemetryConfiguration();
            telemetryConfiguration.ConnectionString = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING");
            telemetryConfiguration.TelemetryChannel = new InMemoryChannel();
            telemetryClient = new TelemetryClient(telemetryConfiguration);
        }

        string testName = context.FunctionName;
        string location = Environment.GetEnvironmentVariable("REGION_NAME");

        var availability = new AvailabilityTelemetry
        {
            Name = testName,

            RunLocation = location,

            Success = false,
        };

        availability.Context.Operation.ParentId = Activity.Current.SpanId.ToString();
        availability.Context.Operation.Id = Activity.Current.RootId;

        var stopwatch = new Stopwatch();
        stopwatch.Start();

        try
        {
            using (var activity = new Activity("AvailabilityContext"))
            {
                activity.Start();
                availability.Id = Activity.Current.SpanId.ToString();
                // Run business logic 
                await RunAvailabilityTestAsync(log);
            }
            availability.Success = true;
        }

        catch (Exception ex)
        {
            availability.Message = ex.Message;
            throw;
        }

        finally
        {
            stopwatch.Stop();
            availability.Duration = stopwatch.Elapsed;
            availability.Timestamp = DateTimeOffset.UtcNow;

            telemetryClient.TrackAvailability(availability);
            telemetryClient.Flush();
        }
    }
    public async static Task RunAvailabilityTestAsync(ILogger log)
    {
        string server_url = Environment.GetEnvironmentVariable("SERVER_URL");
        using (var httpClient = new HttpClient())
        {
            // TODO: Replace with your business logic 
            //await httpClient.GetStringAsync(server_url);
            // await httpClient.GetByteArrayAsync(server_url);
            await httpClient.GetAsync("http://10.0.1.5");
        }
    }
}

}

Replace your local.settings.json with the following:

{
“IsEncrypted”: false,
“Values”: {
“AzureWebJobsStorage”: “UseDevelopmentStorage=true”,
“FUNCTIONS_WORKER_RUNTIME”: “dotnet”,
“APPLICATIONINSIGHTS_CONNECTION_STRING”: “InstrumentationKey=b646541a-f5e3-0000-0000-ab0fdc3828c6;IngestionEndpoint=https://uaenorth-0.in.applicationinsights.azure.com/;LiveEndpoint=https://uaenorth.livediagnostics.monitor.azure.com/”,
“REGION_NAME”: “uaenorth”,
“SERVER_URL”: “http://10.0.1.5/”
}
}

2 comments

Leave a comment

Your email address will not be published. Required fields are marked *