Tuesday, November 25, 2008

JQuery and ASP.Net

Recently I had to built an online art gallery for an artist (still to be deployed :( ). The site is relatively small, from a menu a user can select a group of pictures (gallery) and these images are loaded into a JQuery carousel.

JQuery is a great lightweight JavaScript library and nowadays there are plenty of plugins out there to use. This is a great link for JQuery plugins.

In this little site I used a bunch of plugins, ThickBox, JCarousel and so on.

I used AJAX to wire the server side ASP.NET to the client side code.
Follow these steps to use AJAX and ASP.NET:

1. Create a WebMethod in the page:


[System.Web.Services.WebMethod()]
public static List GetGalleryImages(int galleryID)
{
return galleryService.GetGalleryImages(galleryID);
}


In this case, galleryID is a parameter passed from the client side and it returns a list Picture objects. Picture is a simple POCO populated from an XML file in my case.

2. In a JS here is the code that does the XMLHttpRequest call to the GetGalleryImages WebMethod:


function LoadGalleryImages(galleryID){
$.ajax({
type: "POST",
url: "default.aspx/GetGalleryImages",
data: "{'galleryID': '" + galleryID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg, status) {
LoadCarousel(msg.d);
},
error: function(xhr,msg,e){
alert("Server error, pls try again!");
}
});
}


Note that JSON is used to pass and return data. Parameters are passed as name/value array. LoadCarousel() is a simple JavaScript method to populate the JQuery Carousel.
The list of pictures is returned in msg.d

That's it, hope you find this approach useful. With this approach one can build rich sites using the power of JQuery, use domain objects to manage the business rules of the site and use the code behind of the page as a 'controller'. I didn't use the new ASP.NET MVC. For a one page web site I think its an overkill.

Monday, November 24, 2008

Sending an SMS from a mobile web site

One can send an SMS (Short Message System) from a mobile website by using the following syntax:

<a href="smsto:00441234567?body=This is a great blog http://jackdevofalltrades.blogspot.com">Send SMS</a>

So far so good, the problem I encountered is that on some mobiles the editor opens but the message is not displayed in the editor.
I encountered this issue on some Sony Ericsson mobiles, in particular mobiles on the HB107 platform.

The Href needs to be encoded to a "encoded word" with character set, according to RFC 2047 (ftp://ftp.rfc-editor.org/in-notes/rfc2047.txt) in this form:

=?iso-8859-1?q?here goes the message?=

Additionally, some characters must be Quoted Printable encoded. For example, blanks are replaced by "=20", and equal sign "=" is replaced by "=3D".

This result the original message into the following:
=?iso-8859-1?q?This=20is=20a=20great=20blog=20http://jackdevofalltrades.blogspot.com?=
For the Quoted Printable encoding I found a little utility class which did the job.

Finally, the string need to be URL encoded so it is treated as one body parameter inside the smsto link.
"=" is replaced by "%3D", "?" is replaced by "%3F" etc.

Creating a Facebook application in ASP.Net

Recently I had to create a proof of concept for a Facebook application. The idea was to create an external application where one can send messages to his Facebook friends without being logged in FaceBook.

Ideally one would write FaceBook implementation using PHP but since I prefer ASP.Net I had to add an additional layer to consume the REST APIs made available by the FaceBook team.

Finally, I opted to use the Facebook.NET framework over the FaceBookToolkit. I ran into issues when using FaceBookToolkit and I found FaceBook.NET more reliable and light.

Follow these steps and you will be up and running in creating a FaceBook application in no time:

  1. Download and unzip the FaceBook.Net framework from here
  2. Create a new Visual Studio website project and reference the FaceBook.Net dll.
  3. Now its time to create an application in Facebook. This is a good link to create a FaceBook application. Just follow the instructions. But select the radiobutton “Use Iframe” in “Canvas Page Url” since we are creating an external website not a FBML application.
  4. Secondly, to share your application with other users (one requires a minimum of 5 users before the application can be published) select “Yes” in the radio button that says “Can your application be added on Facebook?” in “Editing your settings”. A new section called “Installation Options” is displayed. Fill the mandatory fields. Also, unchecked the checkbox “Developer Mode”.
  5. Also note that for debugging purpose one can put a local url and thus can debug! Later the urls can be updated when the application is deployed.
  6. Now back to VS to start development. Although, the application will be external one still need to create a page residing in an iframe in Facebook so other users can “install” the application. Also, since we want to perform actions on behalf of users that are not logged in we need an additional step to get a permanent session key. Here are the steps (thus screens) to be created:
    1. From our external site ask new users to “install” the application in FaceBook. This page should redirect to the following URL: http://www.facebook.com/login.php?api_key=APIKEY where APIKEY is the APIKEY generated when the application was created in STEP 4 above.
    2. Once the user logs in FaceBook and accept our invitation he is redirected to the Callback URL (again set in STEP 4) above. This time the user comes with a temporary session key (maximum 24 hours).
    3. With this session we have to create a permanent session to store so we use this session to perform REST API calls on behalf of the user. We ask the user to generated a permanent key by putting a link on our page. The link should open the following page: http://www.facebook.com/code_gen.php?v=1.0&api_key=API_KEY
    4. This page creates a token which the user has to copy and paste in our page. Thus ideally the above URL should open in a new tab;)
    5. The code is the following to create a permanent session using the token provided:

FacebookRequest fr = new FacebookRequest(fbApplication.Session);
String userID = "";
bool expires = false;
String secret = "";
String sessionKey = fr.CreateSession(txtToken.Text, out userID, out expires, out secret);

User faceBookUser = fbApplication.Service.Users.GetUser(userID, null);

// sessionKey key needs to be stored in the DB!!!!!

Now with this session key we can perform any operation we want. Of course, as
requested by FaceBook a link must be provided to remove these rights.
But REST calls can be done as in the following example:

To retrieve your friends:
fbApplication.Service.Friends.GetFriends(FriendFilter.AllFriends);

To send notifications:
fbApplication.Service.Notifications.SendNotification(users,
txtMessage.Text, null);

fbApplication is the control provided by FaceBook.Net

<fb:FacebookApplication ID="fbApplication" runat="server" Mode="IFrame"

EnableExternalBrowsing="true"
ApplicationName="nudgebuddies" OnSessionCreating="fbApplication_SessionCreating" />

As displayed in the above code snippet we are implementing the OnSessionCreating
event. In this event we set our permanent session. The code for this event should
be something as follows:

protected void fbApplication_SessionCreating(object sender, FacebookSessionCreatingEventArgs e)
{
if (Request.Params["id"] != null)
{
String userID = Request.Params["id"];
String sessionKey = Request.Params["sessionid"];
e.SetInfiniteSession(sessionKey, userID);
}
}

It took me a whole day to try and figure out how one can implement this type of FaceBook application.
Hope its useful to someone!