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
(Polymorphism).

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
objStud.RollNo=31
objStud.Name=”Monu”

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()
Get
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”
c.MyProc(12)

‘ prints out “Character in DerivedClass is B”
c.MyProc(Chr(66))

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…
objsampleobject.Finalize

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)
MyBase.New(SomeString)
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
object.

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.

Source: http://sites.google.com/site/moredotnet/oops

Random Image shuffle Javascript code Thursday, Apr 21 2011 

I tested the script and it’s perfect, only thing is I need the random images to load within a set table/cell. The ” onload=”ShufImages();” function needs to be confined within a set table/cell.

I’ve tried placing the function in the header but it errors.

Any help would be greatly appreciated.

Thanks in advanced.

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
http://www.w3.org/TR/html4/strict.dtd”&gt;
<html>
<head>
<title></title>
<script language=”JavaScript” type=”text/javascript”>
<!–
var ImgPath=’/StdImages/’;
var ImgAry=new Array(‘One.gif’,’Two.gif’,’Three.gif’,’Four.gif’,’Five.gif’);
var RandomNu;
var ImgCnt=1;
function ShufImages(){
while (ImgCnt<ImgAry.length){
RandomNu=Math.floor(Math.random()*(ImgAry.length-1));
if (ImgAry[RandomNu]!=’X’){
document.getElementById(‘I’+ImgCnt).src=ImgPath+ImgAry[RandomNu];
ImgAry[RandomNu]=’X’;
ImgCnt++;
}
}
}
//–>
</script>
</head>
<body onload=”ShufImages();” >
<table width=”400″ border=”1″ >
<tr>
<td>
<img id=”I1″ src=”/StdImages/Blank.gif” width=”100″ height=”100″>
</td>
<td>
<img id=”I2″ src=”/StdImages/Blank.gif” width=”100″ height=”100″>
</td>
<td>
<img id=”I3″ src=”/StdImages/Blank.gif” width=”100″ height=”100″>
</td>
<td>
<img id=”I4″ src=”/StdImages/Blank.gif” width=”100″ height=”100″>
</td>
</body>
</html>

Very simple example of Javascript sleep method Tuesday, Apr 12 2011 

Have you ever needed the sleep command in JavaScript? Usually you can use the existing setTimeout(), clearTimeout() and setInterval() to accomplish what you want and in those cases you should use the native functions. But if you really need the sleep or wait statement lets go through the options and see what code might work the best.

JavaScript sleep by loop

<script type="text/javascript">
// bad implementation
function sleep(milliSeconds){
	var startTime = new Date().getTime(); // get the current time
	while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}
</script>
We are using a while loop on line 3 that continually
 evaluates the current time against the time when
 we should stop blocking. This loop will run as fast
 as the browser will let it all the while using up 
valuable cpu resources. Checking the time might not 
seem like much but doing it thousands (or tens of thousands) 
of times per second make a noticeable performance impact 
on your computer (try it and watch your cpu meter). 
This code will "pause" your thread but will also use
 all the resources your computer will give it.
Resource taken from:
http://www.devcheater.com/

 

Reflection Examples [C#] Sunday, Feb 6 2011 

This example shows how to dynamically load assembly, how to create object instance, how to invoke method or how to get and set property value.

Create instance from assembly that is in your project References

The following examples create instances of DateTime class from the System assembly.

// create instance of class DateTime

DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime));

// create instance of DateTime, use constructor with parameters (year, month, day)

DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime),

new object[] { 2008, 7, 4 });

Create instance from dynamically loaded assembly

All the following examples try to access to sample class Calculator from Test.dll assembly. The calculator class can be defined like this.

namespace Test

{

public class Calculator

{

public Calculator() { … }

private double _number;

public double Number { get { … } set { … } }

public void Clear() { … }

private void DoClear() { … }

public double Add(double number) { … }

public static double Pi { … }

public static double GetPi() { … }

}

}

Examples of using reflection to load the Test.dll assembly, to create instance of the Calculator class and to access its members (public/private, instance/static).

[C#]

// dynamically load assembly from file Test.dll
Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");

[C#]

// get type of class Calculator from just loaded assembly
Type calcType = testAssembly.GetType("Test.Calculator");

[C#]

// create instance of class Calculator
object calcInstance = Activator.CreateInstance(calcType);

[C#]

// get info about property: public double Number
PropertyInfo numberPropertyInfo = calcType.GetProperty("Number");

[C#]

// get value of property: public double Number
double value = (double)numberPropertyInfo.GetValue(calcInstance, null);

[C#]

// set value of property: public double Number
numberPropertyInfo.SetValue(calcInstance, 10.0, null);

[C#]

// get info about static property: public static double Pi
PropertyInfo piPropertyInfo = calcType.GetProperty("Pi");

[C#]

// get value of static property: public static double Pi
double piValue = (double)piPropertyInfo.GetValue(null, null);

[C#]

// invoke public instance method: public void Clear()
calcType.InvokeMember("Clear",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
    null, calcInstance, null);

[C#]

// invoke private instance method: private void DoClear()
calcType.InvokeMember("DoClear",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
    null, calcInstance, null);

[C#]

// invoke public instance method: public double Add(double number)
double value = (double)calcType.InvokeMember("Add",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
    null, calcInstance, new object[] { 20.0 });

[C#]

// invoke public static method: public static double GetPi()
double piValue = (double)calcType.InvokeMember("GetPi",
    BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public,
    null, null, null);

[C#]

// get value of private field: private double _number
double value = (double)calcType.InvokeMember("_number",
    BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic,
    null, calcInstance, null);

 

ASP.NET MVC and JSON Tuesday, Dec 21 2010 

In the AJAX community, JSON have become the preferred way of sending and receiving data. That’s not surprising since it’s lightweight, fast and easy to understand. Also, since it’s a subset of Javascript, it’s familiar territory for Javascript coders.

In the ASP.NET MVC Framework, passing JSON from the server to the client script is almost too easy. In this article I will walk you through the code required to make it work.

The back end

Suppose we have a class named Cars like the one below. We want to feed our web page with a list of cars that we want to display AJAX style, preferably by sending the list as a JSON object.

public class Car {

public string Name { get; set; }
public string Color { get; set; }
}

With the ASP.NET MVC Framework it’s a breeze. In your Controller you simply create a method of the type JsonResult which returns a JSON object. You then use the Json() method to transform the class to JSON.
public class CarsController : Controller

{
public JsonResult GetCars()
{
List<Car> cars = Cars.GetCars();
return this.Json(cars);
}
}

Calling this method will return JSON that looks something like this:

[{“Name”:”Saab”,”Color”:”Red”},{“Name”:”Volvo”,”Color”:”Blue”}]

Making the AJAX call

To get the list of cars on the client side, you want to make an AJAX call to the Controller method GetCars(). This is done by calling the URL /Cars/GetCars/.

First I’ll walk you through how to do it with pure Javascript. Then I’ll show you how to do it with the jQuery library.
The Classic Javascript way

First of all you have to create an instance of the XMLHttpRequest object. It’s through this object that you communicate with the back end. Since IE 6 doesn’t support this object but do have support for an ActiveX object that essentially does the same thing, we initially have to do some checking to make sure that we use the correct object. I’ve created a wrapper function that with the help of object detection determines which object to use and then returns it.function getRequestObject() {

var req = false;
if(window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if(window.ActiveXObject) {
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}
return req;
}

I use the getRequestObject function to get the correct Request Object and then gets on with setting up the request.

var request = getRequestObject();

request.onreadystatechange = handleResponse;
request.open(‘GET’, ‘/Cars/GetCars’, true);
request.send(null);

Note: If you’re unfamiliar with AJAX and find this code really strange, I recommend that you read getting started with AJAX from Mozilla Developer Center.

Ok, so the AJAX Call is all set up. The last thing to do is to create the function handleResponse that takes care of the request and the received data.

function handleResponse() {

if (request.readyState == 4) {
var cars = eval(‘(‘ + request.responseText + ‘)’);

for each(car in cars) {
alert(car.Name + ‘, ‘ + car.Color);
}
}
}

The object is received as JSON text through the responseText property of the request object. To convert it to a JSON object you can use the Eval() function. It will parse the text and produce an object structure. This is a fast and convenient way of doing it, but be aware of that it has potential security issues. Only use it if you know that you can trust the source. Otherwise you should use a more robust JSON parser.

The code in this example will throw an alert for each item in the JSON object and display it’s properties. This is done by looping through the received object. Notice how we can access the properties of the object through convenient dot notation.
The jQuery way

The client side scripting is even easier using jQuery. All the Javascript code above can be replaced with this.

$.getJSON(“/Cars/GetCars”, null, function(data) {

$.each(data, function(index, car) {
alert(car.Name, car.Color)
});
});

jQuery handles everything that happens in the background, like instantiating the request object and parsing the received JSON object. So it does all the heavy lifting and leaves the fun stuff to you, like doing creative things with the received data.

 

Reference: http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=399

 

Traversing inside a div/table content using Javascript Monday, Dec 13 2010 

Here is the code to get element inside a div/table and number of div/table or table inside a div/table.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<head>
<title></title>
<script type=”text/javascript”>
function foo(divId1) {
var divId = document.getElementById(“div1”);
var divs = divId.getElementsByTagName(“div”);
alert(“number of div inside div1” + divs.length);
for (var i = 0; i < divs.length; i++) {
divs[i].style.display = “none”;
}
document.getElementById(divId1).style.display = “block”;
}
</script>
</head>
<body>
<div id=”div1″>
<div id=”id1″>Here is Div 1 data.</div>
<div id=”id2″>Here is Div 2 data.</div>
</div>
<input type=”button” value=”Click Me1″ onclick=”foo(‘id1’)” />
<input type=”button” value=”Click Me2″ onclick=”foo(‘id2’)” />
</body>
</html>

Removing Duplicates from a List in C# Friday, Dec 3 2010 

When you are dealing with a list of data, you may be interested in filtering out all duplicate values. For example, let’s say your input resembles the following:

input = { there, here, deer, dear, there, pier, deer, leer }

Your output with duplicates removed would be:

input = { there, here, near, deer, dear, pier leer }

The duplicate there‘s and deer‘s were removed. In this tutorial, I will provide the code for removing duplicates and then explain how the code actually works to efficiently remove duplicate elements.

The Code
The code for removing duplicate values is:

static List<string> removeDuplicates(List<string> inputList)
{
Dictionary<string, int> uniqueStore = new Dictionary<string, int>();
List<string> finalList = new List<string>();
foreach (string currValue in inputList)
{
if (!uniqueStore.ContainsKey(currValue))
{
uniqueStore.Add(currValue, 0);
finalList.Add(currValue);
}
}
return finalList;
}

Note that the above code is designed for Lists that store string data, but you can modify the code easily to accept any type of data! Don’t worry – I will explain later.

How to Use the Code
To test the above code, all you need is a List that contains duplicate values. You can copy and paste the following main method to see for yourself:

static void Main(string[] args)
{
List<string> input = new List<string>();
input.Add(“There”);
input.Add(“Here”);
input.Add(“Sneer”);
input.Add(“There”);
input.Add(“Near”);
input.Add(“Meer”);
input.Add(“Here”);
List<string> result = removeDuplicates(input);
}

Reference: http://www.kirupa.com/net/removingDuplicates.htm

Using SQL State for storing session in asp.net 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 asp.net 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 asp.net 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:

…….\Microsoft.NET\Framework\v2.0.50727

Command Prompt

 

Step 3: Now run this command

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

or

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

Times to demystify this command:

Here,

 

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

ASPStateTempApplications

ASPStateTempSessions

 

Step5:

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”

cookieless=”false”

timeout=”10″>

sessionState>

 

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. 🙂

Reference: http://www.anujtripathi.net/BlogListing.aspx?Id=5

C Sharp 2010 Ebook (pdf) Free download Thursday, Nov 11 2010 

C Sharp 2010 Ebook Free download click here

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.

« Previous PageNext Page »