maartenba / GoogleAnalyticsTracker

GoogleAnalyticsTracker - A C# library for tracking Google Analytics
Microsoft Public License
290 stars 111 forks source link

Track Page Timings? #94

Closed imobiledeveloper closed 8 years ago

imobiledeveloper commented 8 years ago

Does the tracker do api page timings/site speed analytics in the current version? I noticed that when I look online under Behavior -> Site Speed -> Page Timings everything for load time is zero...

gandarez commented 8 years ago

@imobiledeveloper yes it does. Just take a look at our static class UserTimingExtensions on GoogleAnalyticsTracker.WebAPI2 You can easliy implement acoordingly your needs.

imobiledeveloper commented 8 years ago

Do u have a code sample you can share?

-----Original Message----- From: "Carlos Henrique Guardão Gandarez" notifications@github.com Sent: ‎11/‎18/‎2015 2:39 PM To: "maartenba/GoogleAnalyticsTracker" GoogleAnalyticsTracker@noreply.github.com Cc: "imobiledeveloper" draghicimike@gmail.com Subject: Re: [GoogleAnalyticsTracker] Track Page Timings? (#94)

@imobiledeveloper yes it does. Just take a look at our static class UserTimingExtensions on GoogleAnalyticsTracker.WebAPI2 You can easliy implement acoordingly your needs. — Reply to this email directly or view it on GitHub.

gandarez commented 8 years ago

You may try decorating your class with GoogleAnalyticsUserTiming Example:

[GoogleAnalyticsUserTiming("category", "variable")]
public IHttpActionResult Post([FromBody]Cotacao cotacao)
{
       return new CotacaoResult(cotacao, Request);
}

Classes:

public static class UserTimingExtensions
    {
        public static async Task<TrackingResult> TrackUserTimingAsync(this Tracker tracker, HttpRequestMessage httpRequest, string pageTitle, string pageUrl, string category, string variable, long value, string label = null)
        {
            var userTimingParameters = new UserTimings
            {
                DocumentTitle = pageTitle,
                DocumentLocationUrl = pageUrl,
                UserAgent = httpRequest.Headers.UserAgent.ToString(),
                DocumentHostName = httpRequest.RequestUri.Host,
                UserLanguage = httpRequest.Headers.AcceptLanguage.ToString().ToLower(),
                ReferralUrl = httpRequest.Headers.Referrer != null ? httpRequest.Headers.Referrer.ToString() : null,
                UserTimingCategory = category,
                UserTimingVariable = variable,
                UserTimingTime = value,
                UserTimingLabel = label,
                NonInteractionHit = GoogleBoolean.True,
                CacheBuster = tracker.AnalyticsSession.GenerateCacheBuster()
            };

            return await tracker.TrackUserTimingAsync(userTimingParameters);
        }
    }

public class UserTimingTrackingAttribute : AsyncActionFilterAttribute
    {
        DateTime _startTime;
        Func<HttpActionContext, bool> _isTrackableAction;
        public Tracker Tracker { get; set; }

        public string Category { get; private set; }
        public string Variable { get; private set; }
        public string Label { get; private set; }

        public UserTimingTrackingAttribute(string trackingAccount, string category, string variable, string label = null)
            : this(trackingAccount, null, category, variable, label)
        {
        }

        public UserTimingTrackingAttribute(string trackingAccount, string trackingDomain, string category, string variable, string label = null)
        {
            Tracker = new Tracker(trackingAccount, trackingDomain, new CookieBasedAnalyticsSession(), new AspNetWebApiTrackerEnvironment());

            Category = category;
            Variable = variable;
            Label = label;
        }

        public Func<HttpActionContext, bool> IsTrackableAction
        {
            get
            {
                if (_isTrackableAction != null)
                    return _isTrackableAction;

                return action => true;
            }
            set { _isTrackableAction = value; }
        }

        private long TotalMilliseconds
        {
            get { return Convert.ToInt64(new TimeSpan(DateTime.Now.Ticks - _startTime.Ticks).TotalMilliseconds); }
        }

        public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            if (IsTrackableAction(actionContext))
                _startTime = DateTime.Now;

            return Task.FromResult(new object());
        }

        public async override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            if (IsTrackableAction(actionExecutedContext.ActionContext))
                await OnTrackingUserTiming(actionExecutedContext.ActionContext);
        }

        public virtual async Task<TrackingResult> OnTrackingUserTiming(HttpActionContext filterContext)
        {
            return
                await
                    Tracker.TrackUserTimingAsync(filterContext.Request, BuildCurrentActionName(filterContext),
                        BuildCurrentActionUrl(filterContext), Category, Variable, TotalMilliseconds, Label);
        }
    }

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class GoogleAnalyticsUserTiming : UserTimingTrackingAttribute
    {
        public GoogleAnalyticsUserTiming(string category, string variable, string label = null)
            : base("UA-XXXXXXXX-Y", category, variable, label)
        {
            IsTrackableAction = action => true;
        }        
    }