hide google analytic code - asp.net

Is it possible not to show the google analytic code on the master page? I mean can I place it somewhere where no one can see it but still get all the analysis on the application ?

You can use the mobile code for google analytic to make what you ask.
http://code.google.com/mobile/analytics/docs/web/
How this works. This google modile code can call the google analytic from your server on code behind, and not from the client page using javascript. So you can totally hide this call from your clients, and all data are send to google analytic, let say on page load.
First on your google analytic detail page, get the code for mobiles for asp.net, and then see this code that you need to focus and change, so you can make a global function that use on Page Load. To avoid possible delay I also suggest to make a new thread call to the google analytics, until the asp.net 4.5 get outs that include that option on WebRequest.
string utmGifLocation = "http://www.google-analytics.com/__utm.gif";
// Construct the gif hit url.
string utmUrl = utmGifLocation + "?" +
"utmwv=" + Version +
"&utmn=" + GetRandomNumber() +
"&utmhn=" + HttpUtility.UrlEncode(domainName) +
"&utmr=" + HttpUtility.UrlEncode(documentReferer) +
"&utmp=" + HttpUtility.UrlEncode(documentPath) +
"&utmac=" + account +
"&utmcc=__utma%3D999.999.999.999.999.1%3B" +
"&utmvid=" + visitorId +
"&utmip=" + GetIP(GlobalContext.Request.ServerVariables["REMOTE_ADDR"]);
SendRequestToGoogleAnalytics(utmUrl);
private void SendRequestToGoogleAnalytics(string utmUrl)
{
try
{
WebRequest connection = WebRequest.Create(utmUrl);
((HttpWebRequest)connection).UserAgent = GlobalContext.Request.UserAgent;
connection.Headers.Add("Accepts-Language",
GlobalContext.Request.Headers.Get("Accepts-Language"));
using (WebResponse resp = connection.GetResponse())
{
// Ignore response
}
}
catch (Exception ex)
{
if (GlobalContext.Request.QueryString.Get("utmdebug") != null)
{
throw new Exception("Error contacting Google Analytics", ex);
}
}
}
All that is a little hack on google analytic mobile code, but the general idea works on your case. Get the Google Analytic SDK here.
http://code.google.com/apis/analytics/docs/tracking/home.html
What actually google try to archive here. Google say that there is not reason for mobile phone with limited and costly bandwidth to make the call on google analytics. So google make a code behind call to google analytic just by opening a page. From the part of the mobile, he only need to read a tiny image, and on code behind this call to the image is making the reall call to google. From your side, you do not need to place an image, you can direct call google analytic by changing a little the function that google provides.
Hope this help.

since you have to put it in your header for the analytic script, there is no easy way of doing this. you want to hide your ID#? There may be a way to reference a variable for your ID#, but without a bunch of extra coding there is no way.

If it's there, people can see it if they look for it. If it's not there, you can't get the analysis.
You could get a little sneaky, and have the analytics on a page that gets loaded into an invisible iframe, but someone that wants to find it will.

Related

Sometimes Initialization of Google Earth Plugin fails in IE10

This is my code for the initialization of google earth plugin.
Sometimes Initialization of Google Earth Plugin fails in IE10(I have it in compatability mode) IE7 Standards. This error happens only in IE and no other browser.
90% of the time createInstance() method creates the google earth plugin instance and control goes to mygeeEarthPluginInitCb() method but few times mostly after restarting the machine or after few hours of inactivity if I load the page createInstance fails and control goes to geeEarthPluginFailureCb() method.
This is causing an error page, a very intermittent one.
function geeInit() {
alert("google.earth.createInstance : Start");
google.earth.createInstance(geeDivIds.map, mygeeEarthPluginInitCb,
geeEarthPluginFailureCb, earthArgs);
alert("google.earth.createInstance : End");
}
function mygeeEarthPluginInitCb(object) {
alert("Success mygeeEarthPluginInitCb: Inside");
geeEarthPluginInitCb(object);
gex = new GEarthExtensions(ge);
createSearchResultsMarkers(null, 'results');
var lookAt = ge.createLookAt('');
lookAt.setLongitude(Number('-73.784190'));
lookAt.setLatitude(Number('42.643446'));
lookAt.setRange(25000.00);
ge.getView().setAbstractView(lookAt);
initRadSearchValsOnLoad();
}
function geeEarthPluginFailureCb(message) {
alert("Failure geeEarthPluginFailureCb: Inside" + message);
if (google.earth.isInstalled()) {
} else {
var result = confirm('Google Earth Plugin is not'
+ ' installed.Please download and install it.');
if (result == true) {
window.location.href = 'install.html';
}
}
}
Remove all the alert lines, e.g.
alert("google.earth.createInstance : Start");
and
alert("google.earth.createInstance : End");
alert is a special method that blocks execution and user interaction - it could well be that it is blocking the initialisation of the plugin. This is something I have seen before.
Perhaps try using the console, or else outputting data to the document in some way that avoids blocking. e.g.
console && console.log("google.earth.createInstance, "End");
Google acknowledged the issue and mentioned they are working on a fix.
For right now there is a temporary fix below is the shorter version of Google's response.
******** Start Google's Response *************
"We have been able to reproduce this issue, intermittently. It is now pending additional investigation for the Google Earth client team, to find the root cause here. Unfortunately, it is not possible to provide an estimate for a deadline when this will be fixed. This issue definitely has a high priority since it impacts all Google Earth users with custom globes (GEE, and GME), and we have let the team know that this is now critical for your applications.
The only workaround that we can see, right now, is to refresh the page when the plugin fails to load (or you could do that programmatically: implement a timeout, and if after 5 seconds, the Earth API has not yet loaded, reload the plugin, or refresh the page). You could also consider using the Google Earth client, but I'm not sure if this is something that would be applicable to your use case."
**********End Google's Response ***************

Flex not wanting to use https as specified

I have a small little swf that I'm trying to get to work while the webpage is using https/ssl. I'm passing into the swf the fact that the page is using https and have conditional logic as such:
if ( secure ) {
pollChannel = new AMFChannel('my-secure-polling-amf','https://' + globalDomain + '/flex2gateway/cfamfpollingsecure');
}
else {
pollChannel = new AMFChannel('cf-polling-amf','http://' + globalDomain + '/flex2gateway/cfamfpolling');
}
When the page is http it uses the correct endpoint no problem. When secure == true for whatever reason the browser is reporting its using http://somedomain.local/flex2gateway/cfamfpollingsecure, not https.
Anybody have a clue why??? I don't understand why it would adjust itself like that.
Any help is much appreciated!
Lucky for you I had the exact same mystery issue last week and the fix is extremely simple (once you know where to look, that is; I've been digging through the source code for a while to figure it out):
you just have to use SecureAMFChannel instead of the regular AMFChannel

Retrieve comments from website using disqus

I would like to write a scraping script to retrieve comments from cnn articles. For example, this article: http://www.cnn.com/2012/01/19/politics/gop-debate/index.html?hpt=hp_t1
I realize that cnn uses disqus for their comment discussion. As the comment loading is not webpage-based (ie, prev page, next page) and is dynamic (ie, need to click "load next 25"), I have no idea how to retrieve all the 5000+ comments for this article.
Any idea or suggestion?
Thanks so much!
I needed to get comments via scraping a page that had disqus comments via ajax. Because they were not rendered on the server, I had to call the disqus api. In the source code, you will need the identifier code:
var identifier = "456643" // take note of this from the page source
// this is the ident url query param in the following js request
also,look in the js source code to get the pages public key, and forum name. Place these in the url where appropriate.
I used javascript nodejs to test this, ie :
var request = require("request");
var publicKey = "pILMw27bsbJsdfsdQDh9Eh0MzAgFL6xx0hYdsdsdfaIfBHRvLGqFFQ09st";
var disqusUri = "https://disqus.com/api/3.0/threads/listPosts.json?&api_key=" + publicKey + "&thread:ident=456643&forum=nameOfForumFromSource";
request(disqusUri, function(res,status,err){
console.log(res.body);
if(err){
console.log("ERR: " + err);
}
});
The option for scraping (other then getting the page), which might be less robust (depends on you're needs) but will offer a solution for the problem you have, is to use some kind of wrapper around a full fledged web browser and literally code the usage pattern and extract the relevant data. Since you didn't mention which programming language you know, I'll give 3 examples: 1) Watir - ruby, 2) Watin - IE & Firefox via .net, 3) Selenium - IE via C#/Java/Perl/PHP/Ruby/Python
I'll provide a little example using Watin & C#:
IE browser = new IE();
browser.GoTo(YOUR CNN URL);
List visibleComments = Browser.List(Find.ById("dsq-comments"));
//do your scraping thing
Link moreComments = Browser.Link(Find.ByClass("dsq-paginate-append-text");
moreComments.click();
//wait util ajax ended by searching for some indicator
Browser.WaitUntilContainsText(SOME TEXT);
//do your scraping thing
Notice:
I'm not familiar with disqus, but it might be a better option to force all the comments to show by looping the Link & click parts of the code I posted until all the comments are visible and the scrape the List element dsq-comments

Tracking email opens in Google Analytics

We have tracking in our emails to track clicks back to our site through Google Analytics. But is there a way to track opens? I would imagine I have to add a google tracking image to the email somewhere. Possibly javascript too?
As others have pointed out, you can't use Javascript in email. The actual tracking is done by a request for __utm.gif though and the Javascript just constructs the GET parameters.
Google supports non-Javascript uses of Google Analytics per their Mobile web docs:
http://code.google.com/mobile/analytics/docs/web/
They document the full list of parameters, but the only necessary parameters are:
Parameter Description
utmac Google Analytics account ID
utmn Random ID to prevent the browser from caching the returned image
utmp Relative path of the page to be tracked
utmr Complete referral URL
The reference that describes all of the parameters that the Google Analytics tracking GIF allows is here. Use it to build an <img> tag in your email that references the GA GIF.
According to this post, the minimum required fields are:
utmwv=4.3
utmn=<random#>&
utmhn=<hostname>&
utmhid=<random#>&
utmr=-&
utmp=<URL>&
utmac=UA-XXXX-1&
utmcc=_utma%3D<utma cookie>3B%2B_utmz%3D<utmz cookie>%3B
It sounds like you are using campaign tracking for GA but also want to know how many opens there were. This is possible to do with Google Analytics, since they track pageviews or events by use of pixel tracking as all (I think?) email tracking does. You cannot use javascript, however, since that will not execute in an email.
Using Google Analytics pixel tracking:
The easiest way would be to use browser developer tools such as Firebug for Firefox or Opera's Dragonfly to capture a utm.gif request and copy the URL. Modify the headers to suit your needs. You can count it either as an event or pageview. If you count it as an event it should look something like this:
http://www.google-analytics.com/__utm.gif?utmwv=4.8.6&utmn=1214284135&utmhn=www.yoursite.com&utmt=event&utme=email_open&utmcs=utf-8&utmul=en&utmje=1&utmfl=10.1%20r102&utmdt=email_title&utmhid={10-digit time code}&utmr=0&utmp=email_name&utmac=UA-{your account}
You can use this to understand what describes what in the headers.
I better post this to save everyone the trouble of trying to construct that monstrous UTM gif URL.
You can now use the new Measurement Protocol API to send a POST request and easily record events, page views, hits, or almost any other type of measurement. It's super easy!
POST /collect HTTP/1.1
Host: www.google-analytics.com
payload_data
For example, here's a code snippet to send an event in C# (using SSL endpoint):
public void SendEvent(string eventCategory = null, string eventAction = null, string eventLabel = null, int? eventValue = null)
{
using(var httpClient = new HttpClient() {BaseAddress = new Uri("https://ssl.google-analytics.com/")}) {
var payload = new Dictionary<string, string>();
// Required Data
payload.Add("v", "1"); // Version
payload.Add("tid", "UA-XXX"); // UA account
payload.Add("aip", "1"); // Anonymize IP
payload.Add("cid", Guid.NewGuid().ToString()); // ClientID
payload.Add("t", "event"); // Hit Type
// Optional Data
payload.Add("ni", "1"); // Non-interactive hit
// Event Data
if (eventCategory != null)
{
payload.Add("ec", eventCategory);
}
if (eventAction != null)
{
payload.Add("ea", eventAction);
}
if (eventLabel != null)
{
payload.Add("el", eventLabel);
}
if (eventValue != null)
{
payload.Add("ev", eventValue.Value.ToString(CultureInfo.InvariantCulture));
}
using (var postData = new FormUrlEncodedContent(payload))
{
var response = httpClient.PostAsync("collect?z=" + DateTime.Now.Ticks, postData).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception("Could not send event data to GA");
}
}
}
}
Way easier than the hack with the __utm gif.
Helpful Example
You can easily add this to emails by doing this:
In an email:
<img src="{url}/newsletter/track.gif?newsletterName=X" />
In your MVC site, for example, NewsletterController:
public ActionResult Track(string newsletterName) {
using(var ga = new AnalyticsFacade()) {
ga.TrackEmailOpen(newsletterName);
}
return Content("~/images/pixel.gif", "image/gif");
}
In your Global.asax or RouteConfig:
routes.MapRoute(
"newsletteropen",
"newsletter/track.gif",
new
{
controller = "Newsletter",
action = "Track"
});
BOOM, done, son. You can now track email opens using a much nicer API that's supported and documented.
Is your requirement is to track how many times an e-mail is open by given user. We have similar problem. We are using SMTP relay server and wanted to track how many times our marketing e-mails are open in addition to google-analytics which register an even only when someone clicks inside link to our site in e-mail.
This is our solution. It is based on making a REST call by overriding image element of html (our e-mails are html base)
where TRACKING is dynamically generated url which points to our REST service with tracking information about person to which e-mail was send. It is something like that
//def trackingURL = URLEncoder.encode("eventName=emailTracking&entityType=employee&entityRef=" + email.empGuid, "UTF-8");
trackingURL = baseUrl + "/tracking/create?" + trackingURL;
It will be something like "https://fiction.com:8080/marketplace/tracking/Create?eventName=email&entityType=Person&entityRef=56"
When when actual e-mail html is generated it, TRACKING will be replaced by
Important point is to return a response of type image and return a one pixel transparent image with REST response.
So i'll assume that the email contains a link to your Site. Certainly GA can record how often that link is clicked because clicking the link will open the page in turn causing the function *_trackPageview()* to be called, which is recorded by GA as a pageview.
So as long as that page has the standard GA page tag, no special configuration is required--either to the GA code in your web page markup or to the GA Browser. The only additional work you have to do is so that you can distinguish those page views from page views by visitors from another source.
To do that, you just need to tag this link. Unless you have your own system in place and it's working for you, i recommend using Google URL Builder to do this for you. Google URL Builder is just a web-form in which you enter descriptive terms for your marketing campaign: Campaign Source, Campaign Medium, Campaign Content, Campaign Name. Once you've entered values for each of these terms, as well as entered your Site's URL, Google will instantly generate a 'tagged link' for you (by concatenating the values to your Site's URL).
This URL generated by Google URL Builder is the link that would be placed in the text of your marketing email.

Run Javascript on the body of a Gmail message

I want to display LaTeX math in the gmail messages that I receive, so that for example $\mathbb P^2$ would show as a nice formula. Now, there are several Javascripts available (for example, this one, or MathJax which would do the job, I just need to call them at the right time to manipulate the gmail message.
I know that this is possible to do in "basic HTML" and "print" views. Is it possible to do in the standard Gmail view? I tried to insert a call to the javascript right before the "canvas_frame" iframe, but that did not work.
My suspicion is that manipulating a Gmail message by any Javascript would be a major security flaw (think of all the malicious links one could insert) and that Google does everything to prevent this. And so the answer to my question is probably 'no'. Am I right in this?
Of course, it would be very easy for Google to implement viewing of LaTeX and MathML math simply by using MathJax on their servers. I made the corresponding Gmail Lab request, but no answer, and no interest from Google apparently.
So, again: is this possible to do without Google's cooperation, on the client side?
I think one of the better ways to do this might be to embed images using the Google Charts API.
<img src="http://chart.apis.google.com/chart?cht=tx&chl=x=\frac{-b%20\pm%20\sqrt{b^2-4ac}}{2a}">
To Learn more: https://developers.google.com/chart/image/ [note, the API has been officially deprecated, but will work until April 2015]
If you really must use LaTeX and some js library, I think one way you could accomplish this is by injecting a script tag into the iframe.
I hope this is a good starting point.
Example:
// ==UserScript==
// #name Test Gmail Alterations
// #version 1
// #author Justen
// #description Test Alter Email
// #include https://mail.google.com/mail/*
// #include http://mail.google.com/mail/*
// #license GPL version 3 or any later version; http://www.gnu.org/copyleft/gpl.html
// ==/UserScript==
(function GmailIframeInject() {
GM_log('Starting GMail iFrame Injection');
var GmailCode = function() {
// Your code here;
// The ':pd' (div id) changes, so you might have to do some extra work
var mail = document.getElementById(':pd');
mail.innerHTML = '<h1>Hello, World!</h1>';
};
var iframe = document.getElementById('canvas_frame');
var doc = null;
if( iframe ) {
GM_log('Got iFrame');
doc = iframe.contentDocument;
} else {
GM_log('ERROR: Could not get iframe with id canvas_frame');
return
}
if( doc ) {
GM_log('Injecting GmailCode');
var code = "(" + GmailCode + ")();"
doc.body.appendChild(doc.createElement('script')).innerHTML=code;
} else {
GM_log('ERROR: Could not get iframe content document');
return;
}
})();
Well, there are already greasemonkey scripts that do things to GMail as far as i know (like this one). Is this a possible security hole? Of course, anything you'd do with executable code has that risk. Google seems to move a glacial speeds on things they're not interested in. They really do seem to function based on internal championing of ideas, so best way forward is to go find sympathetic googlers, if you want them to include something into GMail. Otherwise stick to Greasemonkey, at least you'll have an easy install path for other people who'd like to see the same functionality.

Resources