Monday, 31 January 2011

Once-per-session javascript

Want to run some javascript only once per session? Here's some code, not written by me, that does the trick:

// ++++++++++++++++++++++++++++++++++++++++++ 
// Run Once Per Session 
// Replace the alerts by functions that need to 
// be run once per session. 
// Written by: Michael Regan 
// Website   : 
// Released under the GPL. 
// ++++++++++++++++++++++++++++++++++++++++++ 
var key_value = "myTestCookie=true"; 
var foundCookie = 0; 

// Get all the cookies from this site and store in an array 
var cookieArray = document.cookie.split(';'); 

    // Walk through the array 
    for(var i=0;i < cookieArray.length;i++) 
               var checkCookie = cookieArray[i]; 
        // Remove any leading spaces 
               while (checkCookie.charAt(0)==' ') 
                 checkCookie = checkCookie.substring(1,checkCookie.length); 
        // Look for cookie set by key_value 
                if (checkCookie.indexOf(key_value) == 0) 
                  alert("Found Cookie "); 
            // The cookie was found so set the variable 
                   foundCookie = 1; 
    // Check if a cookie has been found 
    if ( foundCookie == 0) 
        // The key_value cookie was not found so set it now 
        document.cookie = key_value; 
        alert("Setting Cookie"); 

Wednesday, 26 January 2011

Adding a 3rd party cookie using an image as Response.ContentType

I've been working on a bit of tracking code that can be dropped onto websites so that we can record and analyze visitor data and resolve issues regarding conversion origins, particularly regarding PPC vs affiliate traffic. There are a few techniques, but this one in particular uses .net code to perform some logic (database calls etc) prior to placing a cookie and then responding to the browser as though it is an image:
//prepare the cookie
HttpCookie trackingCookie = new HttpCookie(cookie_name, cookie_value);
 trackingCookie.Expires = DateTime.Now.AddMonths(1);

//this line is a 'compact privacy policy' for IE
HttpContext.Current.Response.AddHeader("p3p", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");   

//drop tracking cookie
//Write image
string loc = Server.MapPath("/img/track.gif");
Response.ContentType = "image/gif";

The js code to initiate it, placed in the host website:


where the javascript value trackingData is populated by clientside code included (before the above code) like so:

This is some simple javascript that grabs the utm_source, utm_campaign (etc..) values from the URL and puts them into the value of trackingData.

Using this technique we can use specific cookie names and values to provide persistence between visitor sessions and to record and analyze their origins.

Tuesday, 25 January 2011

IE8 Developer Tools - Could not get cookie information

Has your developer tools suddenly stopped showing you cookie information with the following error:
Could not get cookie information.
You can fix it by doing the following:
Tools > InternetOptions > General > BrowsingHistory > Delete > Cookies and Temporary Files

Thursday, 20 January 2011

Trouble with Darren Johnstone file upload module

I'd used Darren Johnstone's brilliant file upload module before now, but I thought I'd take a look at SWFUpload just to see what it was like. I found SWFUpload a little too unintuitive to implement, so given my shortage of time I resorted back to the old faithful aforementiond DJFileUpload.

But this time round I just couldn't get it to work. I downloaded the sample C# project and that worked. I drafted all the relevant code into my own project but it still wouldn't work. I spent a long time trying to work out what was different between my project and the sample that worked. Was it because I was using VS2010 with .Net 4.0? What about some kind of permissions problem on my project?

Eventually I found the problem. While trying out SWFUpload I'd added the following code to my Global.asax file. This same code makes Darren Johnstone's file uploader no longer work! Remove it, and hey presto:

void Application_BeginRequest(object sender, EventArgs e)
            /* Fix for the Flash Player Cookie bug in Non-IE browsers.
             * Since Flash Player always sends the IE cookies even in FireFox
             * we have to bypass the cookies by sending the values as part of the POST or GET
             * and overwrite the cookies with the passed in values.
             * The theory is that at this point (BeginRequest) the cookies have not been read by
             * the Session and Authentication logic and if we update the cookies here we'll get our
             * Session and Authentication restored correctly

                string session_param_name = "ASPSESSID";
                string session_cookie_name = "ASP.NET_SESSIONID";

                if (HttpContext.Current.Request.Form[session_param_name] != null)
                    UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
                else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
                    UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
            catch (Exception)
                Response.StatusCode = 500;
                Response.Write("Error Initializing Session");

                string auth_param_name = "AUTHID";
                string auth_cookie_name = FormsAuthentication.FormsCookieName;

                if (HttpContext.Current.Request.Form[auth_param_name] != null)
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
                else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);

            catch (Exception)
                Response.StatusCode = 500;
                Response.Write("Error Initializing Forms Authentication");

Friday, 14 January 2011

Configuring SMTP on new Win 2008 server

I just spent far too long trying to get this to work, so this is a note-to-self so I don't re-invent the wheel next time.

Open Server Manager and add the feature 'SMTP'. Go with all the defaults. This will include the required IIS6.

Go to IIS6 and then setup the SMTP server thus:

In IIS7 configure the SMTP E-mail of the website thus:

Friday, 7 January 2011

Create a new Guid

Here's how you create a new globally unique identifier in C#:


Thursday, 6 January 2011

Page Load event firing multiple times - why?

Today I had a weird problem - my Page Load event was firing twice for every visit, whether postback or not. I eventually found the problem:

It looks like an empty src attribute in an HTML img element is interpreted as a relative URL to the current page, thereby calling the page.