Skip to content

Commit

Permalink
Transition library to .NET Core (baseline netstandard2.0/netcoreapp2.1)
Browse files Browse the repository at this point in the history
  • Loading branch information
maartenba committed Mar 26, 2020
1 parent a617c1f commit 716f3ea
Show file tree
Hide file tree
Showing 162 changed files with 25,483 additions and 2,357 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Expand Up @@ -15,4 +15,5 @@
obj/
bin/
*.suo
*.user
*.user
.idea/*
Binary file not shown.
28 changes: 28 additions & 0 deletions Directory.Build.targets
@@ -0,0 +1,28 @@
<Project>
<PropertyGroup>
<LangVersion>7.3</LangVersion>
<Nullable>disable</Nullable>

<!-- NuGet -->
<IncludeSymbols>True</IncludeSymbols>
<IncludeSource>True</IncludeSource>

<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>GoogleAnalyticsTracker.snk</AssemblyOriginatorKeyFile>
<DelaySign>false</DelaySign>

<Description>GoogleAnalyticsTracker - A C# library for tracking Google Analytics.</Description>
<Authors>Maarten Balliauw and contributors</Authors>
<Copyright>Maarten Balliauw and contributors</Copyright>
<PackageProjectUrl>https://github.com/maartenba/GoogleAnalyticsTracker</PackageProjectUrl>
<RepositoryUrl>https://github.com/maartenba/GoogleAnalyticsTracker</RepositoryUrl>
<RepositoryType>Git</RepositoryType>
<PackageTags>google analytics ga mvc api rest client tracker stats statistics track usage feature telemetry</PackageTags>
<PackageLicenseExpression>MS-PL</PackageLicenseExpression>

<PublishRepositoryUrl>true</PublishRepositoryUrl>
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>

<Product>GoogleAnalyticsTracker</Product>
</PropertyGroup>
</Project>
108 changes: 108 additions & 0 deletions GoogleAnalyticsTracker.AspNetCore/AspNetCoreTracker.cs
@@ -0,0 +1,108 @@
using System;
using System.Threading.Tasks;
using GoogleAnalyticsTracker.Core;
using GoogleAnalyticsTracker.Core.Interface;
using GoogleAnalyticsTracker.Core.TrackerParameters;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;

namespace GoogleAnalyticsTracker.AspNet
{
[PublicAPI]
public class AspNetCoreTracker : TrackerBase
{
private readonly IHttpContextAccessor _contextAccessor;

private static IAnalyticsSession SetupAnalyticsSession(
IHttpContextAccessor contextAccessor,
IOptions<GoogleAnalyticsTrackerOptions> optionsAccessor)
{
var session = new CookieBasedAnalyticsSession(contextAccessor);
optionsAccessor.Value.CustomizeAnalyticsSession?.Invoke(session);
return session;
}

private static ITrackerEnvironment SetupTrackerEnvironment(
IOptions<GoogleAnalyticsTrackerOptions> optionsAccessor)
{
var trackerEnvironment = new AspNetCoreTrackerEnvironment();
optionsAccessor.Value.CustomizeTrackerEnvironment?.Invoke(trackerEnvironment);
return trackerEnvironment;
}

public AspNetCoreTracker(
[NotNull] IHttpContextAccessor contextAccessor,
IOptions<GoogleAnalyticsTrackerOptions> optionsAccessor)
: base(
optionsAccessor.Value.TrackerId,
SetupAnalyticsSession(contextAccessor, optionsAccessor),
SetupTrackerEnvironment(optionsAccessor))
{
_contextAccessor = contextAccessor;
}

[UsedImplicitly]
public Task TrackEventAsync(Exception ex)
{
return TrackEventAsync("Errors", ex.Message, ex.HResult);
}

[UsedImplicitly]
public async Task TrackEventAsync(string category, string action, int value)
{
// If no HTTP context available, bail out...
if (_contextAccessor.HttpContext == null) return;

var eventTrackingParameters = new EventTracking
{
Category = category,
Action = action,
Label = GetRelativeUrl(),
Value = value,
DocumentHostName = _contextAccessor.HttpContext.Request.Host.Value,
UserAgent = _contextAccessor.HttpContext.Request.Headers["User-Agent"],
UserLanguage = _contextAccessor.HttpContext.Request.Headers["Accept-Language"],
DocumentReferrer = _contextAccessor.HttpContext.Request.Headers["Referrer"],
IpOverride = Environment.GetEnvironmentVariable("server.RemoteIpAddress"),
UserId = _contextAccessor.HttpContext.User.Identity.Name
};

await TrackAsync(eventTrackingParameters);
}

[UsedImplicitly]
public Task TrackPageViewAsync()
{
return TrackPageViewAsync(null);
}

[UsedImplicitly]
public async Task TrackPageViewAsync([CanBeNull] string customTitle)
{
// If no HTTP context available, bail out...
if (_contextAccessor.HttpContext == null) return;

var pageviewTrackingParameters = new PageView
{
DocumentTitle = customTitle ?? _contextAccessor.HttpContext.Request.Path.ToString(),
DocumentLocationUrl = GetRelativeUrl(),
DocumentHostName = _contextAccessor.HttpContext.Request.Host.Value,
UserAgent = _contextAccessor.HttpContext.Request.Headers["User-Agent"],
UserLanguage = _contextAccessor.HttpContext.Request.Headers["Accept-Language"],
DocumentReferrer = _contextAccessor.HttpContext.Request.Headers["Referrer"],
IpOverride = Environment.GetEnvironmentVariable("server.RemoteIpAddress"),
UserId = _contextAccessor.HttpContext.User.Identity.Name,
};

await TrackAsync(pageviewTrackingParameters);
}

private string GetRelativeUrl()
{
return string.IsNullOrEmpty(_contextAccessor.HttpContext.Request.QueryString.ToString())
? _contextAccessor.HttpContext.Request.Path.ToString()
: string.Format("{0}{1}", _contextAccessor.HttpContext.Request.Path, _contextAccessor.HttpContext.Request.QueryString);
}
}
}
@@ -1,32 +1,28 @@
using System;
using System;
using System.Net;
using GoogleAnalyticsTracker.Core.Interface;
using Microsoft.Owin;
using JetBrains.Annotations;

namespace GoogleAnalyticsTracker.Owin
namespace GoogleAnalyticsTracker.AspNet
{
/// <summary>An owin tracker environment.</summary>
public class OwinTrackerEnvironment : ITrackerEnvironment
/// <summary>An ASP.NET Core tracker environment.</summary>
[PublicAPI]
public class AspNetCoreTrackerEnvironment : ITrackerEnvironment
{
// ReSharper disable once NotAccessedField.Local
private readonly IOwinContext _context;

/// <summary>
/// Initializes a new instance of the OwinTrackerEnvironment class.
/// Initializes a new instance of the AspNetTrackerEnvironment class.
/// </summary>
/// <param name="context">The context.</param>
public OwinTrackerEnvironment(IOwinContext context)
public AspNetCoreTrackerEnvironment()
{
_context = context;

Hostname = Dns.GetHostName();
OsPlatform = Environment.OSVersion.Platform.ToString();
OsPlatform = Environment.OSVersion.Platform.ToString();
OsVersion = Environment.OSVersion.Version.ToString();
OsVersionString = Environment.OSVersion.VersionString;
}

/// <summary>Gets or sets the hostname.</summary>
/// <value>The hostname.</value>
// ReSharper disable once MemberCanBePrivate.Global
public string Hostname { get; set; }

/// <summary>Gets or sets the operating system platform.</summary>
Expand Down
51 changes: 51 additions & 0 deletions GoogleAnalyticsTracker.AspNetCore/AspNetCoreTrackerExtensions.cs
@@ -0,0 +1,51 @@
using System.Threading.Tasks;
using GoogleAnalyticsTracker.Core;
using GoogleAnalyticsTracker.Core.TrackerParameters;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;

namespace GoogleAnalyticsTracker.AspNet
{
[PublicAPI]
public static class AspNetCoreTrackerExtensions
{
public static async Task<TrackingResult> TrackUserTimingAsync(this AspNetCoreTracker tracker, HttpContext httpContext, string pageTitle, string pageUrl, string category, string var, long value, string label = null)
{
var userTimingParameters = new UserTimings
{
DocumentTitle = pageTitle,
DocumentLocationUrl = pageUrl,
UserAgent = httpContext.Request.Headers[HeaderNames.UserAgent].ToString(),
DocumentHostName = httpContext.Request.Host.Value,
UserLanguage = httpContext.Request.Headers[HeaderNames.AcceptLanguage].ToString().ToLower(),
UserTimingCategory = category,
UserTimingVariable = var,
UserTimingTime = value,
UserTimingLabel = label,
};

return await tracker.TrackAsync(userTimingParameters);
}

public static async Task<TrackingResult> TrackPageViewAsync(this AspNetCoreTracker tracker, HttpContext httpContext, string pageTitle, string pageUrl = null)
{
if (pageUrl == null)
{
pageUrl = httpContext.Request.Path;
}

var pageViewParameters = new PageView
{
DocumentTitle = pageTitle,
DocumentLocationUrl = pageUrl,
UserAgent = httpContext.Request.Headers[HeaderNames.UserAgent].ToString(),
DocumentHostName = httpContext.Request.Host.Value,
UserLanguage = httpContext.Request.Headers[HeaderNames.AcceptLanguage].ToString().ToLower(),
IpOverride = httpContext.Connection.RemoteIpAddress.ToString()
};

return await tracker.TrackAsync(pageViewParameters);
}
}
}

0 comments on commit 716f3ea

Please sign in to comment.