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 :)

Friday, May 4, 2007

Creating and Submitting a Sitemap to Google

As many know, Google search results are based on a crawler software that surfs our sites like a regular user, more or less. If for some reason we have pages on our site that are not linked from any other page, they will not appear in search results. In order to improve google's crawling in our site we should send google a link to an Xml file that we create in our site, and in this file we can list all the site's pages that we want Google to show in his search results. This file is called a Sitemap.

If a site is made of static pages, you just write them down in your file and you are done. All you need to do now (After submitting the Sitemap, of course) is to update the file with any new pages that you create. If, on the other hand, you are running a dynamic site that pulls it's pages out of a database, you have more work to do.

First, you need to create a Permalink for every page. Permalink is a static Url, without ? and parameters in the Url. You can use any unique value for that, like product name or page title.
A permalink can look like this: http://www.5min.com/Video/What-is-5min%20XH9DUGl7fO8%3d.
Then you need to generate the sitemap from a server page. You can use the XmlDocument object model to build the correct Xml file format. I suggest that you use an HttpHandler for this task, but any Asp page will do as well. All you need to do is to write the Xml file into the Http Response object.

Now that you have the Sitemap ready, you have to submit it to google as your Sitemap. For this you have to register to the Google Webmaster Tool service. If you already have a Google account then it's enough. There you have simple instructions how to submit your Sitemap. You can submit many sites and see how google reads them and more statistics.

You can find good information on Sitemaps at http://www.sitemaps.org/.
An already-made c# Sitemap class can be found here.

Please comment with your opinion on this post.

Benny.

Sunday, April 22, 2007

Debugging Javascript in Visual Studio

Last week our server crashed, and had us roaming the internet with no purpose for a couple of days. Maybe one day I will write about that a separate post. The outcome of this is that all Internet Explorer definitions were reset when i connected to the new server and domain.


Since then, i was unable to debug javascript in visual studio. It took me a while to verify that I'm trying to debug the correct script and that the calling procedure is working fine.

I made sure that IIS was configured to debug asp pages, as you can see in the following pictures.
Inside the IIS console open the web site properties.


On the "Virtual directory" tab click on "Configuration".

In the configuration dialog select the Debugging tab and check the two debugging flags.

The last thing to check was Internet Explorer Options. In order to debug Javascript inside Visual Studio one must uncheck the (default) options that disable javascript debugging both on Internet Explorer and on other browsers. this is the checkbox to uncheck:


Well, Now you can just break an any Javascript line, see all values inside the Visual Studio enviroment, and generally have fun while debugging your site :)
benny is freely debugging javascript...


IFrame strikes back

Well, the IFrame bug from last post still exist, and we still don't know what to do about it.
Some good news are that this bug now appears only seldom and we are less concerned about it. We created a random query string that we attached to this frame source url, to make sure that the browser really really really not caching the page. this way the browser thinks its a new page every time. This (at least we think so) lowered to frequency of appearance of the bug to reasonable levels. Yet, the mystery continues...

Thursday, April 12, 2007

IFrame object loads wrong pages !?!?!

This is truly a bug from hell.

For the last two days the upload page on our site behaves very strange. If it was not so creepy i would say the page is sick :-)
this page includes an IFrame object that shows a second page inside, we will call them Outer page and Inner page.
What happends is this: when entering the outer page we sometimes see the inner page correctly. Other times we see the inner page broken, and the source shows that not all page was loaded. Other times we see even stranger things: the inner page is partially loaded and a totally different page is appended to it's end, creating a total mess on the page.

this bug appears only on our production server (dedicated, hosted) and not on our internal network. We tried to move the javascripts on the page around with no change. We tried putting a meta tag that prevents caching of the page - again nothing changed.

We are going to try a sniffer on the response and compare it with the browser source, maybe something goes wrong while rendering this page.

I have not fount any documentation of such a bug anywhere on the net. I still didn't get any answers from any newsgroup or from Experts Exchange (a great technical solution site). I'm getting a little worried...

If anyone ever encountered such a problem or has any suggestions i will be happy to hear it.
I will keep rolling this story as it happends.

Scratching my head :-)
Benny.

Flash object fails to call Javascript function

The most popular way to show video in web pages today is to play the video files inside flash players that are embedded inside the html page. Like everyone else we did it too and it works just fine.

A new feature that we added to our site is the ability to embed our flash player into any blog or site page, and for this purpose we also added a feature that sends information from the flash player to our server each time someone plays one of our videos somewhere out there. That way we can count how many views our videos get even outside the site.


When we added this view-counter feature we could not get it to work. The flash player did not reach the server page even though we wrote the calling code properly.


After looking at some professional blogs and sites we found out the problem: we use the name "5minPlayer" as our player tag name, and the Object tag that holds the flash player should not begin with a number...


There are other limitations to this object tag, and also many things you should know if you are going to use flash on your page, especially if you are implementing extensive interaction between flash and the html page. A great page on this issue can be found here.