Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add analytics page using Azure Application Insights and chart.js #341

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions PC2/Controllers/AnalyticsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.ApplicationInsights.DataContracts;
using System.Threading.Tasks;
using PC2.Data;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.Configuration;

namespace PC2.Controllers
{
[Authorize(Roles = IdentityHelper.Admin)]
public class AnalyticsController : Controller
{
private readonly TelemetryClient _telemetryClient;
private readonly IConfiguration _configuration;

public AnalyticsController(TelemetryClient telemetryClient, IConfiguration configuration)
{
_telemetryClient = telemetryClient;
_configuration = configuration;
}

public async Task<IActionResult> Index()
{
var pageViews = await GetHistoricalData("PageViews");
var uniqueVisitors = await GetHistoricalData("UniqueVisitors");
var sessionDuration = await GetHistoricalData("SessionDuration");
var bounceRate = await GetHistoricalData("BounceRate");

ViewData["PageViews"] = pageViews;
ViewData["UniqueVisitors"] = uniqueVisitors;
ViewData["SessionDuration"] = sessionDuration;
ViewData["BounceRate"] = bounceRate;

return View();
}

private async Task<double> GetMetricData(string metricName)
{
var request = new MetricTelemetry(metricName, 1);
_telemetryClient.TrackMetric(request);
return await Task.FromResult(request.Sum);
}

private async Task<JObject> GetHistoricalData(string metricName)
{
string connectionString = _configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];
string requestUri = $"https://api.applicationinsights.io/v1/apps/{_configuration["ApplicationInsightsAppId"]}/metrics/{metricName}";

using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("x-api-key", connectionString);

HttpResponseMessage response = await client.GetAsync(requestUri);
if (response.IsSuccessStatusCode)
{
string data = await response.Content.ReadAsStringAsync();
return JObject.Parse(data);
}
else
{
return null;
}
}
}
}
}
112 changes: 112 additions & 0 deletions PC2/Views/Analytics/Index.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
@{
ViewData["Title"] = "Analytics";
}

<h2>Analytics</h2>

<div>
<canvas id="pageViewsChart"></canvas>
</div>
<div>
<canvas id="uniqueVisitorsChart"></canvas>
</div>
<div>
<canvas id="sessionDurationChart"></canvas>
</div>
<div>
<canvas id="bounceRateChart"></canvas>
</div>

@section Scripts {
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
var pageViewsData = @Html.Raw(Json.Serialize(ViewData["PageViews"]));
var uniqueVisitorsData = @Html.Raw(Json.Serialize(ViewData["UniqueVisitors"]));
var sessionDurationData = @Html.Raw(Json.Serialize(ViewData["SessionDuration"]));
var bounceRateData = @Html.Raw(Json.Serialize(ViewData["BounceRate"]));

var ctxPageViews = document.getElementById('pageViewsChart').getContext('2d');
var pageViewsChart = new Chart(ctxPageViews, {
type: 'line',
data: {
labels: pageViewsData.times,
datasets: [{
label: 'Page Views',
data: pageViewsData.values,
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});

var ctxUniqueVisitors = document.getElementById('uniqueVisitorsChart').getContext('2d');
var uniqueVisitorsChart = new Chart(ctxUniqueVisitors, {
type: 'line',
data: {
labels: uniqueVisitorsData.times,
datasets: [{
label: 'Unique Visitors',
data: uniqueVisitorsData.values,
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});

var ctxSessionDuration = document.getElementById('sessionDurationChart').getContext('2d');
var sessionDurationChart = new Chart(ctxSessionDuration, {
type: 'line',
data: {
labels: sessionDurationData.times,
datasets: [{
label: 'Session Duration',
data: sessionDurationData.values,
borderColor: 'rgba(255, 206, 86, 1)',
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});

var ctxBounceRate = document.getElementById('bounceRateChart').getContext('2d');
var bounceRateChart = new Chart(ctxBounceRate, {
type: 'line',
data: {
labels: bounceRateData.times,
datasets: [{
label: 'Bounce Rate',
data: bounceRateData.values,
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
}
3 changes: 2 additions & 1 deletion PC2/Views/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ cfg: { // Application Insights Configuration
<li><a class="dropdown-item" asp-controller="About" asp-action="IndexSteeringCommittee">View Steering Committee</a></li>
<li><a class="dropdown-item" asp-controller="About" asp-action="CreateSteeringCommittee">Create Steering Committee Member</a></li>
<li><a class="dropdown-item" asp-controller="About" asp-action="UploadNewsletter">Upload Newsletter</a></li>
<li><a class="dropdown-item" asp-controller="Analytics" asp-action="Index">Analytics</a></li>
</ul>
</ul>
</div>
Expand Down Expand Up @@ -245,4 +246,4 @@ cfg: { // Application Insights Configuration
<script src="~/js/site.js" asp-append-version="true"></script>
@RenderSection("Scripts", required: false)
</body>
</html>
</html>
Loading