Sunday, January 9, 2011

Converting a generic list into JSON string and then handling it in java script

We all know that JSON (JavaScript Object Notation) is very useful in case of manipulating string on client side with java script and its performance is very good over browsers so let’s create a simple example where convert a Generic List then we will convert this list into JSON string and then we will call this web service from java script and will handle in java script.

To do this we need a info class(Type) and for that class we are going to create generic list. Here is code for that I have created simple class with two properties UserId and UserName

public class UserInfo
{
public int UserId { get; set; }
public string UserName { get; set; }
}
Now Let’s create a web service and web method will create a class and then we will convert this with in JSON string with JavaScriptSerializer class. Here is web service class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace Experiment.WebService
{
/// <summary>
/// Summary description for WsApplicationUser
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WsApplicationUser : System.Web.Services.WebService
{

[WebMethod]
public string GetUserList()
{
List<UserInfo> userList = new List<UserInfo>();
for (int i = 1; i <= 5; i++)
{
UserInfo userInfo = new UserInfo();
userInfo.UserId = i;
userInfo.UserName = string.Format("{0}{1}", "J", i.ToString());
userList.Add(userInfo);

}
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return jSearializer.Serialize(userList);
}
}
}

Note: Here you must have this attribute here in web service class ‘[System.Web.Script.Services.ScriptService]’ as this attribute will enable web service to call from client side.Now we have created a web service class let’s create a java script function ‘GetUserList’ which will call web service from JavaScript like following
function GetUserList() {
Experiment.WebService.WsApplicationUser.GetUserList(ReuqestCompleteCallback, RequestFailedCallback);

}
After as you can see we have inserted two call back function ReuqestCompleteCallback and RequestFailedCallback which handle errors and result from web service. ReuqestCompleteCallback will handle result of web service and if and error comes then RequestFailedCallback will print the error. Following is code for both function.
function ReuqestCompleteCallback(result) {

result = eval(result);
var divResult = document.getElementById("divUserList");
CreateUserListTable(result);

}
function RequestFailedCallback(error) {

var stackTrace = error.get_stackTrace();
var message = error.get_message();
var statusCode = error.get_statusCode();
var exceptionType = error.get_exceptionType();
var timedout = error.get_timedOut();

// Display the error.
var divResult = document.getElementById("divUserList");
divResult.innerHTML = "Stack Trace: " + stackTrace + "<br/>" +
"Service Error: " + message + "<br/>" +
"Status Code: " + statusCode + "<br/>" +
"Exception Type: " + exceptionType + "<br/>" +
"Timedout: " + timedout;
}

Here in above there is a function called you can see that we have use ‘eval’ function which parse string in enumerable form. Then we are calling a function call ‘CreateUserListTable’ which will create a table string and paste string in the a div. Here is code for that function.
function CreateUserListTable(userList) {

var tablestring = '<table ><tr><td>UsreID</td><td>UserName</td></tr>';

for (var i = 0, len = userList.length; i < len; ++i)
{
tablestring=tablestring + "<tr>";
tablestring=tablestring + "<td>" + userList[i].UserId + "</td>";
tablestring=tablestring + "<td>" + userList[i].UserName + "</td>";
tablestring=tablestring + "</tr>";
}
tablestring = tablestring + "</table>";
var divResult = document.getElementById("divUserList");
divResult.innerHTML = tablestring;
}
Now let’s create div which will have all html that is generated from this function. Here is code of my web page. We also need to add a script reference to enable web service from client side. Here is all HTML code we have.
<form id="form1" runat="server">
<asp:ScriptManager ID="myScirptManger" runat="Server">
<Services>
<asp:ServiceReference Path="~/WebService/WsApplicationUser.asmx" />
</Services>
</asp:ScriptManager>

<div id="divUserList">
</div>
</form>
Now as we have not defined where we are going to call ‘GetUserList’ function so let’s call this function on windows onload event of javascript like following.
window.onload=GetUserList();
That’s it. Now let’s run it on browser to see whether it’s work or not and here is the output in browser as expected.

JSON string output in browser

That’s it. This was very basic example but you can crate your own JavaScript enabled grid from this and you can see possibilities are unlimited here. Stay tuned for more.. Happy programming..
Shout it
Share:

Distinct operator in Linq

Linq operator provides great flexibility and easy way of coding. Let’s again take one more example of distinct operator. As name suggest it will find the distinct elements from IEnumerable. Let’s take an example of array in console application and then we will again print array to see is it working or not. Below is the code for that. In this application I have integer array which contains duplicate elements and then I will apply distinct operator to this and then I will print again result of distinct operators to actually see whether its working or not.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Experiment
{
class Program
{
static void Main(string[] args)
{
int[] intArray = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 };
var uniqueIntegers = intArray.Distinct();
foreach (var uInteger in uniqueIntegers)
{
Console.WriteLine(uInteger);
}
Console.ReadKey();

}
}
}
Below is output as expected..
DisntictResult

That’s cool..Stay tuned for more.. Happy programming.
Technorati Tags: ,
Shout it
Share:
Saturday, January 8, 2011

ASP.NET 4.0- Html Encoded Expressions

We all know <%=expression%> features in asp.net. We can print any string on page from there. Mostly we are using them in asp.net mvc. Now we have one new features with asp.net 4.0 that we have HTML Encoded Expressions and this prevent Cross scripting attack as we are html encoding them.

ASP.NET 4.0 introduces a new expression syntax <%: expression %> which automatically convert string into html encoded. Let’s take an example for that.

I have just created an hello word protected method which will return a simple string which contains characters that needed to be HTML Encoded. Below is code for that.

protected static string HelloWorld()
{
return "Hello World!!! returns from function()!!!>>>>>>>>>>>>>>>>>";
}
Now let’s use the that hello world in our page html like below. I am going to use both expression to give you exact difference.
<form id="form1" runat="server">
<div>
<strong><%: HelloWorld()%></strong>
</div>
<div>
<strong><%= HelloWorld()%></strong>
</div>
</form>

Now let’s run the application and you can see in browser both look similar.

HtmlEncodedExpression

But when look into page source html in browser like below you can clearly see one is HTML Encoded and another one is not.

HtmlEncodeView with html encoding

That’s it.. It’s cool.. Stay tuned for more.. Happy Programming
Technorati Tags: ,,
Shout it
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews