Click here to Skip to main content
Click here to Skip to main content

Generic Data Exchange Framework with AJAX

, 15 Mar 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
A generic data exchange framework with AJAX.

Introduction

Does internet programming have to be awkward and user unfriendly? Yes, it does, and will continue to be that way until the internet programming model changes from HTTP/HTML to another one. I already hear very angry criticism saying that this model is being successfully used by thousands of programmers all over the world. Yes, that is true. However, have you ever asked yourself questions like: Is it not strange that after more than 10 years of internet existence, there is not a decent HTML editor? Development of an HTML page is always tweaking with HTML tags. Were these editors developed by incompetent beginners? No, they were designed by very skillful people, but the HTML language is not up to the task. And that is not all. The data exchange between the server and the client is ultimately primitive. There are no common objects. Even with ASP.NET, the situation has not improved much. Unfortunately, the model can not be changed instantly. We have to live with it for a few more years, and this article is about how some internet data exchange problems can be solved.

Unification of client and server programming

Would it be nice to program the client the same way as the server is? In objects, not in HTML and DOM terms? What is the main problem in the development of rich web clients? The problem is that rich applications (Windows Forms or Web Forms based) always rely on rich objects. Rich means well structured hierarchal classes and the means to manipulate these structures. Unfortunately, nothing exists on the client side to facilitate this task. We have the JavaScript language - a pretty adequate language that syntactically allows for manipulating structured data, but there is no mechanism to deliver these structures from the server to the client and back from the client to the server. At best, we can use an XML parser. But, do we have to?

The framework presented here solves these problems. All the objects originate on the server. We create the objects (classes) of virtually any complexity on the server, initialize them, register them with the framework (RWCDF), and then the framework will generate already initialized objects for the client. After the data manipulation on the client side is complete, the objects get sent back to the server using the traditional Postback or [and ] AJAX. You can also invoke the methods directly on the server using AJAX calls, passing the objects (the classes) as parameters. For efficient data manipulation, we need collections as well. Without dynamic structures like ArrayList and Hashtable, the implementation of any serious data manipulation engine is very time consuming. JavaScript ArrayList and Hashtable have been implemented and included in the framework. In other words, the framework unifies server and client data manipulation. With this framework, programming of the web client is almost identical to programming of the server. But be aware that this is not a panacea. The performance of JavaScript is the main showstopper. Apart from that, JavaScript also has very loosely defined data types.

Framework programming

The first logical step is to create the data structures that will serve our needs.

public class EmployeeAddress
{                            
    public string City;                            
    public string Country;
    public string Street;                        
    public string Phone;    
    public ArrayList PhotoAlbum = new ArrayList();            
}
                            
public class Employee
{                            
    public long somelong = 8598065;            
    public double Salary = 787878.344;
    public float Scale = 8.66F;
    public string Name;                    
    public string  SName;                            
    public string Title;                            
    public string Position;
    public int Age;
    public DateTime Date;                            
    public string PictureUrl;
    public EmployeeAddress Address;
    public bool Married = true;
    public ArrayList SomeDataCollection;
    
    public  Employee                            
    {
        Address = new EmployeeAddress();
    }                            
}

Note that the instance of the EmployeeAddress class is the member of the Employee class. Actually, the depth of the nested classes is not limited. We create the instances of Employee(s) and initialize them.

ArrayList MyEmployees = new ArrayList();
Employee emp = new Employee()
emp1.Name = "Bob"; 
emp1.SName = "Smith"; 
emp1.Title = "Mr";
emp1.Position = "waiter";  
emp1.Date = new DateTime(2003, 2, 6);
emp1.Address.City = "London";
emp1.Address.Phone = "(043)8984 63535"; 
emp1.Age = 33;
emp1.PictureUrl = "BobSmith.jpg";

//add employee to ArrayList
MyEmployees.Add(emp); 
//....then create more employees and also add them to ArrayList
MyEmployees.Add(emp1);

After that, we only need to register the object(s) which we want to use on the client - in our case, it is the ArrayList of Employee objects - MyEmployees.

Convertor.RegisterObject("MyObjectKey", MyEmployees);

The number of registered objects is not limited. After that, the object MyEmployees can be accessed on the client as a JavaScript class ArrayList.

var EmployeesArrList = _Get("MyObjectKey");

Get the first employee:

var emp = EmployeesArrList.GetAt(0); 
alert(emp.SName + ", " + emp.Name + "," + emp.Title + "," + 
      emp.Position + "," + emp.Address.Street);

Same with other employees.

The employees in the collection can be modified and sent back to the server via the traditional Postback or [and] AJAX. You can invoke the method on the server with EmployeesArrList (or another class) as the parameter as well.

var Params = new Array();
Params.push(EmployeesArrList );
var Ret = r.Invoke("ReadEmployeesMethod", Params);

You can create the instance of the Employee(s) and initialize it:

var Emp1 = new Employee ();
Emp1.Name = "Peter";
Emp1.Age = 20;

And so on ... Add this employee to the collection.

How it works

The business objects on the server are initialized and then serialized to XML format. Then, this code is injected into the HTML page body and sent to the client for rendering. The data is kept in the hidden field. The serialized data is deserilized on the client into the collection of JavaScript objects when the page is loaded.

Data synchronization

Now that we have the data from the server in the form of JavaScript objects, like the Employee object, we can change the fields of these classes.

emp.Position = "waiter";

The next logical step is sending the objects back to the server. This can be done in two ways: Postback and AJAX. The updating of the server objects only requires calling the method.

_Put("MyEmployeesArr", EmpArrList);

before the Postback takes place.

Another way to update the objects on the sever is sending the collection via XmlHttp. In order to do that, just call:

r.Send ("some string data from client"); 

In this particular case, the string 'some string data from client' will be sent to the server.

The objects defined on the server (and recreated on the client), like Employee, can also be sent:

r.Send(emp);

Or the collection of the objects:

r.Send(EmployeesArrList);

where r is Remoting (JavaScript object defined in Rwc.js).

Also, the method on the server can be called; using the method Invoke (also defined in Rwc.js):

var Ret = r.Invoke("ReadABCD", Param1);

where ReadABCD is the method's name on the server. Param1 is the object (any object that is defined on the server and registered).

Here is an example of calling Invoke:

var Params = new Array(); 
Params.push(EmployeesArrList );
var Ret = r.Invoke("ReadEmployeesMethod", Params);

You can create (on the client) an instance of Employee(s) and initialize it:

var Emp1 = new Employee ();
Emp1.Name = "Peter";
Emp1.Age = 20; //..... And so on ...

Add this employee to the collection:

var EmpCollection = new ArrayList();
EmpCollection.Add(Emp1);

Add other employees and send this collection to the server [Postback/AJAX]. On the server side, the objects are received as the instances of objects which have been previously registered.

On the server-side, objects sent via AJAX are received by l_DataReceivedEvent handler.

private object l_DataReceivedEvent(object obj)
{     
    if (obj is Hashtable)
    // check the type of the object sent from the client
    { 
        return "Server: Update OK";
    }
    return "Return a string ";
    // can be returned any registered object
}

If the standard Postback was used, the object is received using the l_PostBackDataReceivedEvent handler.

private void l_PostBackDataReceivedEvent(object obj)
{ 
     Hashtable ht = (Hashtable)obj;
     // all objects on the client are packed to hashtable when PostBack is used

    ArrayList emps = (ArrayList)ht["MyEmployeesArr"];
    Convertor.RegisterObject("MyEmployeesArr", emps);       
}

Data types

Data types that do not have JavaScript representation are absolutely useless. For instance, if you have a class with a member field defined as a TimeSpan, it can not be translated to JavaScript.

Supported data types

  • int
  • char
  • bool
  • float
  • double
  • string
  • DateTime
  • ArrayList
  • Hashtable

The framework and ASP.NET components

The framework has nothing to do with ASP.NET components; it is just a generic, structured data delivery mechanism. However, this framework may be very useful for such components design - it can provide structured data for the components and can be easily integrated with the component framework.

Live demo

A live demo is available here: RWC_Live.

VersiVersion

The current version is 1.0.2.

Credits

For better performance, the framework uses the JavaScript compressor by Eric Woodruff.

If a new version is released, it can be downloaded from www.dotnetremoting.com along with other useful components.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Alex_1
Web Developer
Australia Australia
No Biography provided

Comments and Discussions

 
QuestionMaybe I'm missing something, but is this really a problem today? PinmemberDewey16-Mar-08 14:54 
AnswerRe: Maybe I'm missing something, but is this really a problem today? [modified] PinmemberAlex_116-Mar-08 15:49 
GeneralRe: Maybe I'm missing something, but is this really a problem today? PinmemberDewey16-Mar-08 23:33 
Well, all I can say is this.
 
The one thing that's 99 and 44/100 percent clear is that AJAX is a loser, and RIA's will rule the roost, and your prediction(or the talking heads) is that the HUGE community of .Net developers are going to jump to Google or Adobe?
 
Not in this parallel dimension of reality. With SilverLight, I don't need XmlHttp, and I can send C# objects across the wire, and I have access to files in my distribution, with local isolated storage... I'm in heaven.
 
On top of that, I can produce user interfaces that would make the best AJAX developer fold up his tent and start selling used cars. Add to that the fact that SilverLight has almost all the controls you'll need for business development(oddly the combo box and the tree control isn't there, but it is only Beta 1).
 
You really need to look at SilverLight 2.0 Beta 1, because the development environment is much superior to any Flash development I ever seen, a true programming environment, not a development environment evolved out of a movie model.
 
As a matter of fact, at the company I work for, we're moving towards ONLY doing things in SilverLight vs AJAX. AJAX has now become legacy, it's really obsolete, and non competitive. The choice is not to choose AJAX, it's which RIA to choose, Adobe or Microsoft. I submit that ,Net developers will make the Microsoft choice all day long, and twice on Sunday.
 
Finally, on JSON, I can send multiple objects to the client at the same time, it's easy. I send very complex objects to the client composed of arrays of objects, and nested objects. I can send hash tables of objects that are totally different. JSON is proven, not evil, and faster over the wire than XML.
 
However, I will send XML in the SilverLight environment because JSON isn't needed when javascript isn't the target(now javascript is sometimes evil, lol).
GeneralRe: Maybe I'm missing something, but is this really a problem today? PinmemberAlex_117-Mar-08 0:11 
GeneralRe: Maybe I'm missing something, but is this really a problem today? PinmemberDewey17-Mar-08 20:30 
GeneralAnother javascript library for remoting PinmemberTroels Wittrup Jensen16-Mar-08 12:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141220.1 | Last Updated 16 Mar 2008
Article Copyright 2006 by Alex_1
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid