Skip to content

Commit

Permalink
feat: Add default analytics hooks.
Browse files Browse the repository at this point in the history
  • Loading branch information
jeanplevesque committed Nov 29, 2023
1 parent ab943dd commit 812f459
Show file tree
Hide file tree
Showing 12 changed files with 315 additions and 10 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)

Prefix your items with `(Template)` if the change is about the template and not the resulting application.

## 2.2.X
- Added hooks for default analytics (page views, content loads, and command executions).

## 2.1.X
- Install `GooseAnalyzers` to enable the `SA1600` rule with its scope limited to interfaces and improve xml documentation.
- Replace local `DispatcherQueue` extension methods with the ones from the WinUI and Uno.WinUI Community Toolkit.
Expand Down
5 changes: 5 additions & 0 deletions doc/Architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ This application uses [FluentValidation](https://www.nuget.org/packages/FluentVa

See [Validation.md](Validation.md) for more details.

### Analytics
This application has a built-in analytics base that can be used to track events and errors with potentially any analytics service (e.g. AppCenter, Firebase, Segment, etc.). This base is built around the [IAnalyticsSink](../src/app/ApplicationTemplate.Presentation/Framework/Analytics/IAnalyticsSink.cs) interface.

See [DefaultAnalytics.md](DefaultAnalytics.md) for more details.

## View

### UI Framework
Expand Down
26 changes: 26 additions & 0 deletions doc/DefaultAnalytics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Default Analytics

This application comes with a few default tracked events.
They can be found in the [IAnalyticsSink](../src/app/ApplicationTemplate.Presentation/Framework/Analytics/IAnalyticsSink.cs) interface.
The idea is that you would change the implementation of this interface to send the events to an analytics service (such as AppCenter, Firebase, Segment, etc.).

Here is a list of the default events:

## Page Views
This is based on the changes of state from the `ISectionsNavigator`.

The `ISectionsNavigator` controls the navigation of the application. It's state can be observed and this is leveraged to detect the page views.

## Content Loads
This is based on the default builder of the `IDataLoaderFactory`.

The `IDataLoaderBuilder` allows to customize the default behavior or all DataLoaders. This is leveraged to inject analytics on successful and failed loads.

Content loads are different than page views because a single page view can be associated with multiple content loads.

## Command Executions
This is based on the default builder of the `IDynamicCommandBuilderFactory`.

The `IDynamicCommandBuilder` allows to customize the default behavior or all DynamicCommands. This is leveraged to inject analytics on successful and failed command executions.

Command executions are typically associated with button presses and gestures.
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace ApplicationTemplate.Presentation;

public static class AnalyticsConfiguration
{
/// <summary>
/// Adds the analytics services to the <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The service collection.</param>
public static IServiceCollection AddAnalytics(this IServiceCollection services)
{
return services.AddSingleton<IAnalyticsSink, AnalyticsSink>();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ApplicationTemplate.Presentation;
using Chinook.DataLoader;
using Chinook.DynamicMvvm;
using Chinook.DynamicMvvm.Implementations;
Expand Down Expand Up @@ -41,6 +42,7 @@ private static IServiceCollection AddDynamicCommands(this IServiceCollection ser
new DynamicCommandBuilderFactory(c => c
.CatchErrors(s.GetRequiredService<IDynamicCommandErrorHandler>())
.WithLogs(s.GetRequiredService<ILogger<IDynamicCommand>>())
.WithStrategy(new AnalyticsCommandStrategy(s.GetRequiredService<IAnalyticsSink>(), c.ViewModel))
.WithStrategy(new RaiseCanExecuteOnDispatcherCommandStrategy(c.ViewModel))
.DisableWhileExecuting()
.OnBackgroundThread()
Expand All @@ -62,8 +64,8 @@ private static IServiceCollection AddDataLoaders(this IServiceCollection service
.OnBackgroundThread()
.WithEmptySelector(GetIsEmpty)
.WithAnalytics(
onSuccess: async (ct, request, value) => { /* Some analytics */ },
onError: async (ct, request, error) => { /* Somme analytics */ }
onSuccess: async (ct, request, value) => s.GetRequiredService<IAnalyticsSink>().TrackDataLoaderSuccess(request, value),
onError: async (ct, request, error) => s.GetRequiredService<IAnalyticsSink>().TrackDataLoaderFailure(request, error)
)
.WithLoggedErrors(s.GetRequiredService<ILogger<IDataLoader>>())
);
Expand Down
16 changes: 12 additions & 4 deletions src/app/ApplicationTemplate.Presentation/CoreStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ protected override IHostBuilder InitializeServices(IHostBuilder hostBuilder, str
.AddLocalization()
.AddReviewServices()
.AddAppServices()
.AddAnalytics()
);
}

Expand All @@ -70,13 +71,10 @@ protected override async Task StartServices(IServiceProvider services, bool isFi
if (isFirstStart)
{
// TODO: Start your core services and customize the initial navigation logic here.

StartAutomaticAnalyticsCollection(services);
await services.GetRequiredService<IReviewService>().TrackApplicationLaunched(CancellationToken.None);

NotifyUserOnSessionExpired(services);

services.GetRequiredService<DiagnosticsCountersService>().Start();

await ExecuteInitialNavigation(CancellationToken.None, services);
}
}
Expand Down Expand Up @@ -119,6 +117,16 @@ public static async Task ExecuteInitialNavigation(CancellationToken ct, IService
services.GetRequiredService<IExtendedSplashscreenController>().Dismiss();
}

private void StartAutomaticAnalyticsCollection(IServiceProvider services)
{
var analyticsSink = services.GetRequiredService<IAnalyticsSink>();
var sectionsNavigator = services.GetRequiredService<ISectionsNavigator>();
sectionsNavigator
.ObserveCurrentState()
.Subscribe(analyticsSink.TrackNavigation)
.DisposeWith(Disposables);
}

private void NotifyUserOnSessionExpired(IServiceProvider services)
{
var authenticationService = services.GetRequiredService<IAuthenticationService>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Chinook.DataLoader;
using Chinook.DynamicMvvm;
using Chinook.SectionsNavigation;
using Chinook.StackNavigation;
using Microsoft.Extensions.Logging;

namespace ApplicationTemplate.Presentation;

public class AnalyticsSink : IAnalyticsSink
{
private readonly ILogger<AnalyticsSink> _logger;
private INavigableViewModel? _lastViewModel;

public AnalyticsSink(ILogger<AnalyticsSink> logger)
{
_logger = logger;
}

public void TrackNavigation(SectionsNavigatorState navigatorState)
{
if (navigatorState.LastRequestState != NavigatorRequestState.Processed)
{
// Skip the requests that are still processing of that failed to process.
return;
}

// Get the actual ViewModel instance.
// This allows to track based on instances and not types (because there are scenarios where you can open the same page multiple times with different parameters).
// Having the instance also allows casting into more specific types to get more information, such as navigation parameters, that could be relevant for analytics.
var viewModel = navigatorState.GetActiveStackNavigator().State.Stack.LastOrDefault()?.ViewModel;
if (viewModel is null || _lastViewModel == viewModel)
{
return;
}

// Gather analytics data.
var pageName = viewModel.GetType().Name.Replace("ViewModel", string.Empty, StringComparison.OrdinalIgnoreCase);
var isInModal = navigatorState.ActiveModal != null;
var sectionName = navigatorState.ActiveSection.Name;

// Send the analytics event.
SendPageView(pageName, isInModal, sectionName);

// Capture the last ViewModel instance to avoid duplicate events in the future.
_lastViewModel = viewModel;
}

private void SendPageView(string pageName, bool isInModal, string sectionName)
{
// TODO: Implement page views using a real analytics provider.
if (!_logger.IsEnabled(LogLevel.Information))
{
return;
}

if (isInModal)
{
_logger.LogInformation("Viewed page '{PageName}' in modal.", pageName);
}
else
{
_logger.LogInformation("Viewed page '{PageName}' in section '{SectionName}'.", pageName, sectionName);
}
}

public void TrackDataLoaderSuccess(IDataLoaderRequest request, object value)
{
// TODO: Implement data loaded events using a real analytics provider.
if (!_logger.IsEnabled(LogLevel.Information))
{
return;
}

var dataLoaderName = request.Context.GetDataLoaderName();
if (request.Context.TryGetValue("IsForceRefreshing", out var isForceRefreshing) && isForceRefreshing is true)
{
_logger.LogInformation("Refreshed content '{DataLoaderName}'.", dataLoaderName);
}
else
{
_logger.LogInformation("Loaded content '{DataLoaderName}'.", dataLoaderName);
}
}

public void TrackDataLoaderFailure(IDataLoaderRequest request, Exception exception)
{
// TODO: Implement data loaded events using a real analytics provider.
if (!_logger.IsEnabled(LogLevel.Information))
{
return;
}

var dataLoaderName = request.Context.GetDataLoaderName();
if (request.Context.TryGetValue("IsForceRefreshing", out var isForceRefreshing) && isForceRefreshing is true)
{
_logger.LogInformation("Failed to refresh content '{DataLoaderName}'.", dataLoaderName);
}
else
{
_logger.LogInformation("Failed to load content '{DataLoaderName}'.", dataLoaderName);
}
}

public void TrackCommandSuccess(string commandName, object? commandParameter, WeakReference<IViewModel>? viewModel)
{
// TODO: Implement command execution events using a real analytics provider.
if (!_logger.IsEnabled(LogLevel.Information))
{
return;
}

if (viewModel?.TryGetTarget(out var vm) ?? false)
{
_logger.LogInformation("Executed command '{CommandName}' from ViewModel '{ViewModelName}'.", commandName, vm.Name);
}
else
{
_logger.LogInformation("Executed command '{CommandName}'.", commandName);
}
}

public void TrackCommandFailure(string commandName, object? commandParameter, WeakReference<IViewModel>? viewModel, Exception exception)
{
// TODO: Implement command execution events using a real analytics provider.
if (!_logger.IsEnabled(LogLevel.Information))
{
return;
}

if (viewModel?.TryGetTarget(out var vm) ?? false)
{
_logger.LogInformation("Failed to execute command '{CommandName}' from ViewModel '{ViewModelName}'.", commandName, vm.Name);
}
else
{
_logger.LogInformation("Failed to execute command '{CommandName}'.", commandName);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Chinook.DynamicMvvm;

namespace ApplicationTemplate.Presentation;

/// <summary>
/// This <see cref="IDynamicCommandStrategy"/> tracks the success and failure of a command for analytics purposes.
/// </summary>
public class AnalyticsCommandStrategy : DelegatingCommandStrategy
{
private readonly IAnalyticsSink _analyticsSink;
private readonly WeakReference<IViewModel> _viewModel;

public AnalyticsCommandStrategy(IAnalyticsSink analyticsSink, IViewModel viewModel)
{
_analyticsSink = analyticsSink;
_viewModel = new WeakReference<IViewModel>(viewModel);
}

public override async Task Execute(CancellationToken ct, object parameter, IDynamicCommand command)
{
try
{
await base.Execute(ct, parameter, command);

_analyticsSink.TrackCommandSuccess(command.Name, parameter, _viewModel);
}
catch (Exception e)
{
_analyticsSink.TrackCommandFailure(command.Name, parameter, _viewModel, e);

throw;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Chinook.DataLoader;
using Chinook.DynamicMvvm;
using Chinook.SectionsNavigation;

namespace ApplicationTemplate.Presentation;

/// <summary>
/// This service collects raw analytics data from the application and processes it to send to an analytics provider (such as AppCenter, Firebase, Segment, etc.).
/// </summary>
public interface IAnalyticsSink
{
/// <summary>
/// Tracks a navigation event from which to derive page views.
/// </summary>
/// <param name="navigatorState">The state of the navigator.</param>
void TrackNavigation(SectionsNavigatorState navigatorState);

/// <summary>
/// Tracks a successful data loader request.
/// </summary>
/// <param name="request">The request that was successful.</param>
/// <param name="value">The value that was successfully loaded.</param>
void TrackDataLoaderSuccess(IDataLoaderRequest request, object value);

/// <summary>
/// Tracks a failed data loader request.
/// </summary>
/// <param name="request">The request that failed.</param>
/// <param name="exception">The exception produced.</param>
void TrackDataLoaderFailure(IDataLoaderRequest request, Exception exception);

/// <summary>
/// Tracks a successful command execution.
/// </summary>
/// <param name="commandName">The name of the command.</param>
/// <param name="commandParameter">The optional command parameter.</param>
/// <param name="viewModel">An optional weak reference to the ViewModel owning the command.</param>
void TrackCommandSuccess(string commandName, object? commandParameter, WeakReference<IViewModel>? viewModel);

/// <summary>
/// Tracks a failed command execution.
/// </summary>
/// <param name="commandName">The name of the command.</param>
/// <param name="commandParameter">The optional command parameter.</param>
/// <param name="viewModel">An optional weak reference to the ViewModel owning the command.</param>
/// <param name="exception">The exception produced.</param>
void TrackCommandFailure(string commandName, object? commandParameter, WeakReference<IViewModel>? viewModel, Exception exception);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace Chinook.SectionsNavigation;

public static class SectionsNavigatorStateExtensions
{
public static Type GetViewModelType(this SectionsNavigatorState sectionsNavigatorState)
public static Type GetCurrentOrNextViewModelType(this SectionsNavigatorState sectionsNavigatorState)
{
switch (sectionsNavigatorState.LastRequestState)
{
Expand Down
Loading

0 comments on commit 812f459

Please sign in to comment.