Showing posts with label json. Show all posts
Showing posts with label json. Show all posts

Monday, June 18, 2007

Designing Business Objects for web2.0 Applications

When we sit down at the beginning of the process to design our brand new shiny web2.0 application (Please, not another social network...) we should consider several issues regarding Object Oriented design in general, as well as web2.0 application specifically.

Find your objects
This is true for every program. First thing to do is read the product specification (if working in medium or large company) or just describe the system in words. Notice the objects in your sentences as candidates for being objects in the system. For each one ask yourself: "Does it contain any information i should use?" This Information is the object properties. "What actions can this object perform?" leads to a list of methods. Objects on the list that have no properties or methods should not be objects in the system.

Remember the Channels
When selecting parameters for the methods and types for the properties remember who is on the other side. Is that a web page calling? A web service? Some Embedded code from this blog?
What are they asking for? What language do they speak?
You may consider writing a Data Access Layer that speaks SQL with the database and sends DataSet objects to the Business Objects. The business objects receive requests from Server-Side code that runs inside a web server. Those requests use a certain textual format to pass data to the server. Simple applications may send single values over Query Strings, but any real application should use JSON or XML as a data protocol with the web client. On this web client you may like to have some cool AJAX controls to smooth the User Experience, So you will need a set of Client-Side objects, written usually in Javascript.

Design Serializable Objects
If you are using JSON or XML you should design your objects to be serializeable. That means using only string, int, bool, object and array as the types of your properties. Any JSON Serializer can read such objects and this saves you iterating through all the object properties to read it's values. You just write something like MyJSONString = Serializer.Serialize(MyObject) and Bam! you got yourself a JSON string to send back to the browser.

Match Server and Client Objects
Since we have two sets of objects, one on the server and one on the client, we should match their properties to allow for smooth data transfer. There are JSON and XML serializers in javascript too, of course. You can avoid this problem all together by using a Library planned for this purpose like the Microsoft Ajax Extensions 1.0. Take a look but be careful, this package is only for professionals. It requires the best understanding of Internet technologies and much patience for Microsoft heavy object models.

Plan Great Utilities
Well, What do we do with all this? We can start by writing a set of utilities that will simplify our coding and will make the application more robust. One function we should write is a generic DataSet2Object function, that reads a dataset and returns a collection of the desired objects. There may be some others, but you get the idea.

Remember to breath :)

Benny.

Friday, May 18, 2007

Using JSON to connect Flash with Asp.Net

Life of a programmer are becoming more and more simple when it comes to finding professional help online. Almost any question i have regarding my work, like how to do this, why that doesn't work, etc' I can always find the answer one google search away. Few clicks later i have an explenation, code sample or other solutions. This week i tried to do something that had no good samples or documentation. That made me feel like i have reached the limits of existing technology, and know i'm trying things that other never did before. It is quite exciting for me.


This week Alexey and I wrote a simple "Invite a friend" feature. There is nothing exciting about that in itself. The feature was written inside a Flash control and the business object that actually sends emails is part of our site's engine written in Asp.Net.
Http communication between Flash and web pages is common, and can be done by using the LoadVars object in ActionScript code. You can see a good example here. There are practicaly 3 ways to transfer data over Http to Flash objects. One is sending the data "as is", which is good when you pass one parameter or two. Two is using XML to pack the data on one side and unpack it on the other side. Three is using JSON as the data structure standard. I chose JSON because the code required to Serialize and Deserialize JSON objects and strings is much simpler, shorter, more intuitive and more object oriented. You will see in the samples that one line of code is required in every side of the interaction to persist objects over http between Asp.Net and Flash ActionScript, or any other two sides for that matter.

The c# code for creating Json object on the server is available here and uses Newtonsoft Json.Net objects.
The Actionscript code however, is not available on the internet yet, only here. this code recieves the Json object inside Flash and reads it's values like this: ( I got this code from Trannie who wrote the Json ActionScript 2 object.)

In my projects I used LoadVars to grab the JSON string, so my JSON file
had a NAME=VALUE format with VALUE being the JSON string:

client= {
"name" : "Client",
"crop" : { "x1" : 3, "y1" : 3, "x2" : 623, "y2" : 472 },
"link" : {
"type" : "site",
"url" : " http://www.clientsite.com"
},
"title" : "Job Name",
"text" : "This is a string describing the project",
"details" : [
{
"full" : "Browse.jpg",
"thumb" : "THB_Browse.jpg"
},
{
"full" : "HSWebShot2.jpg",
"thumb" : "THB_HSWebShot2.jpg"
}
]
}

Hopefully that is still valid JSON. It's an excerpt from a JSON file,
so I may have introduced some typos..


In AS, I'd do something like:

var client:Object;
var json = new JSON();

var lv:LoadVars = new LoadVars();
lv.onLoad = function(success) {
if(success) {
client = json.parse(this.client);

trace(client.name );
trace(client.details[1]);
getURL(client.link.url);
}
}



We had some trouble on the ActionScript side because we confused the LoadVars Http object with the internal Json object, so let me elaborate on this. the LoadVars object is the one that use Load method to send Http request to the server, and the onLoad callback function that recieves the response from the server. In order to send Json string in such a request you should use ActionScript syntax to wrap your Json string. The response stream should include the "client =" part, which is NOT generated by the Json server-side class. This part is actually not part of Json, but is used by the Flash LoadVars object in order to read this Json string in ActionScript.

Finally, i want to hear from you what kind of uses can you see for such technology that connects Flash applications with Asp.Net objects so smoothly and easily.

Until next time,

Benny.Serialize(this)

Wednesday, May 9, 2007

Using JSON in AJAX based applications

Who the hell is Json ?
Ajax is a very popular way to create dynamic web2.0 style web pages. It is a method of making asynchronous Javascript calls from web pages to web servers, allowing web pages that refresh different parts of the page with server data without loading the whole page every time. Ajax is used for many different tasks from news reels to rating widgets and much more. The Ajax interface is simple and open. Send an Http request with parameters info, and receive a call-back with the Http response. You can send anything both ways, but when you need to move large chunks of complex data you are on your own. You have to define the data structures, take care of any errors that happen, and so on.

Json stands for JavaScript Object Notation. Json is a protocol (like Xml is) for defining data passed through Ajax requests and responses. Json does not have to be used only with Ajax, it can be used to define javascript objects out of any data received to the browser. But Json is at it's best with Ajax, which demands some standard protocol for moving data through it.

Json is supported on many platforms, like other open standards, and I will share my experience using it with Asp.Net and Visual Studio.

Who likes Json ?
Json is good for any Ajax situation that uses more then one or two parameters. The sites that make the most out of it are those built Object Oriented. Json is a simple way to maintain in Javascript Client code the same Object structure that you use on the server for getting the data and using your business-objects. If you keep to the same objects structure even through your Xhtml code and Css files, you will get a very flexible and stable site.

Implementing Json
Because Json is a client-server protocol there are two sides to the implementation :)
For server side i use Newtonsoft Json.NET. It is a Dll file and Xml file that reside in your bin directory of the site, and allows you (after creating the proper reference) to write this kind of code in your server pages:

Product product = new Product();
 
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
 
string output = JavaScriptConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": new Date(1230422400000),
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}
 
Product deserializedProduct =
(Product)JavaScriptConvert.DeserializeObject(output, typeof(Product));

This code is a sample of how to convert any custom object that you use in your site to a string in Json format. This string is passed back to the client inside the Ajax response. The last line of code shows how to reverse the process, and convert Json strings that are received from the client into server objects.

On the client side things look much the same, to the surprise of many Javascript programmers, me included.
In order to parse the Json strings into Javascript objects on the client I use the json.js file from Json.org. It includes a Json parser. The client side code for reading a Json string will be:

var myObject = myJSONtext.parseJSON(filter);
Then you can use myObject to access all his properties as they were on the server. Json supports any structure that includes objects with pairs of name-value properties inside them, and arrays of these objects, in any depth of nesting.
When you are done juggling these objects on the client you can send them back to the server, maybe with updated data or even send totally different objects. anyway, the code will look like this:

var myJSONText = myObject.toJSONString();



This is pretty much the basics of json, but there is much more, so expect more on Json soon.

If you are using Json in your work please reply and tell me how is it working for you, and what you are using it for.

Benny is inlove with Json :)