Common SELECT Statements (SQL Server) Monday, Jul 18 2011 

Followings are some examples of using SELECT statement. My table name tblTest. Followings are columns. (TestID, TestName, TestDate, TestCity )

1) Select * from tblTest (Returns all columns/Rows)

2) Select * from tblTest Where TestID=2 (Returns the row/s which TestID has value 2)

3) Select * from tblTest where TestID Between 10 and 20 (Return all rows between 10 and 20, this result includes 10 and 20)

4) Select * from tblTest Where TestCity in (‘New York’,’Washington’,’California’) (Returns all rows which city is NewYork, Washington, california)

5) Select * from tblTest Where TestName Like ‘A%’ (Return all rows where the name starts letter A)

6) Select * from tblTest Where TestName Like ‘%A’ (Return all rows where the name ends letter A)

7) Select * from tblTest Where TestName Like ‘[ABC]%’ (Return all rows of name start with A / B / C)

8) Select * from tblTest Where TestName Like ‘[^ABC]%’ (Return all rows of name not start with A and B and C)

9) Select (TestName+space(1)+TestCity) as Address from tblTest (Returns single column address, name and city added together with a space)

10) Select * from tblTest Where TestName IS NULL (Return all rows which TestNane has null values)

11) Select * from tblTest Where TestName IS NOT NULL (Return all rows which TestNane has not null values)

12) Select * from tblTest Order By TestID Desc (Sort the result set descending order, Asc or not using any sort Ascending order)

13) Select ‘Visual Studio’ as IDE, ‘2010’ as Version (Creating memory resident result set with two columns[IDE and Version])

14) Select Distinct TestID from tblTest (Returns unique rows based on TestID)

15) Select Top 10 * from tblTest  (Return 10 customers randomly)

16) Select getdate() (Shows the current date)

17) Select db_name() (shows the database name which you are working on)

18) Select @@Servername (Shows name of the server)

19) Select serverproperty (‘Edition’) (You can pass following ServerName, Edition, EngineEdition, ProductLevel to get current information about the server)

20) Select user_name() (Get current user)

21)  Select *  into #test from tblTest  (Create temporary table #test and insert all records from tblTest)

22)  Select Max(TestID) from tblTest (Returns Maximum TestID from tblTest)

23)  Select * from tblTest Compute Max(TestID) (Returns two result sets – getting all rows and maximum value of TestID)

24) Select FirstName, LastName,  Salary, DOB,

Case Gender
When ‘M’ Then ‘Male’
When ‘F’ Then ‘Female’
From Employees

(This Change Gender fields as if M then prints Male and if F then prints Female)  

SQL SERVER – Delete Duplicate Records – Rows Wednesday, Jun 15 2011 

Following code is useful to delete duplicate records. The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3.

FROM MyTable
FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn3)

To download new features in ASP.Net 4.0 click here. Wednesday, Jun 15 2011 


To download new features in ASP.Net 4.0 click here.

OOPS in a nutshell Thursday, May 12 2011 

OOPS – Object Oriented Programming Languages & Systems.
Everything in the world is an object. The type of the
object may vary. In OOPS, we get the power to create
objects of our own, as & when required.

Class – A class is an organized store-house in
object-oriented programming that gives coherent
functional abilities to a group of related code. It is
the definition of an object, made up of software code.
Using classes, we may wrap data and behaviour together
(Encapsulation). We may define classes in terms of
classes (Inheritance). We can also override the
behaviour of a class using an alternate behaviour

Using inhertance, we may assign different traits to different
classes. Yet, the child classes will inherit some common
traits from the base class. As in the figure above, the
classes for “Permanent” and “Wage Worker” will inherit
some common traits from the class of “Employee”.

A class may contain class members like fields, properties,
events & methods with different types of access modifiers
like private, public, protected or friend, to process the
way they are accessed. In VB.NET, a class may be declared
as below…

Public Class SampleClass
‘define class members
End Class

Key Concepts of .NET – To work with classes and modules,
the key concepts to know are definition, access, inheritance,
constructors, destructors, delegates, abstract classes & interfaces..

Class members – The different types of entities in a class,
like fields, properties, events & methods.

Object – An object is an instance of a class. This instance
may be used to access the members of the class. It is pretty
easy to define an object. See sample code below…

Dim objSampleObject as SampleClass

Structure – It is a bit similar to a class. Semantically,
structures are known as value types, while classes as reference types. We do’nt instantiate an object using the New keyword while working with a structure. We can not inherit from a structure.

Public Structure Student
Public RollNo as Integer
Public Name as String
End Structure

Dim objStud as Student

Here, note that the object objStud is not exactly an instance,
it is a simple object (object of a structure) that is used to
access the members of this structure. It would have behaved
differently had it been an object of a class, as it would have
invoked the constructor associated with the class.

Public Class ClassCalc
Public Function FnAdd(ByVal dblA as double, ByVal dblB _

as double) as Double
FnAdd = dblA + dblB
End Function
End Class

Now, lets make use of the method FnAdd defined in the class
above. To use it, first create an object of this class, say
objX. Using this object, we can invoke the methods of this
class. See code below…

Dim objX as ClassCalc
Dim dblResult as Double
dblResult = objX.FnAdd(4.56,2.35)

Property – A property is a thing that describes the features of an object. A property is a piece of data contained within a class that has an exposed interface for reading/writing. Looking at that definition, you might think you could declare a public variable in a class and call it a property. While this assumption is somewhat valid, the true technical term for a public variable in a class is a field. The key difference between a field and a property is in the inclusion of an interface.

We make use of Get and Set keywords while working with
properties. We prefix the variables used within this code block with an underscore. Value is a keyword, that holds the value
which is being retrieved or set.

Private _Color As String
Public Property Color()
Return _Color
End Get
Set(ByVal Value)
_Color = Value
End Set
End Property

Event – An action that an object does. When something happens, we say an event has happened. For example, when a button is clicked, we say it is the click( ) event. When a mouse hovers on an image, we say the mouseover( ) event has taken place.

Access Modifiers – Keywords used to vary the way members of a class are used. Following are different types…

1) Public – These classes can be used anywhere in the code.
There are no restrictions.

Available only to code outside our class

2) Private – These classes are accessible only within their
declaration contexts. This includes nested procedures. When a variable is declared Public inside a Private class, it is
accessible only from inside that class.

Available only to code inside our class

3) Protected – These classes extend the accessibility of their
members to their child classes (means, to the classes that derive from them). They extend their members to both themselves & their child classes.

Available only to classes that inherit from our class

4) Friend – Friend access means that elements are accessible only within the program. Friend is the default access modifer for any class that does not have a modifier.

Available only to code within our project/component

5) Protected Friend – Available only to classes that inherit from our class (in any project) or to code within our project/component. This is a combination of Protected and Friend.

Default – A Default property is a single property of a class that can be set as the default. This allows developers that use your class to work more easily with your default property because they do not need to make a direct reference to the property. Default properties cannot be initialized as Shared or Private and all must be accepted at least on argument or parameter. Default properties do not promote good code readability, so use this option sparingly.

Overloads – The Overloads property allows a function to be
described using deferent combinations of parameters. Each
combination is considered a signature, thereby uniquely defining an instance of the method being defined. You can define a function with multiple signatures without using the keyword Overloads, but if you use the Overloads keyword in one, you must use it in all of the function’s Overloaded signatures.

Shared -The Shared keyword is used in an inherited or base class to define a property or method as being shared among all instances of a given class. If multiple instances of a class with shared properties or methods are loaded, the shared properties or methods will provide the same data across each instance of the class. When one class alters the value for a shared property, all instances of that class will reflect the change. Shared properties of all instances of the class
point to the same memory location.

Overridable -The Overridable keyword is used when defining a property or method of an inherited class, as overridable by the inheriting class.

Overides – The Overides keyword allows the inheriting class to disregard the property or method of the inherited class and implements ts own code.

NotOverridable – The NotOverridable keyword explicitly declares a property or method as not overridable by an inheriting class, and all properties are “not overridable” by default. The only real advantage to using this keyword is to make your code more readable.

MustOverride – The MustOverride keyword forces the inheriting class to implement its own code for the property or method.

Shadows – The Shadows keyword will effectively hide all of the other methods in the baseclass. It is like forcefully getting rid of the overloading that has been done on the methods of the base class.
The Shadows keyword works like the Overloads keyword except that with shadows we do not have to follow rules such as implementing the same signature. The Shadows keyword does not require the consent (override ability) of the inherited class to replace the property or method’s implementation code. A method does not have to be defined as overridable for the Shadows keyword to work. Read the example…

‘This is the Base Class
Public Class Parent
Public Sub MyProc(ByVal num As Integer)
MsgBox(“Number in Parent is ” & num)
End Sub

Public Sub MyProc(ByVal st As String)
MsgBox(“String in Parent is ” & st)
End Sub
End Class

‘This is the Child Class
Public Class Child
Inherits Parent
Overloads Sub MyProc(ByVal num As Integer)
‘overloads the method with the same parameter list
MsgBox(“Number in Child is ” & num)
End Sub

Overloads Sub MyProc(ByVal ch As Char)
‘ overloads the method
MsgBox(“Character in Child is ” & ch)
End Sub
End Class

When we execute the following code…
Dim c As New Child()

‘ prints out “String in Parent is Hello Wazzup!”
c.MyProc(“Hello Wazzup!”)

‘ prints out “Number in Child is 12”

‘ prints out “Character in DerivedClass is B”

When we use Shadows keyword…
Public Class ChildNumber2
Inherits Parent
Shadows Sub MyProc(ByVal num As Integer)
‘ hides all the different argument list
MsgBox(“Number in ChildNumber2 is ” & num)
End Sub
End Class

Dim c2 As New DerivedClass2()
c2.MyProc(7) ‘only one method is exposed, rest of the
‘methods are hidden

Constructor – When a class instance is created in our code,
a special method of that class, called the constructor, is called. Similarly, when the class is destroyed, the destructor
method is called. These are general terms and usually not the actual member names in most object-oriented languages. It is initialized using the keyword New, and is destroyed using the keyword Finalize. In .NET, we tend to forget using Finalize as
the instances(means the object) are automatically destroyed by the Garbage Collecter, when the object is not in use by he CLR(Common Language Runtime).

Dim objSampleObject as New SampleClass
‘ write the code here…

We can add parameters to the constructors. This was’nt allowed in VB6. We can overload the constructors, change the order of parameters, datatypes of parameters which ultimately change the way the constructor works whenever an instance of that class is invoked.

Also note that a constructor can have any access modifier. If
no argument is added in a constructor, VB.NET adds a no-argument constructor during compile time. It adds the Public Sub New( ) with the class declared, if no argument is passed in the constructor. The following code is added…

Public Class ClassA
Public Sub New( )
End Sub

However, when the constructor is added with parameters, the following code is generated…

Public Class ClassA
Public Sub New(ByVal SomeString as String )
End Sub

When a child class’ object is declared, the child class
constructor & its parent class constructor, both are invoked.
Read example below for more clarity…

Public Class Books
Public Sub New()
System.Console.WriteLine(“Book’s constructor.”)
End Sub

Public Sub myProc()
System.Console.WriteLine(“This is a book.”)
End Sub
End Class

Public Class Authors : Inherits Books
Public Sub New()
System.Console.WriteLine(“Author’s constructor.”)
End Sub
End Class

When the Authors class’ constructor is invoked, like in the
following code, the Books class’ no-argument constructor is also called.

Dim author As Authors
author = New Authors()

The result on the console will be…

Book’s constructor.
Author’s constructor.

If the base class does’nt have a no-argument constructor, then it would result in a compiler error. Hence, we need to use the MyBase keyword with the constructor. Our child class will look like this…

Public Class Authors : Inherits Books
Public Sub New(ByVal SomeString As String)
System.Console.WriteLine(“Authors’s constructor.”)
End Sub
End Class

If a class is not inheriting from any base class, then it will
call the base class constructor of System.Object if we are using MyBase.New( ). Summarizing constructors, whenever we initiate a constructor, the following things happen…

Base class constructor is invoked.
Class level variables are initialized.
Code in the class constructor gets executed.
If the argument name passed in the constructor, is same as the variable name used in the constructor, we use the Me keyword to refer to the constructor variable. For example if the variable name is SomeString, and the parameter passed is also SomeString, then the variable is referred as Me.SomeString.

Abstract Class – They are classes that cannot be instantiated. We cannot create an object from such a class for use in our program. We can use an abstract class as a base class, creating new classes that will inherit from it. Creating an abstract class with a certain minimum required level of functionality gives us a defined starting point from which we can derive non-abstract classes.

An abstract class may contain abstract methods & non-abstract methods. When a class is derived from an abstract class, the derived class must implement all the abstract methods declared in the base class. We may use accessibility modifiers in an abstract class (unlike in Interfaces).

An abstract class can inherit from a non-abstract class. In C++, this concept is known as pure virtual method.

Interface – its a kind of class, that has only methods, do not have code, just the definition of the methods. Also, the interface can’t be instantiated. Its an abstract class with public abstract methods, all of which must be implemented in the inherited classes. All methods in an interface are public, no other access modifier is used. It is public by default.

Classes can contain code, but interface dont. However, classes that implement an interface do contain code. Keep in mind that there are no instances of interfaces in VB .NET. Every instance is a type that implements an interface, but is itself not an instance of the interface. Also note, in an interface, all methods must be abstract (which is not necessary in an abstract class).

‘VB .NET Interface
Public Interface ISalary
Sub CreditSalary(ByVal Amount As Decimal)
ReadOnly Property Incentive() As Decimal
ReadOnly Property Attendance() As Integer
End Interface

To use members of an interface, we make use of the implements keyword.

Public Class Employee
Implements ISalary
Public Function Salary() As Decimal Implements ISalary.CreditSalary()
‘code here …
End Function
End Class

Serializable – This is a class attribute. When we use this attribute with a class, an instance of this class can be taken in whatever state it is, and write it to a disk. The class can then be deserialized, and the class will act as if it is simply stored in the memory.

Boxing & Unboxing – Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as Boxing. Converting reference type back to value type
is known as Unboxing.

Value Types – Value types are primitive types that are mapped directly to the FCL. Like Int32 maps to System.Int32, double maps to System.double.
All value types are stored on stack and all the value types are derived from System.ValueType. All structures and enumerated types that are derived from System.ValueType are created on stack, hence known as ValueType.

Reference Types – Reference Types are different from value types in such a way that memory is allocated to them from the heap. All the classes are of reference type. C# new operator returns the memory address of the

Partial Class – This concept has been introduced in .NET framework 2.0. They give you the ability to split a single class into more than one source code (.cs or .vb) file. Here’s what a partial class looks like when it’s split over two files…

// Stored in file MyClass1.cs
public partial class MyClass
public MethodA()

// Stored in file MyClass2.cs
public partial class MyClass
public MethodB()

When you build the application, Visual Studio .NET tracks down each piece of MyClass and assembles it into a complete, compiled class with two methods, MethodA() and MethodB().

Partial classes don’t offer much in the way of solving programming problems, but they can be useful if you have extremely large, unwieldy classes. (Of course, this might be a sign that you haven’t properly factored your problem, in which case you should really break your class down into separate classes.) The real purpose of partial classes in .NET is to hide automatically generated designer code.


Using SQL State for storing session in Wednesday, Dec 1 2010 

HTTP is called a stateless protocol because each command is executed independently, without any knowledge of the commands that came before it. This makes website development a quite difficult task. To make it resolve “State Management” comes into play and here I am going to give you the step by step procedure to deploy “SQL State session” in you application.

Just to get a quick reference before we get into the tutorial, I would like you to pay some attention to the session states modes,

1.    Off :  Which disable session state management

2.    InProc: This is the by default mode in the application. Stores session in the web server.

3.    Out of process: Also know as state server mode. In the memory of a machine dedicated to storing session variables

4.    SQL Server : Session stored in the SQL Server.

Now, let’s get back to the soul of this article and check out the steps you need to follow to implement SQL Server

Step 1: Go to Visual Studio command prompt:

Open VS command prompt

Step 2: Traverse to this path:


Command Prompt


Step 3: Now run this command

aspnet_regsql.exe -S servername-E -ssadd -sstype p


aspnet_regsql.exe -S SERVERNAME -U sa -P password -ssadd -sstype c -d yourdatabase

Times to demystify this command:



S IP address or the name of the Sql Server in which you want to store the session.
E Indicate that you want use integrated security at the time of making connection.
-ssad It will add support to the SQL server mode session state.
-sstype Type of support for session state, available options are


t Temporary storage
p Permanent storage
C Custom Storage



-u User Id while connecting to the SQL server.
-p Password while connecting to the SQL server.
-ssremove To remove support for the SQL server mode session state.
-d Name of the database when –sstype is on “c” [Custom storage].


Note: In our case we are using the integrated security so the so we are using this command

aspnet_regsql.exe -S servername-E -ssadd -sstype p

Step 4:

Now when you run the command, your database will be installed successfully, you can check the same by verify the tables installed





If everything is done properly, then come to your ASP.NET application and make the appropriate setting for the SQL server session state:

<sessionState mode=”SQLServer” allowCustomSqlDatabase=”true”

sqlConnectionString=”Data Source=MyDataSource;Initial Catalog=ASPState;Integrated Security=SSPI”





Step 6:

Now we have to see that it’s working correctly or not:

On Page_Load,

Session[“TestSession”] = “Some Data”;

On button click

string testVariable = Session[“TestSession”].ToString();


Run your application and check your database to verify that everything is working fine.


Verify Database

If you find difficulty at the any step, please feel free to contact me.

Hope to see your sessions in SQL Server. 🙂


Download free ebook of ASP.Net 4.0 Step By Step Thursday, Nov 11 2010 

To download free ebook of ASP.Net 4.0 step by step click here.

The Attributes of a Connection String in ASP.Net with C# Thursday, Nov 11 2010 

To use a SqlConnection object, you must provide various pieces of information joined into a string but are separated from each other with a semi-colon “;”. Each piece appears as a Key=Value:


It can be passed as follows:

SqlConnection connection = new SqlConnection("Key1=Value1;Key2=Value2;Key_n=Value_n");

or assigned as a string to the SqlConnection.ConnectionString property:

string strConnection = "Key1=Value1;Key2=Value2;Key_n=Value_n";
SqlConnection connection = new SqlConnection();

connection.ConnectionString = strConnection;

The Source of Data

To establish a connection, you must specify the computer you are connecting to, that has Microsoft SQL  Server installed. If you are creating your application on the same computer on which SQL Server is  installed, you can use (local). Here is an example:
SqlConnection connection = new SqlConnection("Server=(local); ");

If you know the name of the computer, you can assign it to the computer attribute. Here is an example:

SqlConnection connection = new SqlConnection("Server=central; ");

In the same way, if you are connecting to a specific computer, you must provide its name. Here is an


SqlConnection connection = new SqlConnection("Data Source=central; ")


An important aspect of establishing a connection to a computer is security. To support security, the

connection string of the SqlConnection class includes an attribute called Trusted_Connection orIntegrated

Security that can have a value of truefalseyesno, or SSPI with the SSPI having the same indication

as true.

If you are establishing a trusted or simple connection that doesn't need to be verified, you can assign

a value of true or SSPI.  Here is an example:

SqlConnection connection =
        new SqlConnection("Server=(local);Trusted_Connection=SSPI");

If you are programmatically establishing the connection, to apply authentication, you can assignfalse or

no to the security attribute you selected.

The Username

To specify the user name, after assigning false or no to the security attribute, you must use theUser ID

attribute and assign it a valid username. Here is an example:

string strConnection = "Server=(local);" +
                           "Integrated Security=no;" +
                           "User ID=wmessmann";
    SqlConnection connection = new SqlConnection(strConnection);

The Password

Besides the username, to create a secured connection, you must also provide a password. To specify the

password, you can user either the PASSWORD or the PWD. Here is an example:

string strConnection = "Server=(local);" +
                           "Integrated Security=no;" +
                           "User ID=wmessmann;PWD=$outh~@kotA";
    SqlConnection connection = new SqlConnection(strConnection);

The Database

To specify the database, the connection string includes an attribute named Database. TheDatabase keyword

can also be substituted for the Initial Catalog value. Here is an example:

SqlConnection connection = new SqlConnection(Server=(local);Database=;);

Another alternative is to assign an empty, single-quoted, string to this attribute. Here is an example:

void InitializeComponent()
    string strConnection = "Server=(local);Initial Catalog='exercise1';";
    SqlConnection connection = new SqlConnection(strConnection);

As mentioned above, the Database attribute is optional, especially if you are only connecting to the

computer and not to a specific database.

Additional Attributes

There are various other attributes used in the connection string. They include Network Library(also

called Net), Application NameWorkstation IDEncryptConnection TimeoutData SourcePacket Size,

AttachDBFilenameCurrent LanguagePersist Security Info.

After creating the connection string, when the application executes, the compiler would "scan" the string

to validate each key=value section. If it finds an unknown Key, an unknown value, or an invalid

combination of key=value, it would throw an ArgumentException exception and the connection cannot be


SQL Server Interview Questions and Answers ebook free download Wednesday, Nov 10 2010 

SQL Server Interview Questions and Answers ebook free download click here.

Calling Cross Domain Web Services in AJAX Wednesday, Oct 13 2010 

One of the current vogues in web applications is the creation of mashups. This involves the marrying of content and/or functionality from two different sources. Over the last few years, the opening up of formerly proprietary APIs from the likes of Google, Yahoo,, Flickr, YouTube and Amazon has allowed developers to implement in their own applications, with simple one line calls to the requisite APIs, features such as adding photos, maps, booklists, videos and playlists.

The APIs allow the developer to select content through a series of filters such as location, date, user id, or membership of a particular group. The APIs are almost always thinly disguised wrappers for a web service.

With a lot of modern applications now employing Ajax techniques (with indeed whole web sites such as dedicated to Ajax patterns, and dedicated to mashup applications which utilize a lot of Ajax techniques), it makes sense to call the web services from within your own JavaScript. However, there is one big hitch to this theory. The XMLHttpRequest object is prevented from calling web services from outside its own domain. This is sensible given that if you called a script in one place and it, in turn, called a script on another server, it could leave an applicationopen to all sorts of malicious scripts, hacks and exploits.

However in the case of web services, it isn’t so sensible. Web services are called with either SOAP or HTTP-GET/POST requests and return information in the same way. They are designed to be called from other domains, and in some ways it’s an inherent contradiction to prevent them being called this way. So, given that there are plenty of mashups out there, and plenty of applications developed calling cross-domain web services, what do developers do to get around this limitation?

There isn’t a single answer to this question, but in this article I’ll discuss the current most popular techniques and what several developers are proposing to do get around this problem more neatly.

The XMLHttpRequest object

At the heart of the problem lies the XMLHttpRequest object. This object is central to many Ajax applications, although not an essential feature. The XMLHttpRequest object was introduced to IE5 as an ActiveX control, although the original version was conceived in Outlook Web Access 2000. This was an Outlook web-mail service that allowed people to access functionality such as download email, check calendars, and update contacts on the go, by allowing the application to issue its own client-side HTTP requests. It was introduced as a native object to Mozilla for release 1.0 and ended up in Safari 1.2 and Opera 7.60.

The XMLHttpRequest object doesn’t allow calls to be made from code in one domain to a web service in another. The latest craze for mashups involves calling Web Services from APIs made publicly available by companies such as Google, Flickr, Yahoo, and YouTube. This means that a call will always have to be made cross-domain, otherwise you can’t use them. The best way to illustrate the problem is to build an example.

The currency converter example

In the example the application calls the freely available currency conversion services from There are two drop down lists containing the list of currencies. So for example, you can select US Dollar in the first and Great British Pound Sterling in the second and then click on a button, to get the current rate. When the button is click, JavaScript is used to call the web service. The result is returned to the XMLHttpRequest object and ultimately rendered in the page.

Our application must have at least two sections, the first is the HTML page and the second is the script that calls the service. Our default.htm page is as follows:

<%@ Page Language="C#" AutoEventWireup="true"
                        CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html xmlns="" >
    <title>Ajax Currency Convertor</title>
<script type="text/javascript" src="Ajax.js"></script>
Currency To Convert From:
<select id="FromBox">
<option value="USD" selected="true">USD - U.S. Dollar</option>
<option value="GBP">GBP - British Pound</option>
<option value="EUR">EUR - Euro</option>
<option value="JPY">JPY - Japanese Yen</option>
Currency To Convert To:
<select id="ToBox">
<option value="USD">USD - U.S. Dollar</option>
<option value="GBP" selected="true">GBP - British Pound</option>
<option value="EUR">EUR - Euro</option>
<option value="JPY">JPY - Japanese Yen</option>
<br /><br />
<input id="button1" type="button" value="Click to convert currency"
           onclick="initiateConversion()" />
<br /><br />
<table id="table1">


sasasfunction initiateConversion()
xmlhttprequest = createRequestObject();
var url = “
+ document.getElementById(“FromBox”).value
+ “&ToCurrency=”
+ document.getElementById(“ToBox”).value ;“GET”, url, true);
xmlhttprequest.onreadystatechange = getData;

function createRequestObject()
if (window.XMLHttpRequest)
return xmlhttprequest = new XMLHttpRequest();
else if (window.ActiveXObject)
return xmlhttprequest = new ActiveXObject(“Microsoft.XMLHTTP”);
function getData()
if ((xmlhttprequest.readyState == 4) &&( xmlhttprequest.status == 200))
var myXml = xmlhttprequest.responseXML;
var xmlobject = null;
var XMLText = null;
if (window.ActiveXObject)
XMLText = myXml.childNodes[1].firstChild.nodeValue;
XMLText = myXml.childNodes[0].firstChild.nodeValue;

var table = document.getElementById(“table1”);
var row = table.insertRow(table.rows.length);
var tablecell = row.insertCell(row.cells.length);
+ ” to ”
+ document.getElementById(“ToBox”).value));
var tablecell = row.insertCell(row.cells.length);
table.setAttribute(“border”, “2”);


<%@Page Language = “C#” Debug=”true” %>

<%@ import Namespace=”System.Xml” %>

<script language=”C#” runat=”server”>

void Page_Load()


XmlDocument wsResponse = new XmlDocument();

string url = “; + Request.QueryString[“FromBox”].ToString() + “&ToCurrency=” + Request.QueryString[“ToBox”].ToString();        wsResponse.Load(url);

string XMLDocument = wsResponse.InnerXml;

Response.ContentType = “text/xml”;




For complete reference:



Application and Session Objects in ASP.NET Wednesday, Oct 13 2010 

Application and Session Objects in ASP.NET

Sessions serve as a way to transport and maintain user data in web pages, such as forums, or e-commerce websites. In this article, We take a quick tour of both session and application objects, and gives us practical examples as to their uses.  


So what is a session?

session is the time for which a particular user interacts with a web application. During a session the unique identity of the user is maintained internally. A session ends if there is a session timeout or if you end the visitor session in code.

What’s the use of sessions?

Sessions helps to preserve data across successive accesses. These can be done on a per user basis, via the use of session objects. Session objects give us the power to preserve user preferences and other user information when browsing a web application. To better understand the use of sessions, consider an example: Suppose you own a website in which you give the visitors the option to choose the background color of the pages they will browse. In such a case you need to remember the user’s choice on each of the page. This task can be accomplished using sessions.

A more practical example is the case of an e-commerce website where the visitor browses through many pages and wants to keep track of the products ordered.

Application and Session Objects in ASP.NET – Our First Session

Sessions in ASP.NET are simply hash tables in the memory with a timeout specified. Consider the following examples

Session(“username”) = “Aayush Puri”

Session(“color”) = “Blue”


This assigns the values “Aayush Puri” and “Blue” to the session variables “username” and “color”, respectively. If I need to know the “username” or “color” in subsequent pages, I can use Session(“username”), Session(“color”).

Sessions in ASP.NET are identified using 32-bit long integers known as Session IDs. The ASP engine generates these session ID’s so that uniqueness is guaranteed.

Let’s now see how you can configure the session object depending on the requirements of your Web Application.

Session Type What it does Example
Session.Abandon Abandons (cancels) the current session.
Session.Remove Delete an item from the session-state collection. Session(“username”) = “Aayush Puri”
Initialize a session variable)

Deletes the session variable “username”)

Session.RemoveAll Deletes all session state items
Session.Timeout Set the timeout (in minutes) for a session Session.Timeout=30 (If a user does NOT request a page of the ASP.NET application within 30 minutes then the session expires.)
Session.SessionID Get the session ID (read only property of a session) for the current session.
Session.IsNewSession This is to check if the visitor’s session was created with the current request i.e. has the visitor just entered the site. The IsNewSession property is true within the first page of the ASP.NET application.

Application and Session Objects in ASP.NET – Application Objects

As we saw in the previous section, sessions help us preserve data on a per user basis. What if we want to initialize variables that are available in a session and that are the same for all users? This means that a change in the value of an application variable is reflected in the current sessions of all users. For example, we may like to fix variables like tax rate, discount rate, company name, etc., that will be specified once for all variables we can access in a session. This is whereapplication variables come in. Heck, they can even be used to show legal notices at the bottom of every page!

Creating an application variable is similar to session variables.

Application(“legal_notice”) = “No part of this article may be reproduced without prior permission”


There is a concern when changing the value of an application variable: at any particular instant, multiple sessions might be trying to change the value, although only one session can be allowed to change it. ASP.NET has an in built mutual exclusion for dealing with these types of problems.

  • Application.Lock – Locks the application variables
  • Application.Unlock – Unlocks the application variables

Once application variables are locked sessions that attempt to change them have to wait.

Application and Session Objects in ASP.NET – Practical Examples Showing the Use of Sessions

You might need to redirect the visitor to a particular page if some error has occurred. On the redirected page, you’ll need to display the error message. A session variable initialized to an error message fits the bill. Here’s an example: Suppose you are writing a function check_string() (as a part of page named page1.aspx) which accepts no other string than “ASP.NET Rocks!” If the string passed as an argument does not match, then you need to redirect to a page (“page2.aspx”) and display the error.

Public Sub check_string(ByVal str As String)
If Not Str.equals("ASP.NET Rocks") Then
Session("error_message") = "The string was NOT ""ASP.NET Rocks"" "
End If
End Sub


Page2.aspx This next fucntion will display the error message.

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Session("message") <> "" Then
Session.Remove("message") 'Make the session variable null
End If
End Sub


I include this piece of code in the function “Page_load” to check for any error message on every visit to this page.

Here’s a personal example of having to use sessions: I had to design a website which had three types of users, all requiring authorization. All users were divided into three categories, and each category had a well defined set of rules and permissions.

While writing server-side scripts, I had to ensure that a particular script run only for qualified users. The information in thedatabase showed which user belonged to which category. Querying the database was too cumbersome, so a simple and elegant solution was to use session variables.

At the time of authorization I queried the category of the user and stored the result in a session variable.

At the time of authorization also fetch the category type
Session(“category”) = Get_category(username)


And that’s it–small, quick, and to the point. Would that all were as simple as sessions… but that’s neither here nor there. Enjoy!

Next Page »