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