Wednesday, August 4, 2010

Multiple state box in ASP.NET 3.5

We usually play with the checkboxes/ radio buttons when we provide choices for the user. But how will it be interesting to use the old style checkboxes where my choices (I will call them as states) are Accept, Reject, or Tentative? For more examples, if I would like to provide more states not just two, and want to represent each state with unique image then how can I achieve it?

Here is the example which goes out of the box to use styling images to represent each choice that users can select.

We will take below example and complete this assessment.

I would like to collect reviews from the users about my articles. For that I would like to provide them the following options:
- Not adequate
- Average
- Good
- Helpful
- Very helpful

All reviews will be presented using stylish images. User will click on the first state i.e. Not adequate. If he would like to increase his/her rating to second level, simply click on the image again. This will show an image for the second state. For the next level, simply click again and it will show you the next level state.

I should also be able to add more states dynamically with minimum efforts.

Evaluating multiple approaches:
For this, we will not use the existing checkbox/ radio button control as they do not provide enough scope for this requirement.

Initially I thought it will be simple if I use the toggle button extender control from the Ajax. When I completed the work using it, I found that before loading the actual styling images, it still shows the default checkboxes for fraction of seconds. Also it puts other limitations that we can’t read its states for more than 2 values. So I thought that this will be much easier using our own control.

So I did plan to develop a custom control for this. To respect that the initial idea came from the checkboxes and toggle button extender, I will name my custom control as “ImageCheckbox”.

Writing Custom control class:
You need to create a new class file with the name as ImageCheckbox. You can read more on how to create custom control over the net. Here is the complete source code for this class. This is simple web server control that inherits directly from WebControl class.

using System;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace ImageCheckbox
public class ImageCheckbox : WebControl, IPostBackEventHandler
public ImageCheckbox()
: base(HtmlTextWriterTag.Span)
State = "unchecked";
ImageFormat = ".gif";

public event EventHandler Click;

/// Call JavaScript client side functions. Put the JavaScript in string format.

public string OnClientClick
get { return ViewState["onclientclick"] as string; }
set { ViewState["onclientclick"] = value; }

/// Location of the images. This is the path where all the images representing each state will reside.

public string ImagePath
get { return ViewState["imagepath"] as string; }
set { ViewState["imagepath"] = value; }

/// Format of the images. All images representing states should be of the same format.

public string ImageFormat
get { return ViewState["imageformat"] as string; }
set { ViewState["imageformat"] = value; }

/// Current state value. Assign a string value representing the current state.

public string State
get { return ViewState["state"] as string; }
set { ViewState["state"] = value; }

private string ImageURL { get {
string lImageURL = String.Empty;
lImageURL = ImagePath;
if (!(ImagePath.LastIndexOf('/') == (ImagePath.Length - 1)))
lImageURL += "/";
lImageURL += State + ImageFormat;
return lImageURL;
} }

protected override void RenderContents(HtmlTextWriter writer)
writer.WriteAttribute("name", this.UniqueID);
writer.WriteAttribute("src", ImageURL);
writer.WriteAttribute("onclick", "javascript:" + OnClientClick + " " + Page.ClientScript.GetPostBackEventReference(this, string.Empty));

public void RaisePostBackEvent(string eventArgument)
Click(this, EventArgs.Empty);

This accepts following properties from the user.

Image Path:
Location of the images. This is the path where all the images representing each state will reside.

Image Format:
Format of the images. All images representing states should be of the same format.

Current state value. Assign a string value representing the current state.

On Client Click:
Call JavaScript client side functions. Put the JavaScript in string format. This is to add more flexibility for the developers allowing them to extend the solution at the next level as per their requirements.

Using custom control in our application:
This is very important part of this problem. This part will explain how to best use the dynamic nature of the custom control we just built.

Add folder and images for state values:
As we have 5 states (options) for the ratings that I will be collecting from the users, I will need 5 images representing each state value. All the images must use the same image format (file extension should be the same).
Create a new folder in your application (most likely under images folder which you are using to store all the images that your application needs). I will name my folder as “ratings”. Add these images into this folder.

Here are my file names:
- not_adequate.gif
- average.gif
- good.gif
- helpful.gif
- very_helpful.gif

Suppose I am writing default.aspx page in which I will include the above control.

We will get back to this point on how to include the Image checkbox custom control in our page. Before that we will look at other important aspects of this solution.

Using Enum to represent collection of the state values:
I will use enum to make this solution strongly bounded with the requirement.

Here is my Enum which defines behavior of the states. (This will go into the default.aspx.cs file.)

public enum CheckboxStates

Now, we will go back to default.aspx page and get the custom control added to the page (you can read more on how to add custom control to the page over the net).

Register custom control:
Add below line in your aspx page to register your custom control.

(Ignore the space before or after <> )

< %@ Register Assembly="ImageCheckbox" Namespace="ImageCheckbox" TagPrefix="cm" % >

Add it in the form:
Add the instance of the custom control in the form and set appropriate values of the properties.

< id="imgCheckbox" onclick="imgCheckbox_Click" runat="server" state="average" onclientclick="alert('hi....');" imageformat=".gif" imagepath="images/ratings/"> < /cm:imagecheckbox >

Assign the state to default value. Here the default value given is ‘average’.

OnClientClick property is used to show the alert box saying ‘hi…’ just to present how it works or how it can be used. You can call any function of your need.

Here the image format is ‘.gif’.

Path for the images is ‘images/ratings’.

Very important is to add OnClick event. The current version of this custom control uses post back technique to change the state of the control. Modifying it to handle client side state change will be very good improvement here.

I wanted it do at server side, just to explore that we can even call a server side script to execute server side code and perform some business logic with every change of state. I can store the frequency of user’s choice in the database with the onclick event.

Server side hander to change control states:
Here is my server side code for the OnClick event. This handles change in state one by one based on the values specified in the Enum.

protected void imgCheckbox_Click(object sender, EventArgs e)
string firstState = String.Empty;
string nextState = String.Empty;
string currentState = imgCheckbox.State;
bool isBreak = false;

foreach(string stritem in Enum.GetNames(typeof(CheckboxStates)))
firstState = stritem;

if (isBreak)
nextState = stritem;
if(stritem == currentState)
isBreak = true;
if (String.IsNullOrEmpty(nextState))
nextState = firstState;

imgCheckbox.State = nextState;

//Do more stuff


Adding more state values:
Just add the new images for your new states in the ratings folder and add the name of the files in the Enum. That’s it… you are done!

> I will try to get the next version of the solution here which will handle changing states at client side soon.

> I will also try to add more properties in order to show the text value for the state providing more utilization of the solution to replace the normal checkboxes or toggle button extender in our application.

> The sequence of the states should be monitored and should appear as they are listed in the Enum.

Thank you.

Let me know your suggestions or improvements that you think are important for this solution.

Tuesday, June 22, 2010

Web Analytics explained using Google Analytics

This article discuss about:
o Web Analytics in general
o Implementing Google Analytics in your website

Web Analytics

It’s a measurement of the website usage by users. This measurement includes various parameters or units such as hit counts, downloads, errors, visitors area etc.

The web allows you to publish your business or content to a very large audience, very easily. But that does not change the need to make sure you understand your audience. By connecting with your visitors, you make them feel more comfortable. If your site “thinks” the way they do, it becomes natural and they will recommend it to friends. Web analytics can give you the power to know how your visitors use your site, to know how they react to your site (or changes on your site) and to improve the quality of the site. The better your visitors feel about using your site, the better your bottom line will be.

If your site is commerce-related and you have competition, you can be sure that your competitors are also using web analytics (or some related marketing techniques) to gain more customers. In particular, you can use web analytics to gain not just more customers, but more valuable customers.

In addition to design (or behavior) analysis, web analytics can be used to diagnose server or site problems, and measure the effectiveness of marketing and advertising campaigns.


@The Benefits of Web Analytics
As a marketer, you realize the need to understand the results of the investments you make in order to achieve the goals you've established for your website - whether those goals are actual online purchases, or requests for information, downloads of product demos or white papers, etc. Within search engine marketing campaigns your "investment" can, and must, be broken down to an extremely granular level in order to measure - and more importantly - maximize, your results. You need to know what each keyword is generating for you in terms of both traffic and ROI - both from natural search engine optimization and pay-per- click programs. Only then can you and your The Web Marketing Guy campaign management team make the most informed decisions regarding changes to your targeted keyword list in order to maximize your ROI.

a. Measuring and maximizing ROI• Identify which referral sources (i.e. search engines, e-mail campaigns, newsletter sponsorships, print ads and affiliates) generate the most revenue, products, customers and orders for your business.
• Which sources have the highest browse-to-buy ratios and the highest overall revenue potential.
• Actionable information enables timely decisions, such as continuing a successful marketing strategy or stopping a campaign going nowhere.
• Measure-respond-measure scenario
• Online channel is keeping up with your overall business goals
• Visitor traffic and e-commerce sales numbers justifying the resources put into them
b. Better Target Your Marketing Efforts• Determine which visitor groups are most likely to convert into customers, members or subscribers
• Define visitor groups by the content they read, the actions they take, even the URL they come from.
c. Optimize Conversions
• Click-path tracking to maximize the rate at which your Web site visitors convert into customers, subscribers or members.
• Adjusting the content and navigation of your site in response to your reports
d. Pinpoint Online Revenue-Enhancing Opportunities
• e-commerce intelligence tying in click-stream behavior (the page-by-page paths visitors take through a site) with purchasing activity to unveil key shopping patterns and trends
• Identifying online revenue-enhancing opportunities, such as product cross-sells, the most profitable referring sources of traffic, and the ability to see which keywords, search engines or promotions drive the most sales.
• Determine upward and downward trends in a particular product, and which products would function best as loss leaders to attract new customers.
e. Save On Customer Support - improving the efficiency of your online support to dramatically reduce your offline costs.
f. Help Customers Help Themselves - path analysis indicates whether or not visitors are finding the information they need within.
• Early detection system for possible problems
• Real-time analysis of visitor interaction with your Web site can prompt changes to ensure that your products meet the needs of your customers, and uncover potentially larger support issues before they become headaches.

@The basics of Web Analytics measurement
Web analysis is not only the hits counted to your website. Mostly the hits counted are only for the home page and not all relative pages and various actions made by the users.

Hit counters just provide basic information. Web analytics includes several other units as a part of common measurement:

o Hits and impressions
o Page views
o Downloads
o Errors
o Bytes
o Users
o Unique hosts
o Visits or sessions
o Visit tracking with cookies

@Web Analytics Vendors
• Urchin
• WebTrends
• NetTracker
• DeepMetrix
• Core metrics Smart Tags
• Google Analytics

More about Google Analytics:

Google Analytics is the enterprise-class web analytics solution that gives you rich insights into your website traffic and marketing effectiveness. Powerful, flexible and easy-to-use features now let you see and analyze your traffic data in an entirely new way. With Google Analytics, you're more prepared to write better-targeted ads, strengthen your marketing initiatives and create higher converting websites.

How Google Analytics helps you:
 Gives an idea on how people visits site, how they navigate and who becomes customers
 Let you know the important keywords for your site
 Page visits, click through rates, number of visits for a definite period, cost, count of visitors across the cities, conversion rates
 Summary of effectiveness of the campaigns from where the sites are getting hits
 Graphics reports and dashboards which helps analyzing data very quickly
 Customizable reports
 Sending reports via email or data export

Quick features of Google Analytics:
 Analytics Intelligence
 Advance segmentation
 Flexible customization
 Ecommerce tracking
 Track your business goals against threshold levels that you define
 Mobile tracking
 Data export API
 Advanced Analytics tools
 Benchmarking

Now, let us discuss how to install Google Analytics and customize an account to get the exact details which Business wants to analyze.

Signing up for Google Analytics

To create an Analytics account:
1. Visit
2. Enter your Google Account email and password and click Sign In. If you don't have a Google Account, click Sign up now to create one.
3. Click Sign Up.
4. Enter your Website's URL, making sure to select either http:// or https:// from the drop-down list. Enter a nickname for this account in the Account Name field, then click Continue.
5. Enter your contact information and click Continue.
Read the Google Analytics Terms of Service. If you agree to these terms, select the Yes checkbox and click Create New Account to continue.

Finding Google Analytics tracking code for the profile

To access your tracking code:

1. Sign in to Google Analytics.
2. From the Analytics Settings page, find the profile for which you would like to retrieve the tracking code. Please note that tracking code is profile-specific.
3. From that profile's Settings column, click Edit.
4. At the top right of the Main Website Profile Information box, click Check Status.
5. Your tracking code can be copied and pasted from the text box in the Instructions for adding tracking section.

Setting Goals and Funnels
If your website is designed to drive visitors to a particular page, such as a purchase or email signup page, you can track the number of successful conversions using goals and funnels in Google Analytics.

 A goal is a website page a visitor reaches once she or he has made a purchase or completed another desired action, such as a registration or download.
 A funnel represents the path that you expect visitors to take in order to reach the goal. Defining these pages allows you to see how frequently visitors abandon goals (and where they go instead) and the value of the goal.

Tagging Advertisement campaigns
Tagging your online ads is an important prerequisite to allowing Google Analytics to show you which marketing activities are really paying off. Tagging involves inserting and defining specific variables into the links that lead to your website.

Setting Filters
A filter is used to include, exclude, or change the representation of certain information in a report.

Enable Ecommerce Transaction tracking
With some simple additions to the receipt page of the website, Google Analytics can automatically detect and record transaction and product information. The required information is placed into a hidden form which is parsed for transaction and product information. Most template driven e-commerce systems can be modified to include this information in the receipt.

You'll also need to enable e-commerce reporting for your website's profile:

From the Analytics Settings page, click Edit next to the profile you would like to enable.
Click Edit from the Main Website Profile Information box
Change the E-commerce Website radio button from No to Yes.

Implementing Google Analytics for a website in general

Basic installation:

Copy and paste the code segment into the bottom of your content, immediately before the tag of each page you are planning to track. If you use a common include or template, you can enter it there.

For Data driven or page with Frames:

Database driven sites - Insert the tracking code on your index.php page or equivalent (eg. default.php, index.cfm).

Pages with frames - A web page containing frames will generate multiple pageviews: one for the framing page (containing either a FRAMESET or IFRAME tag within its HTML code), and one for each page shown in a frame. As a result, pageviews may be somewhat inflated. Even if a page on your site only appears as a frame for another page, we still recommend tagging it with the entire tracking code. If a visitor reaches the page through a search engine or a direct link from another site and the page doesn't contain the tracking code, the referral, keyword and/or campaign information from the source will be lost.

For Secure pages (https):

The Google Analytics tracking code is now the same for both secure and non-secure websites. The new tracking code detects the protocol of the page being tracked and matches the security of your web page automatically. Pages with URLs beginning with http:// will download the non-secure version at and pages with URLs beginning with https:// will load the secure version at No modification of the tracking code on secure pages is required.

Although the previous version of the tracking code (urchin.js) required you to copy/paste special tracking code into your secure pages, this is no longer necessary if you are tracking your site with ga.js. You can use the same tracking code on both secure (https://) and non-secure (http://) pages.

Basics of Web Analytics and terminologies:

Web Metrics
Several units or measurements which are commonly referred to when doing web analysis
Number of hits to the website