Google Analytics based on Microsoft.AspNet.Identity roles - asp.net-mvc

I am trying to find a way to register all the traffic of a website with Google Analytics, spliting the reporting based on the Microsoft.AspNet.Identity role.
I did not found anything that allows to do it.
Something like:
if(User.IsInRole("public"))
{
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'PUBLIC', 'auto');
ga('send', 'pageview');
</script>
}
else if (User.IsInRole("private"))
{
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'PRIVATE', 'auto');
ga('send', 'pageview');
</script>
}

You are looking for the User ID feature. Here is a Tutorial.
You need to setup the feature. Then you can start tracking like this:
ga('create', 'UA-XXXXXX-Y', {'userId': customUserId});
Anonymous Users you can detect by
User.Identity.IsAuthenticated
You want to send a userid that you do not have like 0 for anonymous users.

I have been testing for a few days now and I found a great way to have 2 different properties in the same account:
#if (Model.IsUserInternal == true)
{
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXXX-2', 'auto');
ga('send', 'pageview');
</script>
}
else
{
<script>
(function(i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function() {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-XXXXXXXXX-1', 'auto');
ga('send', 'pageview');
</script>
}
Where XXXXXXXXX is the same.

Related

select2 v4 dataAdapter.query not firing

I have an input to which I wish to bind a dataAdapter for a custom query as described in https://select2.org/upgrading/migrating-from-35#removed-the-requirement-of-initselection
<input name="pickup_point">
My script:
Application.prototype.init = function() {
this.alloc('$pickupLocations',this.$el.find('[name="pickup_point"]'));
var that = this;
$.fn.select2.amd.require([
'select2/data/array',
'select2/utils'
], function (ArrayData, Utils) {
var CustomData = function($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
};Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
var data = {
results: []
};
console.log("xxx");
for (var i = 1; i < 5; i++) {
var s = "";
for (var j = 0; j < i; j++) {
s = s + params.term;
}
data.results.push({
id: params.term + i,
text: s
});
}
callback(data);
};
that.$pickupLocations.select2({
minimumInputLength: 2,
language: translations[that.options.lang],
tags: [],
dataAdapter: CustomData
});
});
}
But when I type the in the select2 search box the xxx i'm logging for testing doesn't appear in my console.
How can I fix this?
I found the solution on
https://github.com/select2/select2/issues/4153#issuecomment-182258515
The problem is that I tried to initialize the select2 on an input field.
By changing the type to a select, everything works fine.
<select name="pickup_point">
</select>

jQuery Mobile Google Universal Analytics

I've been happily using this best practice http://roughlybrilliant.com/jquery_mobile_best_practices#7 for integrating ga.js with jQuery Mobile. I'm planning to upgrade to analytics.js using the new Universal Analytics tracking code. I wonder whether something like this below will work following the best practice using the ga.js tracking code.
<script>
$(document).ready(function (e) {
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
});
$(document).on('pageshow', '[data-role=page], [data-role=dialog]', function (event, ui) {
try {
ga('create', 'UA-XXXXXXXX-X', 'domain.com');
if ($.mobile.activePage.attr("data-url")) {
ga('send', 'pageview', '$.mobile.activePage.attr("data-url")');
} else {
ga('send', 'pageview');
}
} catch (err) {}
});
</script>
Everything should work above save the '$.mobile...' part being in quotes. A few of their suggestions are a bit off though. Refractored below
<script>
// domReady is unnecessary here and can slow down perceived performance
// $(document).ready(function (e) {
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-XXXXXXXX-X', 'domain.com'); // move this here!
// });
$(document).on('pageshow', '[data-role=page], [data-role=dialog]', function (event, ui) {
try {
if ($.mobile.activePage.attr("data-url")) {
ga('send', 'pageview', $.mobile.activePage.attr("data-url")); // remove quotes
} else {
ga('send', 'pageview');
}
} catch (err) {}
});
</script>

ASP.NET MVC Jquery Ajax post form serialize?

Ajax function
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: { model: $(this).serialize(), locations: getCheckedLocation(), reports: getCheckedReports() },
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$('#user_operations_container').html(result);
setTimeout(function () { LoadAction('#Url.Action("GetAllUsers", "User")') }, 1000);
$("#widgets ul li a").removeClass("link_active");
$("#widgets ul li:first-child a").addClass("link_active");
}
});
}
return false;
});
});
functions that are using in ajax data attribute
function getCheckedLocation() {
var nodes = $('#tt_location').tree('getChecked');
var s = '';
for (var i = 0; i < nodes.length; i++) {
if (s != '') s += ',';
s += nodes[i].text;
}
return s;
}
function getCheckedReports() {
var nodes = $('#tt_reports').tree('getChecked');
var s = '';
for (var i = 0; i < nodes.length; i++) {
if (s != '') s += ',';
s += nodes[i].text;
}
return s;
}
HTML
<div> // there are html helpers for model (dropdownlistfor, textboxfor,...)
</div>
<div> // checkbox tree (#tt_location)
</div>
<div> // checkbox tree (#tt_reports)
</div>
Controller
[HttpPost]
public ActionResult _EditUser(UserViewModel model,string locations,string reports)
{
// model = null
// locations and reports are expected. (not null)
}
Question
Why model is null?
When I use ajax data attribute like this = data: $(this).serialize(), , It works model is not null.
How can I post model, with additional data (locations,reports).
I hope I can explain. Thanks...
Try like this:
data:$('this').serialize() + "&locations=" + getCheckedLocation() "&reports=" + getCheckedReports()
It will work.
Hope it helps

jQuery Autocomplete: How to enable cache?

This is my source code that use a function to push the suggestion array:
jQuery(document).ready(function ($){
var cache = {};
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$("#ctags-input")
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function(req, add){
var ctags_action = 'suggest_tags';
var term = req.term;
if (term in cache) {
add(cache[term]);
return;
}
$.getJSON(SuggestTags.url+'?callback=?&action='+ctags_action, req, function(data) {
var suggestions = [];
$.each(data, function(i, val){
suggestions.push({
label: val.name,
count: val.count
});
});
cache[term] = suggestions;
add(suggestions);
});
},
focus: function() {
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
terms.pop();
terms.push( ui.item.value );
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + " (" + item.count+ ")</a>")
.appendTo(ul);
};
});
To add cache ability, jQ UI site demo directly uses response for data:
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
}
How to implement this cache demo in my code?
Put suggestions in the cache.
var term = req.term;
if (term in cache) {
add(cache[term]);
return;
}
...
cache[term] = suggestions;
add(suggestions);

Uploadify - How to capture the newly created ID for scriptdata?

I have solved the problem myself now, below is the solution:
No problem any more. I am only writing this to get my text validated.
<script type="text/javascript">
/***************************************************/
/* THIS VARIABLE IS USED TO TRANSPORT THE NEW ID. */
var assignmentId;
/***************************************************/
$("#btnSave").click
(
function () {
var inputData = $("form").serialize();
var url = $("form").attr("action");
$.post(url, inputData, function (data) {
/********************************************************/
/* NOW UPLOADIFY GETS THE NEW ID!! */
assignmentId = data.AssignmentID;
alert(assignmentId.toString());
$('#fileuploader').uploadifySettings("scriptData", { 'currentValue': assignmentId });
/********************************************************/
$('#fileuploader').uploadifyUpload();
});
}
);
$("#fileuploader").uploadify({
'uploader': '#Url.Content("/Scripts/uploadify/uploadify.swf")',
'cancelImg': '/Scripts/uploadify/cancel.png',
'buttonText': 'Browse For File',
'script': '#Url.Action("Upload")',
'folder': '/uploads',
'scriptData': { 'currentValue': assignmentId },
'onAllComplete': function (event, data) { window.location = "/Assignment/" + assignmentId; },
'onError': function (a, b, c, d) {
},
'onSelectOnce': function (event, data) { noFilesToUpload = false; },
'fileDesc': 'Media Files',
'fileExt': '*.jpg;*.jpeg;',
'sizeLimit': 27000000,
'multi': false,
'auto': false
});
</script>
Thank you!
I have solved the problem myself now, below is the solution:
No problem any more. I am only writing this to get my text validated.
<script type="text/javascript">
/***************************************************/
/* THIS VARIABLE IS USED TO TRANSPORT THE NEW ID. */
var assignmentId;
/***************************************************/
$("#btnSave").click
(
function () {
var inputData = $("form").serialize();
var url = $("form").attr("action");
$.post(url, inputData, function (data) {
/********************************************************/
/* NOW UPLOADIFY GETS THE NEW ID!! */
assignmentId = data.AssignmentID;
alert(assignmentId.toString());
$('#fileuploader').uploadifySettings("scriptData", { 'currentValue': assignmentId });
/********************************************************/
$('#fileuploader').uploadifyUpload();
});
}
);
$("#fileuploader").uploadify({
'uploader': '#Url.Content("/Scripts/uploadify/uploadify.swf")',
'cancelImg': '/Scripts/uploadify/cancel.png',
'buttonText': 'Browse For File',
'script': '#Url.Action("Upload")',
'folder': '/uploads',
'scriptData': { 'currentValue': assignmentId },
'onAllComplete': function (event, data) { window.location = "/Assignment/" + assignmentId; },
'onError': function (a, b, c, d) {
},
'onSelectOnce': function (event, data) { noFilesToUpload = false; },
'fileDesc': 'Media Files',
'fileExt': '*.jpg;*.jpeg;',
'sizeLimit': 27000000,
'multi': false,
'auto': false
});
</script>

Resources