Monday, November 28, 2011

Unlimited Scroll in ASP.Net DataList Control

Unlimited scroll is not a big deal, for example facebook news feed its scroll when user reach bottom of the page. Actually client side script check the scroll position the container, if the position is in bottom, the scripts request content form server and update the container. In here the container is a DIV tag, named holder, and put some style tag height, width and overflow.holder is hold the DataList

CSS for the holder.

Here I used Northwind database Products Table to demonstrate the unlimited scroll in this  article and used a Handler page, First time page loads with 10 records in DataList, take a look below.
        if (!IsPostBack)
            DataClass data = new DataClass();
            DataList1.DataSource = data.FirstTenRecords();
And in client side I set current item count to 10 and next item count to 0.
var current=10;
var next=0;
and call function for load next form javascript, it’s nothing but calling server via AJAX, ie requesting Handler page with a query string of start and next. below  image shows how the request url form client, I used firebug to show requests
lets look on loadNext
 var loadNext = function () {
            next = current + 10;
                url: "Handler.ashx?start=" + current + "&next=" + next,
                success: function (data) {
            current = current + 10;
Before calling the Handler page set next, after set current to current+10
  next = current + 10;
  current = current + 10;
To get the data from a specific row number I used a stored procedure, it will return my data, I want to send number of position, if I send start=10&next=20, It will return 10th to 20th row form the database.
USE [Northwind]
/****** Object:  StoredProcedure [dbo].[ProductPages]    Script Date: 11/28/2011 12:03:17 ******/
ALTER PROCEDURE [dbo].[ProductPages]
 @start int,
 @next int
SELECT ProductID,ProductName,UnitPrice FROM
   SELECT ROW_NUMBER() OVER(ORDER BY ProductID,ProductName,UnitPrice) NUM,
   * FROM Products
) A 
WHERE NUM >@start AND NUM <=@next
Now let take a look on how its work. everything works depends on holders scroll function. script check the scroll position of the container is bottom or not, if it on bottom, function call loadNext().
 $(document).ready(function () {
            $("#holder").scroll(function () {
                if ($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight()) {
Handler page is nothing, like a aspx page.Its call a class file DataClass, DataClass is simple class file to reduce bulky code in Handler page. It call the DataLayer and return the data from database, after do some format to fill on the DataList and write it on response.
public void ProcessRequest(HttpContext context)
        string startQstring = context.Request.QueryString["start"];
        string nextQstring = context.Request.QueryString["next"];
        //null check
        if ((!string.IsNullOrWhiteSpace(startQstring)) && (!string.IsNullOrWhiteSpace(nextQstring)))
            //convert string to int
            int start = Convert.ToInt32(startQstring);
            int next = Convert.ToInt32(nextQstring);
            //setting content type
            context.Response.ContentType = "text/plain";
            DataClass data = new DataClass();
            //writing response
            context.Response.Write(data.GetAjaxContent(start, next));
There is only one class file. But I put there class on that file.
1:DataClass :
  • Contain two function On handler page we are calling first function GetAjaxContent(start,end) it retrun the records from database. 
  • 2nd function loaad data on Page_Load even
2: Provide : Provide SqlConnection from web.config
3:DBHelper : Data layer Take a look

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

/// Summary description for DataClass

public class DataClass
    public DataClass()
    ///  return rows depend on position
    ///  if you need 10th to 20th you need to pass start=10 and end=20
database start position of one row
database end position of one row
    public string GetAjaxContent(int start, int end)
        string result = string.Empty;
        //adding sp params with values in Dictionary entry.
        Dictionary keyValPair = new Dictionary();
        keyValPair.Add("@start", start);
        keyValPair.Add("@next", end);

        DBHelper DBHelper = new DBHelper();
        //passing the Stored Procedure name and keyvalue pair
        DataTable dataTable = DBHelper.GetTable("ProductPages", keyValPair);
        if (dataTable.Rows.Count > 0)
            for (int i = 0; i < dataTable.Rows.Count; i++)
                result += string.Format(@"
", dataTable.Rows[i][0].ToString(), dataTable.Rows[i][1].ToString(), dataTable.Rows[i][2].ToString()); } } //this string is going to append on Datalist on client. return result; } /// /// function to bind data on page load /// /// public DataTable FirstTenRecords() { Dictionary keyValPair = new Dictionary(); keyValPair.Add("@start", 0); keyValPair.Add("@next", 10); DBHelper DBHelper = new DBHelper(); DataTable dataTable = DBHelper.GetTable("ProductPages", keyValPair); return dataTable; } } /// /// return sqlconnection string formweb.config file /// public class Provider { public static SqlConnection GetConnection() { return new SqlConnection(ConfigurationManager.AppSettings["SqlConnectionString"]); } } /// /// Data layer /// public class DBHelper { public DBHelper() { } SqlConnection con; SqlCommand cmd; SqlDataAdapter adapter; public DataTable GetTable(string SPName, Dictionary SPParamWithValues) { DataTable dataTable = new DataTable(); try { con = Provider.GetConnection(); //open DB connection con.Open(); cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = con; cmd.CommandText = SPName; foreach (KeyValuePair paramValue in SPParamWithValues) { cmd.Parameters.AddWithValue(paramValue.Key, paramValue.Value); } adapter = new SqlDataAdapter(cmd); adapter.Fill(dataTable); } finally { //close connection string con.Close(); } return dataTable; } }
If it not display properly please use the images
Download Source
Download full source code

Friday, September 30, 2011

Download Microsoft® Visual Studio® 11 Developer Preview

Visual Studio 11 Developer Preview is an integrated development environment that seamlessly spans the entire life cycle of software creation, including architecture, user interface design, code creation, code insight and analysis, code deployment, testing, and validation. This release adds support for the most advanced Microsoft platforms, including the next version of Windows (code-named "Windows 8") and Windows Azure, and enables you to target platforms across devices, services, and the cloud. Integration with Team Foundation Server allows the entire team, from the customer to the developer, to build scalable and high-quality applications to exacting standards and requirements.

Visual Studio 11 Developer Preview is prerelease software and should not be used in production scenarios. 

This preview enables you to test updates and improvements made since Visual Studio 2010, including the following:

  • Support for the most advanced platforms from Microsoft, including Windows 8 and Windows Azure, as well as a host of language enhancements. 
  • New features such as code clone detection, code review workflow, enhanced unit testing, lightweight requirements, production intelliTrace™, exploratory testing, and fast context switching. 

This preview can be installed to run side by side with an existing Visual Studio 2010 installation. The preview provides an opportunity for developers to use the software and provide feedback before the final release. To provide feedback, please visit the Microsoft Connect website.

The .NET Framework 4.5 Developer Preview is also installed as part of Visual Studio 11 Developer Preview.

Note: This prerelease software will expire on June 30, 2012. To continue using Visual Studio 11 after that date, you will have to install a later version of the software.

In order to develop Metro style applications, the Visual Studio 11 Developer Preview must be installed on the Windows Developer Preview with developer tools English, 64-bit. Developing Metro style applications on other Preview versions of Windows 8 is not supported.

System requirements

Supported Operating Systems: Windows 7, Windows Server 2008 R2
    • Windows 7 (x86 and x64)
    • Windows 8 (x86 and x64)
    • Windows Server 2008 R2 (x64)
    • Windows Server Developer Preview (x64)
  • Supported Architectures:
    • 32-bit (x86)
    • 64-bit (x64)
  • Hardware Requirements:
    • 1.6 GHz or faster processor
    • 1 GB of RAM (1.5 GB if running on a virtual machine)
    • 5.5 GB of available hard disk space
    • 5400 RPM hard drive
    • DirectX 9-capable video card running at 1024 x 768 or higher display resolution

What is new in VS2011
Source Download  Microsoft® Visual Studio® 11 Developer Preview

Tuesday, August 30, 2011

Download Microsoft Visual Studio 2010 SP1

MIcrosoft Visual Studio 2010 SP1 RTM
Microsoft released Microsoft Visual Studio 2010 SP1 RTM for all vs2010 products to developers.
Online Installer
Offline Installer
Offline Installer is an .ISO file. You can use daemon tools [download from here] to create virtual IDE devices.

Tuesday, February 1, 2011

Checking Username Availability using AJAX

Checking username in user registration page is common thing in these days. Now we can check how to this using AJAX., ie Check username availability without postback. To achieve this you need to know about Ajax. Ajax is Asynchronous JavaScript and XML. AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page [more].

Here I use two Class files and one Generic handler page to simplify code.

1: AjaxHelper
2: DataBaseHelper
3: Handler.ashx

Do not get confused, Client side javascript communicating sever with the help of Handler file, ie we send request to handler file, In the Handler file we create one instance of AjaxHelper Class and communicate with database with the help of DataBaseHelper Class

First we can check the sample images

User in Database

Now we can check how to send request to Handler Page, ie we do ajax calls to server, see the script below

Above we requested the handler file, Now we are going to check what handler file do when a request come from the client side.
first handler file check the query string. after create an instance of AjaxHelper class, it contain one boolean function called CheckUserNameAvailable(stirng username). if the value of CheckUserNameAvailable is true, it send response as "Available" else it send "Not Available".
public void ProcessRequest(HttpContext context)
        HttpRequest request = context.Request;
        HttpResponse response = context.Response;
        if (!string.IsNullOrEmpty(request.QueryString["uname"]))
            AjaxHelper ajaxHelper = new AjaxHelper();
            bool available = ajaxHelper.CheckUserNameAvailable(request.QueryString["uname"]);
            if (available)
Username Available
"); } else { response.Write("
Username Not Available
"); } } }

Next is what is happening AjaxHelper Class, here is do not use any store procedure, if you need you can use SP. I already mentioned that this class contain only one method, public bool CheckUserNameAvailable(string username)
in this class I select the users in usertable which username is equal to requested username.
public class AjaxHelper
    public AjaxHelper()
    public bool CheckUserNameAvailable(string username)
        DataBaseHelper DBHelper = new DataBaseHelper();
        string cmdString = string.Format("SELECT username FROM usertable  WHERE username ='{0}'", username);
        string user = Convert.ToString(DBHelper.ExecuteScalar(cmdString));
        if (string.IsNullOrEmpty(user))
            return true;
            return false;

Check the DataBaseHelper Class, in DataBaseHelper class we read connection string form web.config file. then create sql connection, set sql command object, open sql connection, execute sql command, close sql connection, dispose command and connection.

public class DataBaseHelper
    SqlConnection con;
    SqlCommand cmd;

    public DataBaseHelper()
    public object ExecuteScalar(string commandText)
        con = Provider.GetConnection();
        cmd = new SqlCommand(commandText, con);
            return cmd.ExecuteScalar();
        { throw; }

public class Provider
    public static SqlConnection GetConnection()
        return new SqlConnection(ConfigurationManager.AppSettings["sqlConn"]);

Connection string in Web.Config


Download source username availability in Ajax

Tuesday, January 25, 2011

Javascript Countdown timer

This post is mainly to understand, how to program a countdown timer using javascript. if you need to study more about javascript and javascript timer function go to and select Learn JavaScript.

Here I use two funtion to ActivateTimer() and Timer()

check the script

Check the Output

Example URL

Full code file

        <div ID="Label1" style="font-size:24pt;font-weight:bold;"></div>
        <input type="button" onclick="ActivateTimer();" value="Activate" />
        <script language="javascript" type="text/javascript">
            var min = 1;
            var sec = 59;
            var timer;
            var timeon = 0;
            function ActivateTimer() {
                if (!timeon) {
                    timeon = 1;
            function Timer() {
                var _time = min + ":" + sec;
                document.getElementById("Label1").innerHTML =_time;
                if (_time != "0:0") {
                    if (sec == 0) {
                        min = min - 1;
                        sec = 59;
                    } else {
                        sec = sec - 1;
                    timer = setTimeout("Timer()", 1000);
                else {
                    alert("Time is Over");


Limiting file size or getting file size of Upload file in ASP.Net

this is a small code snippet to limit file size on file upload

Asp.Net FileUpload control's FileBytes.Length returns file size in Bytes.
Here we want file size in MB. so we want to divide size by 1024*1024.

1024 kilobytes = 1 megabyte (MB)
1 Kilobyte = 1024 bytes

protected void Button1_Click(object sender, EventArgs e)
        //checking size 
        double fileSize =(double) FileUpload1.FileBytes.Length;
        double fileinMB = fileSize / (1024 * 1024);
        if (fileinMB > limit)
            Response.Write("Size is limited to 2MB");
        //upload file