• Home
  • Privacy Policy
  • Terms & Conditions
  • Contact
  • Advertise
Videos, Photos, Wallpapers, Free Download, Movies, Songs, Sports , Live TV, Entertainment
 
  • Home
  • Bollywood
  • Hollywood
  • Box Office
  • Beauty
  • Fashion
  • Celebrity
  • Business
    • Social Media
    • Money Online
    • Category
  • Entertainment
    • Bollywood
  • Video
    • Youtube
    • Video
  • Technology
    • Asp.net
    • C#
    • SQL
    • .Net
Showing posts with label JSON. Show all posts
As discussed in the earlier section, the emphasis in Ajax-based applications is more on data than on content being sent across the web browser. Therefore, we shall discuss more on the available data interchange formats. Based on the need of the application, different data interchange formats can be used.

The following are some examples of these different formats:
  • HTML content
  • Plain text or string format
  • XML (Extensible Markup Language)
  • JSON (JavaScript Object Notation)
HTML Content:

One of the more common data interchange formats is the normal HTML content being transferred from server to client. When the server sends the HTML content as a response to a request, this content can be accessed by JavaScript and can be placed in any element using the innerHTML property or related methods. In our example of the Items list, the HTML content that would be sent to the browser is as follows:

<div><span>Computer .Net Course</span><span>Advance</span>
<span>2007</span><span>$ 896.00</span></div>
<div><span>Computer C# Course</span><span>Premier</span>
<span>2006</span><span>$ 655.00</span></div>
<div><span> Computer ASP.Net Course </span><span>Regular</span>
<span>2007</span><span>$ 720.00</span></div>

This content can be taken as is and inserted as HTML content in any of the elements that have the innerHTML property. Therefore, it is simple to bind, but formatting the HTML received from the server would be a big disadvantage.

The Most Common Plain Text or String Format :

Plain text or string format is a simple data interchange format as it does not involve any complexity. The server just returns plain text, and this can be bound to any element in the HTML using properties like value, text, and innerText based on the element chosen for display. We can also go for delimited string values as the response format for related data, although this has some disadvantages. Some of the ASP.NET Ajax server controls we examine later in the book emit delimited string values in their response format. One such control is an UpdatePanel control, which emits the response in the following format:
Size|ControlType|ControlName|ControlData The preceding string is delimited by “|” (the pipe symbol). Here, Size is in number of bytes, ControlType is the type of control (in this case, it is UpdatePanel), and ControlName is the name assigned to the control. The last delimited value is ControlData, which holds HTML content to be displayed on the browser. The advantage of using this format is the simplicity in coding, but the disadvantage is that if the position of the values is changed, it requires changes in the client code.

XML (Extensible Markup Language) :

XML is a markup language that was designed to describe data. XML stands for EXtensible Markup Language and is a W3C recommendation. XML today is a common standard for exchanging and manipulating data. It is one of the most commonly used data interchange formats in today’s web- and windows-based applications, because of its wide acceptance among several software vendors.
The exchange of data in XML is more so between the web server and client browser, as most browsers today implement XML DOM specifications, making it easier for the JavaScript to handle XML. XML does not have any predefined tags, and you must define your own tags to describe data. It uses a Document Type Definition (DTD) or an XML Schema to describe the data. In other words, a DTD or an XML Schema performs a grammar check to ensure its validity. This has gained popularity because of the simplicity in its data representation and its support for hierarchical data. Also, XML is free and extensible.
The following is an example of XML data representation:

<?xml version=”1.0” encoding=”utf-8” ?>
<ItemList>
<Item>
<Name>Computer .Net Course</Name>
<Type>Advance</Type>
<Year>2007</Year>
<Fee>$ 896.00</Fee>
</Item>
<Item>
<Name>Computer C# Course</Name>
<Type>Premier</Type>
<Year>2006</Year>
<Fee>$ 655.00</Fee>

</Item>
<Item>
<Name>Computer ASP.Net Course</Name>
<Type>Regular</Type>
<Year>2007</Year>
<Fee>$ 720.00</Fee>
</Item>
</ItemList>

The preceding XML data represents Items and its attributes, such as Name, Type, Year, and Fee. It is a simple structure that is self-explanatory.

The XML data retrieved from the server can be displayed on the browser in a couple of ways, as follows:

Use of XML DOM specification—This API can be used to parse the XML, access it, and transform into HTML content using JavaScript. To know more about the specifications of XML DOM API, go to www.w3.org.

Use of XSLT to transform the document into HTML—XSLT is a declarative, XML-based transformation language used to convert an XML document from one form to other. The XSLT processor uses an XSLT style sheet for converting XML document to HTML, plain text, or any other format supported by the processor.

JSON (JavaScript Object Notation) :

XML has become the defacto standard for data transmission. In Ajax-based applications, XML can be accessed by the XMLHttpRequest object in XML format using the responseXML property or in string format using the responseText property.
However, choosing XML as a data exchange format has its downsides, too. It is not suited especially when heavy data has to be exchanged between the server and client. Why? First, it becomes difficult to parse huge XML and access data; second, the XML data format is higher in bytes in what could have been accomplished in a smaller form.
XML has become the defacto standard for data transmission. In Ajax-based applications, XML can be accessed by the XMLHttpRequest object in XML format using the responseXML property or in string format using the responseText property.
However, choosing XML as a data exchange format has its downsides, too. It is not suited especially when heavy data has to be exchanged between the server and client. Why? First, it becomes difficult to parse huge XML and access data; second, the XML data format is higher in bytes in what could have been accomplished in a smaller form.

Douglas Crockford has created an alternate format, which is extremely lightweight and string-based for data exchange between server and client. Called JSON, it is an acronym for JavaScript Object Notation—a light-weight data interchange format.

JSON supports two data structures: objects and arrays. Objects are unordered collections of name/value pairs. This object is enclosed in { and }. Name and value are separated by :, and the name/value pairs are separated by ,. Arrays are an ordered sequence of values. An array is enclosed in [ and ], and its values are separated by ,.

The name is a string enclosed in double quotes. Values can be any one of the following data types: String, Number, Boolean [true or false], Object, Array, and null.

JSON is flexible in the sense that it can represent any data structure as is, and it provides the flexibility to add any new field to an existing structure without making the existing programs obsolete. The big advantage of JSON is that it’s more compact and a lot easier to parse than XML. All we need to do is to pass the JSON string to the eval of JavaScript. The eval function of JavaScript evaluates the input string and assigns the output to the HTML elements. It should be noted, however, that usage of the eval function hampers performance. You might have to think of a different option, but only when the data is huge—converting huge strings on the client side might cause delays to the end user. But the best part of JSON is that you can have this parsing in a .js file and can include it in any page. Also, JSON has no version number because the specification is declared stable forever. There are several JSON parsers that support most of the programming languages; these parsers can be downloaded from www.json.org/.

Most of the ASP.NET Ajax server controls use JSON as a data interchange format. The server controls emit JSON strings, and the Microsoft Ajax Client Library parses this data using the internal .js files and hands the data to the client. This format is preferred because of its size, compactness, and ease of parsing the data. Overall, it helps improve the performance of the ASP.NET Ajax application.
JSON Web Services really are the jumping off point between server-centric and client-centric web development. You can add all of the pretty, JavaScript-y, AJAX-y sugar you want to your UI, but if your page or control posts back, (weather or not it is asynchronously via an Update Panel) then it is still server-centric in terms of logic.

But by off-loading your logic to JSON Web Services, you are making your pages themselves each act like a nice client-centric MVC application. The HTML is obviously the view, the web services act as the model, since they will be processing business objects for persistence or returning them to the UI for consumption. Finally, a JavaScript file sits in between, acting as a controller.



Model - Web Service

using System;
using System.Web.Services;
using System.Web.Script.Services;

namespace MyWebApplication
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class JSONTestService : WebService
{
[WebMethod]
public void SetNewTest(Guid id, string text)
{
this.Application.Add(id.ToString(), text);
}
[WebMethod]
public string GetNewTest(Guid id)
{
return this.Application[id.ToString()].ToString();
}
[WebMethod]
public Guid CreateNew()
{
return Guid.NewGuid();
}
}
}

But normally, these web services will be processing full business objects. What I do is actually keep a variable on the client that stores my object, manipulate its properties via client-side events, (both of which are in the JavaScript file), and then pass the whole object to a web service for server-side manipulation.


View - Page / Control

<script type="text/javascript" language="javascript">
var txtGetNewTestID = '<% =this.txtGetNewTest.ClientID %>';
var txtSetNewTestID = '<% =this.txtSetNewTest.ClientID %>';
</script>

<table>
<tr>
<td>

</td>
<td>
<asp:Button id="btnNew" runat="server" Text="New" OnClientClick="GetNew(); return false;" />
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtSetNewTest" runat="server" />
</td>
<td>
<asp:Button ID="btnSetNewTest" runat="server" Text="Set" OnClientClick="SetNewTest(); return false;" />
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtGetNewTest" runat="server" />
</td>
<td>
<asp:Button ID="btnGet" runat="server" Text="Get" OnClientClick="GetNewTest(); return false;" />
</td>
</tr>
</table>

The only embedded JavaScript here is for variable declarations. Loose JavaScript files can't use the <% ... %> construct to call into .NET code, since they are not in the context of a page or control. So I like to expose the controls I'll need to manipulate this way, and then use $get(<control unique id>) in my JavaScript file to get a reference to the control.

You can still use server controls, and take advantage of the extensions they add to HTML controls. However, we don't want to cause a post back, as that will kill the state of our client objects. So for controls that always do an AutoPostBack, (like buttons) add "return false;" to end of the "client" event; this will not call __doPostback() behind the scenes.

Controller - JavaScript file

var _guid = null;

function GetNew()
{
MyWebApplication.JSONTestService.CreateNew(GetNewDone, OnError, null);
}

function GetNewDone(result)
{
_guid = result;
}

function SetNewTest()
{
MyWebApplication.JSONTestService.SetNewTest(_guid, $get(txtSetNewTestID).value, null, OnError, null);
}

function GetNewTest()
{
MyWebApplication.JSONTestService.GetNewTest(_guid, GetNewTestDone, OnError, null);
}

function GetNewTestDone(result)
{
$get(txtGetNewTestID).value = result;
}

function OnError(ex)
{
alert('Error: ' + ex._message);
}

If any of the server code in a web method on your web service throws an exception, the OnError JavaScript function here will be called. The variable passed is a JSON serialized Exception object, providing the description of the error, as well as a full stack trace! This way, you can still catch-and-log-and-rethrow your exceptions on the server, and gracefully deal with them on the client.

Another benefit to using a loose JavaScript file as the controller is that it provides a rich debugging experience. I wrote more about that here.

I know that using a JavaScript file as a controller in the MVC architecture is a stretch, but it works. Since you can swap .js files on the fly, they are kind of a configurable broker; as long as they handle events on the client and can, in response, call services on the server, the paradigm fits. This way, you can completely replace your back end, and then merely tweak your JavaScript file to keep communication between your persistence and your UI flowing.

The only thing left to do is wire everything up in the code-behind of the page / control:

using System;
using System.Web.UI;

namespace MyWebApplication
{
public partial class JSONTest : UserControl //or Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
ScriptManager sm = ScriptManager.GetCurrent(this.Page);
sm.Scripts.Add(new ScriptReference("/JSONTest.js"));
sm.Services.Add(new ServiceReference("/JSONTestService.asmx"));
}
}
}
}

In fact, since I've adopted this architecture, the only code-behind my pages and controls have is in the Load event, if IsPostBack is false. This separation of logic from presentation makes for a much cleaner ASPX / ASCX file, both in terms of managed code behind and HTML!

Despite the fact that the implementation of the "model" web services is still .NET code, they are called asynchronously though the AJAX web service infrastructure, not via a form submit, and therefore do not cause the Load event of your page to fire. This really does away with the page lifecycle as we know it. This way, we can move all of the business logic from the page to JavaScript, and then use JSON Web Services to either do persistence and call other services, or do any processing that is too complex for, or not supported by, JavaScript (for example, guids).

Speaking of the implementation of these web methods, there is more thing to point out. In the first post I linked to in this article, I talk about one main "reality check" of JSON Web Services: they do not share the same Session as the UI. So my workaround for this is to use the Application object, and store objects in it keyed off of guids.

This way, although all of instances of our app are using the same Application object, there will be no name collisions. And as far as the server is concerned, and object in memory is an object in memory; there shouldn't be any performance ramifications using this method verses using Session state.
Older Posts Home

ASP.NET Examples

 
2012 24x7 Magazine. All rights reserved.
Designed by 24x7 Magazine