public static async Task <bool> Run([TimerTrigger(AvailabilityTestInterval.Minute01)] TimerInfo notUsed, ILogger log) { log.LogInformation($"**Availability func executed at: {DateTime.Now}"); string responseContent; using (HttpClient http = AvailabilityTest.NewHttpClient()) { using (HttpResponseMessage response = await http.GetAsync("https://availabilitymonitoring-extension-monitoredappsample.azurewebsites.net/Home/MonitoredPage")) { HttpResponseMessage httpResponseMessage = response.EnsureSuccessStatusCode(); log.LogInformation($"**httpResponseMessage:" + httpResponseMessage.Content.ToString()); responseContent = await response.Content.ReadAsStringAsync(); } } bool hasExpectedContent = responseContent.Contains("<title>Monitored Page</title>", StringComparison.OrdinalIgnoreCase) && responseContent.Contains("(App Version Id: 2)", StringComparison.OrdinalIgnoreCase); log.LogInformation($"**hasExpectedContent?" + hasExpectedContent.ToString()); //AvailabilityTelemetry result = testInfo.DefaultAvailabilityResult; //result.Properties["UserProperty"] = "User Value"; //result.Success = hasExpectedContent; //return result; return(hasExpectedContent); }
public static async Task <AvailabilityTelemetry> Run( [TimerTrigger(AvailabilityTestInterval.Minute01)] TimerInfo notUsed, //[TimerTrigger("*/5 * * * * *")] TimerInfo timerInfo, [AvailabilityTestInfo] AvailabilityTestInfo testInfo, ILogger log) { log.LogInformation($"[CatDemo-ExplicitlySpecifyConfig] Run(..): C# Coded Availability Test Function executed at: {DateTime.Now}." + $" ActivitySpanId = \"{Activity.Current.SpanId.ToHexString() ?? "null"}\";" + $" TestDisplayName = \"{testInfo.TestDisplayName ?? "null"}\";" + $" LocationDisplayName = \"{testInfo.LocationDisplayName ?? "null"}\";" + $" LocationId = \"{testInfo.LocationId ?? "null"}\"."); string responseContent; using (HttpClient http = AvailabilityTest.NewHttpClient()) { using (HttpResponseMessage response = await http.GetAsync("https://availabilitymonitoring-extension-monitoredappsample.azurewebsites.net/Home/MonitoredPage")) { response.EnsureSuccessStatusCode(); responseContent = await response.Content.ReadAsStringAsync(); } } bool hasExpectedContent = responseContent.Contains("<title>Monitored Page</title>", StringComparison.OrdinalIgnoreCase) && responseContent.Contains("(App Version Id: 2)", StringComparison.OrdinalIgnoreCase); AvailabilityTelemetry result = testInfo.DefaultAvailabilityResult; result.Properties["UserProperty"] = "User Value"; result.Success = hasExpectedContent; return(result); }
public static async Task <bool> Run( [TimerTrigger(AvailabilityTestInterval.Minute01)] TimerInfo notUsed, ILogger log) { // User-specified test parameters: string monitoredApiUrl = "http://availabilitymonitoring-extension-monitoredappsample02.azurewebsites.net/api/Time?source=CatMonitoredApiIsAvailable"; HttpMethod httpMethod = HttpMethod.Get; KeyValuePair <string, string>[] headers = new KeyValuePair <string, string>[] { }; string payload = null; TimeSpan overallTimeout = TimeSpan.FromSeconds(30); // Needs to be set for the result: bool isAvailabilityTestSuccessful; // Initialize an HTTP client and set default headers: using (var timeoutController = new CancellationTokenSource(overallTimeout)) using (HttpClient http = AvailabilityTest.NewHttpClient()) { CancellationToken timeoutControl = timeoutController.Token; // Run the request and get the response: using (HttpResponseMessage response = await ExecuteRequestAsync(http, monitoredApiUrl, httpMethod, headers, payload, log, timeoutControl)) { isAvailabilityTestSuccessful = await ValidateResponseAsync(response, log, timeoutControl); } } return(isAvailabilityTestSuccessful); }
public static async Task <bool> Run( [TimerTrigger(AvailabilityTestInterval.Minute01)] TimerInfo notUsed, ILogger log) { log.LogInformation($"[CatDemo-SimpleBinding] Run(..): C# Coded Availability Test Function executed at: {DateTime.Now}." + $" ActivitySpanId = \"{Activity.Current.SpanId.ToHexString() ?? "null"}\"."); string responseContent; using (HttpClient http = AvailabilityTest.NewHttpClient()) { using (HttpResponseMessage response = await http.GetAsync("https://availabilitymonitoring-extension-monitoredappsample.azurewebsites.net/Home/MonitoredPage")) { response.EnsureSuccessStatusCode(); responseContent = await response.Content.ReadAsStringAsync(); } } bool hasExpectedContent = responseContent.Contains("<title>Monitored Page</title>", StringComparison.OrdinalIgnoreCase) && responseContent.Contains("(App Version Id: 2)", StringComparison.OrdinalIgnoreCase); return(hasExpectedContent); }
// Types 'FunctionExecutingContext' and 'IFunctionFilter' (and other Filter-related types) are marked as preview/obsolete, // but the guidance from the Azure Functions team is to use it, so we disable the warning. #pragma warning disable CS0618 public Task OnExecutingAsync(FunctionExecutingContext executingContext, CancellationToken cancelControl) #pragma warning restore CS0618 { Validate.NotNull(executingContext, nameof(executingContext)); // Grab the invocation id and the logger: Guid functionInstanceId = executingContext.FunctionInstanceId; ILogger log = executingContext.Logger; // Check if this is an Availability Test. // There are 3 cases: // 1) This IS an Availability Test and this is an in-proc/.Net functuion: // This filter runs AFTER the bindings. // The current function was already registered, becasue the attribute binding was already executed. // 2) This IS an Availability Test and this is an out-of-proc/non-.Net function: // This filter runs BEFORE the bindings. // a) If this is the first time the filter runs for the current function, TryGetTestConfig(..) will // read the metadata file, extract the config and return True. // b) If this is not the first time, the function is already registered as described in (a). // 3) This is NOT an Availability Test: // We will get False here and do nothing. bool isAvailabilityTest = _availabilityTestRegistry.Functions.IsAvailabilityTest(executingContext, out string functionName, out IAvailabilityTestConfiguration testConfig); if (!isAvailabilityTest) { if (log != null) { using (log.BeginScope(LogMonikers.Scopes.CreateForTestInvocation(functionName))) { log.LogDebug($"Availability Test Pre-Function routine was invoked and determned that this function is NOT an Availability Test:" + " {{FunctionName=\"{FunctionName}\", FunctionInstanceId=\"{FunctionInstanceId}\"}}", functionName, functionInstanceId); } } return(Task.CompletedTask); } // If configured, use a fall-back logger: log = AvailabilityTest.Log.CreateFallbackLogIfRequired(log); IReadOnlyDictionary <string, object> logScopeInfo = LogMonikers.Scopes.CreateForTestInvocation(functionName); using (log.BeginScopeSafe(logScopeInfo)) { log?.LogDebug($"Availability Test Pre-Function routine was invoked:" + " {{FunctionName=\"{FunctionName}\", FunctionInstanceId=\"{FunctionInstanceId}\"," + " TestConfiguration={{TestDisplayNameTemplate=\"{TestDisplayNameTemplate}\" }} }}", functionName, functionInstanceId, testConfig.TestDisplayName); // - In case (1) described above, we have already registered this invocation: // The function parameters have been instantiated, and attached to the invocationState. // However, the parameters are NOT yet initialized, as we did not have a AvailabilityTestScope instance yet. // We will set up an AvailabilityTestScope and attach it to the invocationState. // Then we will initialize the parameters using data from that scope. // - In case (2) described above, we have not yet registered the invocation: // A new invocationState will end up being created now. // We will set up an AvailabilityTestScope and attach it to the invocationState. // Subsequently, when the binings eventually get invoked by the Functions tuntime, // they will instantiate and initialize the parameters using data from that scope. // Get the invocation state bag: AvailabilityTestInvocationState invocationState = _availabilityTestRegistry.Invocations.GetOrRegister(functionInstanceId, log); // If test configuration makes reference to configuration, resolve the settings IAvailabilityTestInternalConfiguration resolvedTestConfig = _availabilityTestScopeSettingsResolver.Resolve(testConfig, functionName); // Start the availability test scope (this will start timers and set up the activity span): AvailabilityTestScope testScope = AvailabilityTest.StartNew(resolvedTestConfig, _telemetryConfiguration, flushOnDispose: true, log, logScopeInfo); invocationState.AttachTestScope(testScope); // If we have previously instantiated a result collector, initialize it now: if (invocationState.TryGetResultCollector(out AvailabilityResultAsyncCollector resultCollector)) { resultCollector.Initialize(testScope); } // If we have previously instantiated a test info, initialize it now: if (invocationState.TryGetTestInfos(out IEnumerable <AvailabilityTestInfo> testInfos)) { AvailabilityTestInfo model = testScope.CreateAvailabilityTestInfo(); foreach (AvailabilityTestInfo testInfo in testInfos) { testInfo.CopyFrom(model); } } } return(Task.CompletedTask); }