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.

Example:
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)
{
base.RenderContents(writer);
writer.WriteBeginTag("img");
writer.WriteAttribute("name", this.UniqueID);
writer.WriteAttribute("src", ImageURL);
writer.WriteAttribute("onclick", "javascript:" + OnClientClick + " " + Page.ClientScript.GetPostBackEventReference(this, string.Empty));
writer.Write("/>");
}

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


Properties:
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.

State:
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
{
not_adequate,
average,
good,
helpful,
very_helpful
}

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)))
{
if(String.IsNullOrEmpty(firstState))
firstState = stritem;

if (isBreak)
{
nextState = stritem;
break;
}
if(!isBreak)
{
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!


Limitations:
> 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

Idea:
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.

Background:
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.


Theory:

@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 http://www.google.com/analytics.
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 http://www.google-analytics.com/ga.js and pages with URLs beginning with https:// will load the secure version at https://ssl.google-analytics.com/ga.js. 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.

References:
Basics of Web Analytics and terminologies:
http://www.thewebmarketingguy.com/web-analytics/index.html



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

Friday, November 20, 2009

Invalid memory location error with PHP, IIS and MS SQL/ My SQL

Invalid memory location error with PHP, IIS 5.1 and MS SQL Server 2005

There can be multiple reasons for this error:

@ Please recheck all the configurations settings that are suggested in PHP।CONFIG file that have been suggested when you install PHP on IIS Server with MS SQL Server 2005.

@ Also, check that you have loaded all extension dll’s in the phproot\ext\ folder and you have installed MS SQL server driver for PHP.

@ The most common reason for this error is because of the “ntwdblib.dll”. If you decide to use MS SQL server with PHP, you need to replace the default version of ntwdblib.dll file with the version number 2000.80.194.0. You can either get this MS SQL installation discs. Install the prerequisite files from Disc1 and it will install all needed dll’s. Or, you can download it from http://webzila.com/dll/1/ntwdblib.zip.

@ Run IISRESET command and then check your application.

@ If you are getting this error message with the My SQL, then it may be the case that the My SQL version is not compatible with the PHP version and you will need to upgrade My SQL to the higher version.

Thursday, September 24, 2009

ASP.NET 3.5 - Populate grid view based on value selected in the dropdown

Q:
Can we populate grid view dynamically based on dropdown value?
I have a dropdown list. When user selects a particular value from the dropdown list, the grid view records needs to be changed based on the value selected in dropdown.

A:
Continuing to earlier post where I have demonstrated how we can bind dynamic dataset to the grid view; I am going to explain how we can achieve this.

Task:
I have a dropdown list for divisions e.g. 1st year, 2nd Year etc. If user selects 1st Year from the dropdown, students list for Division 1 will be displayed in the grid view. If user selects 2nd year, they will be presented 2nd year student list.

Below are the steps that we will have to follow to achieve the given task:
1. Add dropdown list for all division values
2. On change of the selected index, bind new dataset to the grid view
3. It is important to enable “AutoPostBack” property for the dropdown field

Step 1:
Below is the code snippet to add dropdown field for all divisions on the form:

<div style="margin-top:10px;">
<asp:Label ID="lbl_SelectDivision" runat="server" Text="Select division:"> </asp:Label>
</div>
<div style="margin-top:10px;" >
<asp:DropDownList ID="ddl_Division" runat="server" >
<asp:ListItem Text="I st year" Value="ISTYEAR" />
<asp:ListItem Text="II nd year" Value="IINDYEAR" />
</asp:DropDownList>
</div>


This adds 1st Year and 2nd year as two division values to the dropdown list.

Step 2:
The next is to add an event which will be called on change of the value selected in the dropdown. The name of this event is “onselectedindexchanged”. We will call a method defined in the code behind class for this page. [You can achieve the same using design view. If you go to property window for the dropdown and double click on the event name, IDE automatically add this function for you.]

<div style="margin-top:10px;">
<asp:Label ID="lbl_SelectDivision" runat="server" Text="Select division:"> </asp:Label>
</div>
<div style="margin-top:10px;" >
<asp:DropDownList ID="ddl_Division" runat="server" onselectedindexchanged="ddl_Division_SelectedIndexChanged" >
<asp:ListItem Text="I st year" Value="ISTYEAR" />
<asp:ListItem Text="II nd year" Value="IINDYEAR" />
</asp:DropDownList>
</div>


Here is the code behind method. This function has a duty to collect the selected value of the dropdown and pass it to helper function which does work to dynamically populate records in grid view.

/*
*This event handler simply collect current selected value of the dropdown
*Passes it to the helper function which will actually populate dynacmic data to grid view
*/
protected void ddl_Division_SelectedIndexChanged(object sender, EventArgs e)
{ PopulateStudentsList(ddl_Division.SelectedValue.ToString());
}


PopulateStudentsList” is the method which we have seen in earlier post modified a little bit to accept the selected value as a parameter and use it for further processing.

public void PopulateStudentsList(string pm_selectedDivision)
{
gv_StudentsList.DataSource = getStudentList4Division(pm_selectedDivision);
gv_StudentsList.DataBind();
}

Step 3:
You are yet now done. Up to now, you have all source code ready to wok fine for your requirement. But the change in dropdown value will not call your event handler defined in step 2.
In order to fire this event handler, you must submit the page whenever you change the dropdown value. This is achieved using “AutoPostBack” property set to true for the dropdown field. “AutoPostBack” property if enabled - helps you to submit your page automatically whenever there is a change or action has been made on the control.

<div style="margin-top:10px;">
<asp:Label ID="lbl_SelectDivision" runat="server" Text="Select division:"> </asp:Label>
</div>
<div style="margin-top:10px;" >
<asp:DropDownList ID="ddl_Division" runat="server" onselectedindexchanged="ddl_Division_SelectedIndexChanged" AutoPostBack="True" >
<asp:ListItem Text="I st year" Value="ISTYEAR" />
<asp:ListItem Text="II nd year" Value="IINDYEAR" />
</asp:DropDownList>
</div>


Here is the result after you change the value from 1st Year to second your.



Note: If you do not want to submit the page on change of dropdown value; best approach is to use AJAX – next topic of discussion :)!

Monday, September 21, 2009

ASP.NET 3.5 - How to populate grid view dynamically using dataset

Q:
I have a req. where I want to display the list of students. The records to be displayed are based on the filtered criteria; also the columns to be displayed in the grid are decided at run time.

A:
You have a grid view defined in your page as below:

/* grid definition - spaces are added to render html tags as text
between tags */
<div style="margin-top:10px;" >
<asp:Label ID="lbl_StudentsList" runat="server" Text="Student's List:" >
</asp:Label>
</div>

<asp:GridView ID="gv_StudentsList" runat="server" >
< emptydatarowstyle backcolor="LightBlue" forecolor="Red"/>
<EmptyDataTemplate>

<asp:Label runat="server">No student found. <
/asp:Label>

</EmptyDataTemplate>
</asp:GridView>
</div>

You have to call the method in an event on which you want to populate the records in grid view. I will call this method (Method definition is given below) on load event of the page.
/* Call method on particular event */
protected void Page_Load(object sender, EventArgs e)
{
PopulateStudentsList();
}

public void PopulateStudentsList()
{
/* This defines data source for the grid as dataset returned from the
method and then bind it to grid to see the records in the grid in action */
gv_StudentsList.DataSource = getStudentList4Division("ISTYEAR");
gv_StudentsList.DataBind();
}

Now, we will write a method which will populate grid view with data and the columns to be added - defined dynamically inside the method.
/* This method constructs data set using data table */
public DataSet getStudentList4Division(string pm_strDivision)
{
DataSet dsListStudent = new DataSet();
DataTable dt = new DataTable();

/* This example works but is not the standard way to populate data from
DB – this is just for demonstration purpose
You need a database named
Quickstart in your backend with Student table having schema as columns specified
as per req. */

String connString = "Data Source=.;Initial
Catalog=QuickStart;Integrated security=true";

SqlConnection sqlConnect =
new SqlConnection(connString);
sqlConnect.Open();
SqlCommand cmd = new
SqlCommand("select * from Student WHERE division ='" + pm_strDivision + "'",
sqlConnect);
SqlDataReader sdr = cmd.ExecuteReader();

if
(sdr.HasRows)
{
//Prepare data table columns
string strfirstname =
"";
string strlastname = "";
DateTime strdob;
string strcity = "";
string strreligion = "";

/* These are the column headings */
dt.Columns.Add("First name", typeof(string));
dt.Columns.Add("Last
name", typeof(string));
dt.Columns.Add("Date of birth", typeof(DateTime));
dt.Columns.Add("City", typeof(string));
dt.Columns.Add("Religion",
typeof(string));

while (sdr.Read())
{
strfirstname =
sdr["FirstName"].ToString();
strlastname = sdr["LastName"].ToString();
strdob = Convert.ToDateTime(sdr["DateOfBirth"]);
strcity =
sdr["City"].ToString();
strreligion = sdr["Religion"].ToString();

/*
This line populates value in the data table */
dt.Rows.Add(strfirstname,
strlastname, strdob, strcity, strreligion);
}

}

//Add Table
to dataset
dt.TableName = "Students list";
dsListStudent.Tables.Add(dt);

sdr.Close();
sqlConnect.Close();

return dsListStudent;
}
The result of the data source in the grid view will look as below:

In next post, we will see how to populate grid based on the value selected in the dropdown list using the above scenario.

*Please note that the code explored above is working but has not been validated for different unit tests like positive test or negative test.

*Schema for the table student is as below:
CREATE TABLE [dbo].[Student](
[ID] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[FirstName] [varchar](80) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[LastName] [varchar](80) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[DateOfBirth] [datetime] NULL,
[City] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PanNo] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Religion] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Cast] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Division] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]

Thursday, September 17, 2009

C# - Hashtable and ArrayList

Q:
What is “Hashtable”? What are the benefits of it over Arraylist?
I am thinking of using Arraylist or Hashtable to group and then sort near about 100000 of records. Which collection will be better option for me? Why?

A:
Hashtable is one type of collection supported by C#. It’s a collection of items in key value pair. Every item in the Hashtable has a key with pointer to its linked value. The key and the value can be any object. Key must be unique value. Hashtable is useful when you need to store data in a key and value pair.

A Hashtable is better for looking up values based on the key, but you can't really sort it - it maintains its own 'internal sort' to optimize the lookups.

So, if you want to lookup values then it's better to use a Hashtable, if you want to sort all the items into a particular order then use the Arraylist.

A wrapper class can be designed that will make use of internal hashtable to provide search on items and a list for iteration and sorting.

Trick for rapid fire developers to get items sorted from hashtable:
Hashtable h = new Hashtable();
h.Add(1, 1);
h.Add(2, 5);
h.Add(3, 3);
ArrayList l = new ArrayList(h.Values);
l.Sort();
*Values in hashtable should be numeric values.

.NET 2.0 also offers Dictionary collection. It is a mix between hashtable (sort and identify objects of any type by a key) and an Arraylist (objects of a specified type).