To create an Azure Application Insights real-time Power BI using the C# function, complete the following steps:
- Navigate to Azure Functions and create a new function using the following template:

- Click on C# in the preceding screenshot, provide the Name and click on the Create button, as shown in the following screenshot:

- Replace the default code with the following code. Make sure that you configure the right value for which the analytics query should pull the data. In my case, I have provided five minutes (5m) in the following code:
#r "Newtonsoft.Json"
using System.Configuration;
using System.Text;
using Newtonsoft.Json.Linq;
private const string AppInsightsApi =
"https://api.applicationinsights.io/beta/apps";
private const string RealTimePushURL = "PastethePushURLhere";
private static readonly string AiAppId =
ConfigurationManager.AppSettings["AI_APP_ID"];
private static readonly string AiAppKey =
ConfigurationManager.AppSettings["AI_APP_KEY"];
public static async Task Run(TimerInfo myTimer, TraceWriter
log)
{
if (myTimer.IsPastDue)
{
log.Warning($"[Warning]: Timer is running late! Last ran
at: {myTimer.ScheduleStatus.Last}");
}
await RealTimeFeedRun(
query: @"
requests
| where timestamp > ago(5m)
| summarize passed = countif(success == true),
total = count()
| project passed
",
log: log
);
log.Info($"Executing real-time Power BI run at:
{DateTime.Now}");
}
private static async Task RealTimeFeedRun( string query,
TraceWriter log)
{
log.Info($"Feeding Data to Power BI has started at:
{DateTime.Now}");
string requestId = Guid.NewGuid().ToString();
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("x-api-key",
AiAppKey);
httpClient.DefaultRequestHeaders.Add("x-ms-app",
"FunctionTemplate");
httpClient.DefaultRequestHeaders.Add("x-ms-client-
request-id", requestId);
string apiPath = $"{AppInsightsApi}/{AiAppId}/query?
clientId={requestId}×pan=P1D&query={query}";
using (var httpResponse = await
httpClient.GetAsync(apiPath))
{
httpResponse.EnsureSuccessStatusCode();
var resultJson = await
httpResponse.Content.ReadAsAsync<JToken>();
double result;
if (!double.TryParse(resultJson.SelectToken
("Tables[0].Rows[0][0]")?.ToString(), out result))
{
throw new FormatException("Query must result in a
single metric number. Try it on Analytics before
scheduling.");
}
string postData = $"[{{ "requests": "{result}"
}}]";
log.Verbose($"[Verbose]: Sending data: {postData}");
using (var response = await
httpClient.PostAsync(RealTimePushURL, new
ByteArrayContent(Encoding.UTF8.GetBytes(postData))))
{
log.Verbose($"[Verbose]: Data sent with response:
{response.StatusCode}");
}
}
}
}
The preceding code runs an Application Insights analytics query that pulls data for the last five minutes (requests) and pushes the data to the Power BI push URL. This process repeats continuously based on the timer frequency that you have configured.
- This is a screenshot that has a sequence of pictures showing the real-time data:
