Thursday, July 31, 2008

ASP.NET MVC, AJAX, and JQuery

I have been developing asp.net application from .NET framework 1.0, 1.1, 2.0, 3.0 - so pretty much from the begining. Nowadays, what really excites me (as far as programming goes) is ASP.NET MVC. The MVC model has been out there for a while in the Java world or Ruby world (with rails). But it is only since .NET Framework 3.5 that Microsoft ASP.NET starts to pick it up.

One thing that I really like about MVC (compared to ASP.NET webform) is the ability to control your HTML directly. This therefore empowers you to create your own Javascript component easier. In a way, it is a bit more manual then webform, but the total control and flexibility really pays off.


AJAX therefore then can become TRUE AJAX, rather than "fake" AJAX like webform's UpdatePanel. Payload is much smaller between client and server - which makes MVC app super fast (if done right, especially with AJAX).

ASP.NET MVC also enables you to have a TDD (test driven development) approach to UI development. Since all "controls" or "pages" are rendered by invoking an "Action" methods - which is just a regular method - there those methods can be called by a Unit Test of your choice and checked.

.NET framework 3.5 allows you to have pretty URL too. Initially baked into MVC assemblies, but in SP1 it will be released as part of the framework itself.

So, how do you code MVC? Is it really any different than C# or VB? Well, here is the thing, MVC is not a language or third party tools. It is more of a UI development framework. So you still use the same language (like C#, VB, etc).

For me, development in MVC pattern have been quite an experience. It really brought back the true power of separation between your model to your view/presenter but in a very powerful manner. Having a strong tight and concise HTML combined with the ability to maximize your Javascript without the use of 3rd party controls really opens tons of possibilities - this is really where you can fully utilize AJAX, in which I choose to use JQuery.

JQuery is a javascript framework. It is really powerful because it has a superb selectors - therefore with concise code, you can really do a lot of stuff that normally will take tons of code. So, what does it look like?


Here is the code to do that (just 1 line):

$("#surprise").slideToggle();

In JQuery website, you can read about all the APIs and its capabilities. It is quite amazing and opens new possibilities for your UI development.

You can read more about ASP.NET MVC:
Code Plex
An Architectural View of the ASP.NET MVC Framework
ASP.NET page
Scott Gu's Blog

JQuery:
JQuery
-- read more and comment ...

Google Visualization

Google Visualization is an API where you can feed your data to it and it will produce for you a "visualization" of your data; such as in a pie-chart, bar-chart, line-chart, and even some more complex visualization rendering. In other words, if you have structured data (dynamic or static), you can let Google handle the rendering of its visualization for you (instead of making a screen capture/image in a desktop app and including it in your web app/site).


Here is an example (taken from Google pie-chart code example) on how to render a pie chart about daily activities. From this basic code, we can customize the code to our liking, including displaying dynamic data.


<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["piechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Hours per Day');
data.addRows(5);
data.setValue(0, 0, 'Work');
data.setValue(0, 1, 11);
data.setValue(1, 0, 'Eat');
data.setValue(1, 1, 2);
data.setValue(2, 0, 'Commute');
data.setValue(2, 1, 2);
data.setValue(3, 0, 'Watch TV');
data.setValue(3, 1, 2);
data.setValue(4, 0, 'Sleep');
data.setValue(4, 1, 7);

var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, is3D: true, title: 'My Daily Activities'});
}
</script>
</head>

<body>
<div id="chart_div"></div>
</body>
</html>

The result (you can click on the chart btw - and get some details):


As I mentioned above, customization is easy. With dynamic data that comes from the server, as long as you can form your data to conform with the javascript data.addColumn format, you are set! Here is an example using data coming from ASP.NET MVC ... (or using JSON is also very easy)

<script type="text/javascript">
google.load("visualization", "1", {packages:["piechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Hours per Day');
data.addRows(<%=(ViewData["MyTasks"] as List<Task>).Count() %>);
<%
int i = 0;
foreach (var task in (ViewData["MyTasks"] as List<Task>))
{
int j = 0;
%>
data.setValue(<%=i %>, <%=j %>, "<%=task.TaskName.Length > 15 ? task.TaskName.Substring(0, 15) + " ..." : task.TaskName%>");
<%j++; %>
data.setValue(<%=i %>, <%=j %>, <%=task.Hours %>);
<%i++; %>
<%
}
%>
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, is3D: true, title: 'My Daily Activities'});
}
</script>

Now, if you are using ASP.NET web-form, is it not that easy to get your data out from your code-behind and expose it to the javascript api of Google Visualization. In this case you may need to expose your object as a protected property of your control/page so it can be accessible.

Nevertheless, once you are at the point where your data is accessible, sending your data to Google and getting a visualization back is a breeze (and fast too).

Cool, huh? Now, let's look at the code in more detail:

<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
...
This part of the code is where you reference Google's API in your code. There is no javascript to download etc, and this is all you need to do to make the API available for you. Now, in a way this is cool, because you don't need to worry about the javascript itself, less file to maintain, etc. But, it also means that there is no intellisense. I don't think it is that big of a deal, since the code you are writting will be pretty concise anyway.


...
google.load("visualization", "1", {packages:["piechart"]});
google.setOnLoadCallback(drawChart);
...
This section of code is what telling the API about what visualization you want to use (such as "piechart") and instantiate it, then it calls the method "setOnLoadCallback" passing in a method "drawChart"; which that puts the data together send it to the API to be drawn. The method "drawChart" is not a Google method. It is a regular javascript method and you can call it whatever you want (such as "myMethod" or "whatever") and as long as it is consistent in its uses, you will be fine.


...
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Hours per Day');
data.addRows(5);
data.setValue(0, 0, 'Work');
data.setValue(0, 1, 11);
...
The example we are looking at is using a "DataTable" type to hold our data. This is probably the simplest way of holding our data to be sent to the visualization engine. I am not sure if there are any other data structure available from Google, but so far I have not had any needs to go beyond what DataTable has been able to provide. Anyway, this section of code is basically for putting our data together into the DataTable object "data". DataTable is basically an array. So when we are setting the values using setValue method, we are setting the data based on a specifiec coordinate (row/column). The method setValue takes in these parameters: row, column, value. You can have as many columns as you want as long as you define them - using addColumn method - before putting data into the DataTable.

...
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
...
This code is pointing out to Google Visualization on where to draw the chart. I created a div space in my HTML and gave it an id ("chart_div").

Click here to go to Google Visualization Gallery.

-- read more and comment ...

Wednesday, July 30, 2008

The Flip is Sweet!

It has been over a month since I bought a Flip for my wife as a birthday present. Wait! What is a "flip" you say? A "Flip" is a video capturing device that is as big as your Treo phone. Not only it is small, but it is also excellent in capturing video and very user friendly.


My wife has been pretty happy with it and I tell you, it is probably one of the best bang for the buck investment I have done lately. The one that I bought is the "ultra" version. It has a higher quality video than the basic, uses 2 AA batteries, more color options, etc. You can see the complete comparison here.

Helen mostly uses it for shooting video about Jon so we can send them to my parents. It is very easy to use - Scott Hanselman says that it has a very high WAF (Wife Acceptance Factor). There are only 5 buttons: record, play, delete, next and previous - and they are self-explanatory. Sync-ing with a computer is a breeze and you can configure it to auto upload to YouTube if you want. You do need to install MPEG-4 coded to paly it back in your computer though - or you can just install the software that comes along with the Flip itself.

I paid $129 for mine @ Amazon - and it is probably cheaper now since the Mino is out.

Here is a sample - Jon dancing his Robot Dance:

The "flashing" light was me taking pictures with my digital camera.




-- read more and comment ...

Boston Trip (day 4 & 5)

Helen's sister and her family went to Nantucket island and spending the night there - and we decided to go home to Columbus Thursday evening, but we wanted to spend some time in Boston before leaving.back in ohio


Thursday (7/24):
Hearty breakfast @ home with Helen's aunt's homecooking (yummy ...) started our day. We were planning to go to MIT campus and spend the rest of day @ Quincy market area. I plotted our course through Google map and copy them down on paper - all was good to go. I was driving and we took 1 right turn too soon (Boston street name signs are not the best) and we ended up in Newbury St. again.

After deliberation, we decided to stop and walk along Newbury St. again ... since last time we missed some good spots and Mom's birthday was coming. As parking was quite difficult, after circling Newbury for 4 times, we found a spot for our car and started our birthday gift searching. Jon fell asleep in the car during the parking spot hunt. Within half an hour into our nice sunny day walk, suddenly it got dark quickly and started pouring rain ... we ran back to our car all soaking wet - Jon was not because he was in the stroller with the cover on - o well. My camera was poured on - worried me a bit - but it was ok.

quincy market Somehow with all these madness and damp, we wanted to march on to go to Quincy market - so off we go - with spotty direction nonetheless. Needless to say, we were lost for about an hour (it was pouring hard too during that time). Phone call here and there to Helen's cousin and SMS to Google to get directions, and finally we got into our destination - Quincy market. The rain stopped and we had a nice lunch at the food court, window shopping, and got Mom's birthday present. We went back to Helen's cousins apartment to take an afternoon nap and rest before the long drive home after dinner.

For dinner we went to a restaurant called "Bernard's" - a chinese food restaurant in Boston's suburb. One of the food that we order was a a deep fried sea bass with some kind of spicy sauce - it was awesome! Gotta look that restaurant up again next time we are in the area.

Helen and I cannot thank Helen's aunt enough and her cousins for their generosity in allowing us to invade their apartment for several days and showing extended hospitality toward our family. We finally took off from Boston around 10pm EST ... to the west ... o well - midwest!!

Friday (7/25):
After a looooong drive, we finally got back in Ohio. We stopped by Cleveland (around 8:30am) and planning to go to a Chinese restaurant called "Li Wah" to get dim sum. But it was not open until 10am (crap ...) so we continued on and stopped @ Bob Evans to get breakfast before going into Columbus. Home sweet home ...

-- read more and comment ...

Tuesday, July 29, 2008

Boston Trip (day 3)

Wednesday (7/23):
After a well needed sleep and rest (after the long 13 hours drive), we woke up and headed off to Portland, Maine on Wednesday. Stop by at the Lighthouse and had lunch @ Flatbread Co. We thought it was seafood related flatbread/pizza, turns out just a brick oven pizza with NO seafood!!



lighthouseThe lighthouse was awesome. It is somehow related to the "Perfect Storm" (also a movie by the same name/title). The weather was cloudy with some breeze, good enough for photography. I bracketed some shots for HDR and reached a borrowed Nikon F5 for a slide shot, but it was not working. Got an "ERR" message on the display. Crap! Must go full digital for the rest of the trip - I guess it was not that bad - my Nikon D80 is reliable. Put my SB-600 on and got some people shots with balanced (not blown out sky and properly lighted subject).

O well ... it was starting to rain and we were hungry - so we are off looking for places to eat - "Flatbread". Even though it was just a regular brick oven pizza place, but the pizza was excellent. flatbreadJon had a good time looking at the brick oven and comparing it to my smoker/grill (not in the same league) - and walking out in the deck, where there were boats and birds.

We took a stroll on the same street as the restaurant, going in shops etc and we left Portland around 4pm, promising our cousins that we'll be back in Boston by around 6pm. Goof around at home (and let Jon plays Guitar Hero) and resting before heading off to dinner.jon and guitar hero

For dinner, we went to Union Oyster House for more seafood! We ordered a combination plate filled with scallops, shrimp, crabs, lobster, and fish on top of rice pillaf. It was great! But ... there were no refills for sodas (bummer =( ). Union Oyster House is one of the oldest restaurant in Boston, filled with history, and of course - excellent food. The place was packed - and we were there closer to 8pm, so it was past normal dinner time - but still filled with people. I stopped by Hard Rock Cafe on our way home and got my shirt and bought one for Jon and Helen as well.
-- read more and comment ...

Sunday, July 27, 2008

Boston Trip (day 1 & 2)

Boston was awesome. It was a long drive (13.5 hours from Columbus, OH) ... good thing we left from Columbus and going back to Columbus at night (so Jon slept 90 % of the trip). We left Monday night and got back in Columbus by Friday morning. The trip itself left me a desire to comeback and spend more time in New England area.



Monday night (7/21): leaving Columbus

Tuesday (7/22):
breakfast! We stopped for breakfast. We were looking for an IHOP, because my niece was craving for it ... but it was not open when we got there (during breakfast time - like 8am). So the other option was Cracker Barrel - since hungriness was eating our souls, Cracker Barrel it is ...

Arrived in Boston around 10am, went straight to our cousins apartment. Helen's aunt cooked some killer Indonesian food for lunch! With full stomach we headed off Harvard Square. Jon & John Harvard Jon did not want to be photograph with John Harvard (he said he liked Brutus better - good answer!) - but he had an excellent time chasing squirrels (apparently squirrels in Harvard are friendlier to human than ones in Columbus). Took some pictures here and there with some old buildings ... and next destination is ... ice cream @ Newbury St. PJ Licks!

But first, our our way back to the car, Jon fell down on and literally kissed the concrete, got blood gushing out of his lips and into his mouth, his nose also bleed. I carried him in my arms (he was crying, obviously ...) while wiping tears and blood out of his face and chin. Turns out it was not that bad, all teeth were still intact, only busted lips. Jon fell asleep in the car to Newbury and we just put him in the stroller while we were there (he pretty much asleep for the whole walking around in Newbury - about 1.5 hours).

Newbury St.Newbury St was awesome. We could have spent the whole day just walking around in Newbury St. But our destination was JP Licks ... an ice cream joint - just perfect for the weather. With Jon sleeping on the stroller, we walked and walked and walked ... the ice cream joint was 7 blocks away from where we parked (about 1-1.5 miles), but since parking is precious on Newbury St., so we accepted the consequence of walking.


I never knew that Paris also has a "Madura" - it is an island north east of Java, Indonesia.

after dinnerLegal Seafood for dinner ... Legal Seafood is a staple of Boston dining experience for seafood. Just 3 blocks away from JP Licks, we went there directly. It was excellent seafood ... we had plenty of food and kept sampling each others' food. After dinner Jon and I went for a walk in the mall (while everybody else was having desert). That was it for Tuesday ... we called it a day and went home ...

-- read more and comment ...