ActionScript.org Flash, Flex and ActionScript Resources - http://www.actionscript.org/resources
Basic Activity Tracking with Flash, Actionscript 2.0 and ASP.NET 2.0
http://www.actionscript.org/resources/articles/703/1/Basic-Activity-Tracking-with-Flash-Actionscript-20-and-ASPNET-20/Page1.html
Mike McKinnon

I am an ASP Dot Net / C# Programmer.  I also am Flash Certified.  I specialize in marketing and advertising related websites that tie in the visual richness of flash with elements of http://ASP.NET and server side programming to create rich content driven applications that track user behaviour.   Current Languages : C# / PHP / Javascript / T-SQL / http://VB.NET.

 
By Mike McKinnon
Published on November 27, 2007
 

Difficulty: Intermediate

In this article I will be demonstrating how to track activities in your flash application by using LoadVariables to pass arguments to a waiting asp.net page (.aspx) to process however you want. My example utilizes an SQL Server database to store the activities, but you could utilize any database connection via ASP.NET 2.0.  

This article touches upon basic OOP principals and includes example code in both Actionscript 2.0 for the flash tracking and C# for the server side processing.  I also utilize a simple utility class in Actionscript to contain the methods necessary to connect to the asp.net web page.


Introduction and Set-Up

Introduction:
I'm a .net programmer.  My servers are all windows boxes, running a mix of IIS Versions, nothing open source, no linux or php.  Most articles regarding database operations or mixing server side programming with flash involve either Adobe server products, or open sourced (php, perl, etc) solutions.  I hope to provide this article as a useful reference for those of us who bravely choose to use Microsoft Server Products, and still want to utilize server side objects and data with our flash applications.


Getting Started:
To go through this tutorial you will need the following products:
• Flash 8 or better with Actionscript 2.0 running.
• Visual Studio 2005 or Visual Web Developer (Free Version)
• Sql Server 2000 or a Sql Server Express Installation  (Note: sql server is not mandatiory to understand the concepts.  Any database can be used with a .NET application, but that is beyond the scope of this tutorial.) 

Setting Up:
First thing to do is to create a folder for your application on your disk. For this example we will create a folder named "MyApplication" under the C: Drive. "C:\MyApplication". Also create a new Flash Project under this folder. Call the Project : "FlashTrackingProject".


Step One : Creating the Actionscript Class

The first thing we need to do is to create a class that will do the heavy lifting between Flash and the ASP.NET web application the flash movie will be running on.

 

  1. Create a new Actionscript (.as) file.  Name the file "DotNetUtils.as".  We are creating a class for this for two main reasons.  One, we can add all our methods to this class that relate to interoperating with ASP.NET, and two its better practice to utilize classes rather than just throwing methods into your flash movie, you can handle errors easier, and hey, its re-usable.
  2. Once your actionscript file is opened,  paste the following code into it:

 

class DotNetUtils {  

var _trackingPageName:String;

  

public function set TrackingPageName(a:String):Void {

          _trackingPageName = a ? a : String;   }

 

   public function get TrackingPageName():String {

          return _trackingPageName;   }

  

   /* CONSTRUCTOR */

   function DotNetUtils() { }


/* Tracks A Generic Action by appending values to the query string */

public function TrackActivity(object, activity):Void {
   var destinationUrl = _trackingPageName+"?obj="+object+"&act="+activity;

   loadVariables(destinationUrl, _root);

   }     

}


 

Lets go through each piece of this class to understand what it does.

 

var _trackingPageName:String;

 

This is the declaration of a private variable.  This variable is for the whole class instance.  It stores the path to the  physical page we are going to send the loadVariables command to.

 

public function set TrackingPageName(a:String):Void {

          _trackingPageName = a ? a : String;

   }

 

   public function get TrackingPageName():String {

          return _trackingPageName;

   }

 

These functions are simply the getter and setter methods for the private variable _trackingPageName, which we created on the first line.  In C# these would simply be : get{ return this.value; } and set { this = value; }. but in Actionscript 2.0 they are unfortunately a bit more complicated to implement. 

 

/* CONSTRUCTOR */

   function DotNetUtils() { }

 

The constructor is there so you can instantiate a class.  You could pass all the variables through this if you modified it.

 

/* Tracks A Generic Action */

   public function TrackActivity(object, activity):Void {

var destinationUrl = _trackingPageName+"?obj="+object+"&act="+activity;

          loadVariables(destinationUrl, _root);

   }     

 

The function "TrackActivity" is really the only thing in the whole class that does anything.  It’s a function that takes two parameters:  object and activity.  The object parameter is used to define what you are tracking.  I would use this as the name of my Button or Movie Clip that I am tracking.  The activity parameter would be the action I would be tracking on this object.  This could be a click or a rollover event.

The function works like this:

 

  1. Get the destination Url.  This is the parameter you supply after you construct our class.  It’s the Page name of the ASP.NET page that will be handling the tracking aspect from ASP.NET.  Its basically the page with the methods necessary to hit a SQL Database.
  2. Once it has that destination url it builds a query string parameter (a long string after the page name broken up by special characters), and inserts the object name and activity into it.
  3. Finally it sends this query-string to the ASP.NET tracking page.  From there the server side code takes over.


Step Two : Creating the Flash Movie to track

Now we are going to create a new flash movie with one button on it that; when clicked will send values through our class to the server so we can save them in a database.  Start by creating a new Flash Movie.  Name it "TrackerTest.fla" and save it in the same directory as your Project and Actionscript file and add it to the project.

 

  1. Create a button and place it directly on the stage so its on the main timeline in Frame 1 on Layer 1.  Name the instance in the properties window "MyButton".
  2. Click on the buttons instance and press F9 to open the Actionscript Panel.
  3. Once the Actionscript panel is opened paste the following code into it: 
  4.  

import DotNetUtils;

//Button Click Event for the Click Me Button

MyButton.onPress = function() {

       //instantiate your DotNetUtils Class

       var util = new DotNetUtils();

       //tell the object what Page on your site is handling the tracking

       util.TrackingPageName = "FlashTrack.aspx";

       //issue the track activity

       util.TrackActivity("MyButton", "Click");

};

 


So lets look at this line by line to understand what is happening.

 

import DotNetUtils;

 

This is the ever important import statement that you must use when referencing an external class (.as) file.  Its equivalent to C#'s using statement.  It allows you to import namespaces and classes from other files or assemblies.

 

MyButton.onPress = function() {

       //instantiate your DotNetUtils Class

       var util = new DotNetUtils();

       //tell the object what Page on your site is handling the tracking

       util.TrackingPageName = "FlashTrack.aspx";

       //issue the track activity

       util.TrackActivity("MyButton", "Click");

};

 

This  above function is the event handler for the buttons onPress event.

 

var util = new DotNetUtils();

 

This creates an instance of our DotNetUtils class named "util".  Class instantiation is a fundamental practice in OOP programming.

 

util.TrackingPageName = "FlashTrack.aspx";

 

Here we supply the DotNetUtils class its only parameter.  The Tracking Page Name, this tells the class what page to send the LoadVariables command too.

 

util.TrackActivity("MyButton", "Click");

 

This calls the only method of our class, TrackActivity.  We pass it two parameters.

  1. The Object: "MyButton" (this is the instance name - makes it easy to report on)
  2. The Activity: "Click" (this is the event that happened when the tracking command was issued)

So, that’s it for the flash part.  Once we issue that TrackActivity command the class takes over, it builds the query string from our supplied parameters and sends it off to our pre-determined tracking page.  From there ASP.NET puts it into a database.


Step Three : Creating the Visual Studio 2005 (ASP.NET) Web Application

Please note, I have included the entire VS 2005 project with this tutorial in the supplied attachment.   

In order to get your values to your database your going to need a server side language to talk to the db.  So we need to create a VS 2005 project that will be our asp.net web site.  Since this tutorial is more about interoperability between ASP.NET and Actionscript 2.0 im not going to go into great detail here, but I will provide a quick overview of what is needed.

 

  1. Create a web app that will house your flash movie.
  2. Create a page Separate from your flash movie display page, call it "FlashTrack.aspx"
  3. In the Code-behind file create the following private method:

 

 

/// <summary>

/// Logs the Activity to a Sql Database

/// </summary>

/// <param name="obj">The object being tracked</param>

/// <param name="act">The action to track</param>

private void TrackActivity(string obj, string act){

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TrackerDB"].ConnectionString))

{

//create a command element and the parametrs needed

SqlCommand cmd = new SqlCommand("INSERT INTO ActivityLog (Object, Activity, HitTime) VALUES (@Object, @Activity, @HitTime);", conn);

cmd.Parameters.AddWithValue("@Object", obj);

cmd.Parameters.AddWithValue("@Activity", act);

cmd.Parameters.AddWithValue("@HitTime", System.DateTime.Now);

try

   {

                 conn.Open();

                 cmd.ExecuteNonQuery();

                 conn.Close();

          }

          //if there is an error you can handle it here.

          catch (Exception ex)

          {

                 throw (ex);

          }       

}

}

 

  1. In the Page's Load Event Add the following Code:

//make sure something was sent

   if (Request.QueryString != null)

   {

        string myObj = "";

        string myAction = "";

        if (Request.QueryString["obj"] != null)

        {

             myObj = Request.QueryString["obj"].ToString();

        }

        if (Request.QueryString["act"] != null)

        {

            myAction = Request.QueryString["act"].ToString();

        }

        //Call to SQL Database

        TrackActivity(myObj, myAction);

       }


Basically what this does is the following:

 

  1. Check the querystring to make sure there are variables in it
  2. Puts the object and action into strings
  3. Sends the strings to a method designed to connect to an SQL Server Database and insert into a table named "ActivityLog" the following 3 parameters:
    1. Object
    2. Activity
    3. HitTime

That’s it really. Now all you have to do is put your flash movie on a page in your website, and add a page like our "FlashTrack.aspx" page to your site and you can be tracking all kinds of user behavioural data from your flash movies right into your SQL Server Databases.  Currently I use this type of tracking to track the following kinds of activities:

 

  • User Session starts (when a user first enters our site)
  • Clicks on products to "learn more" or "buy now"
  • Roll-overs we may have on movies that provide more product information
  • Log-in or Log-outs
  • Feedback clicks, or certain milestones you may have in your site.

You can even use this to send "silent" events to your site.  Because it uses LoadVariables it doesn't do anything to inform the user.  So you can be playing a video or commercial, or even song, and if it is in a flash format you could have actionscript events fire on certain key frames to log how long a person has been watching or listening to something in particular.

 

I have included the VS 2005 Project, the Flash Project, Flash file and Actionscript class file in the download.  I have also included scripts that will create the necessary SQL Server tables.  Once you have a utility class like this and learned the in's and out's of operating back and forth from flash you can create different pages to track different types of activities or send / receive data to and from flash.

 

Note about security:  Please note that since this is user behavioural collection you will need a terms and conditions page on your site somewhere and its always a good idea to include a privacy policy.   Also note that you will need to keep the asp.net and flash movie in the same site or else you will get Cross Site Security Violations.


Some Resources for further reading:

 

ASP.NET and the Querystring:

http://aspnet.4guysfromrolla.com/articles/020205-1.aspx

 

Integrating Flash with ASP.NET:

http://dotnetjunkies.com/Tutorial/986D1568-2686-435A-855A-5A95F25FFC71.dcik

 

LoadVariables and LoadVars:

http://www.actionscript.org/resources/articles/46/1/LoadVariables-and-LoadVars-Objects/Page1.html