Showing posts with label Facebook. Show all posts
Showing posts with label Facebook. Show all posts

Saturday, January 1, 2011

Posted by SAMAJ SHEKHAR

0

Serializing and Deserializing Data from Json to .Net Objects. ( Example Facebook Feeds)


A very very Happy New Year to you all. I thought why not start this year with a nice blog post, so here i am with a post on how to Deserialize data from Json to a .Net Object and back again.Many libraries exist for this Job most notabely the Json.Net and Dynamic Rest library by Nikhil Kothari

But developer community has always asked why microsoft didn't have it in the Frame work. Well now they have one. It comes in frame work now with an added dll of "System.Web.Extentions.dll". That provides us the Class JavascriptSerializer which you can use by including a using statement as follows.

using System.Web.Script.Serialization;

Before going into the code, let us first understand what is JSON, and what is its significance in the modern world of web applications.

What is JSON?

JSON is another format of expressing data, just like XML. But, JSON is very simpler than XML, and tiny than XML. So, it is becoming popular in the web world to choose the JSON notation over XML since JSON notation are usually shorter, and less data to be transmitted if at all they were to be.

A Simple Example

So lets understand this process with an example, since i am currently working on a project which uses facebook to query data, i think this will be helpful to the facebook developer community also. So first you need to define a class that matches the JSON object you are receiving. like a class if a Data in Json looks like below.

{
"obj1":"data",
"obj2":"10004",
"obj3":{
      "subobj1":"data",
      "subobj2":"data"
      }
"obj4":"data"
}

Then the corresponding class for that in .Net will be

public class MyObj1
{
    public string     obj1 { get; set; }
    public int        obj2 { get; set; }
    public MyObj2     obj3 { get; set; }
    public string     obj4 { get; set; }
}

public class MyObj2
{
    public string subobj1 { get; set; }
    public string subobj2 { get; set; }
}

Notice The obj3 in Json is a completely different class as it contains sub fields so a different class fo that in .Net. Also Remember JavascriptSerializer uses reflections to match field or property "names" with that in "Json" so be careful.

Now to deserialize above Json data to the .Net classes juat include the following line.

JavaScriptSerializer sr = new JavaScriptSerializer();
string jsondata = /*your json string here*/;
//Now with this line the Json string will be converted in MyObj1 object type
MyObj1 converted = sr.Deserialize<MyObj1>(jsondata);
Facebook Example (Deserializing Facebook Feeds)

Now the data returned by facebook's Graph API is also in Json and below is an sample data returned by

http://graph.facebook.com/samajshekhar/feed?limit=1

{
   "data": [
      {
         "id": "100000570310973_182862925076050",
         "from": {
            "name": "Samaj Shekhar",
            "id": "100000570310973"
         },
         "message": "#Wow A decade has passed .. #Happy New year to every one....May this new  year be the most luckiest for you and every one.",
         "icon": "http://photos-d.ak.fbcdn.net/photos-ak-snc1/v27562/23/2231777543/app_2_2231777543_9553.gif",
         "actions": [
            {
               "name": "@samajshekhar on Twitter",
               "link": "http://twitter.com/samajshekhar?utm_source=fb&utm_medium=fb&utm_campaign=samajshekhar&utm_content=20985773201301504"
            }
         ],
         "type": "status",
         "application": {
            "name": "Twitter",
            "id": "2231777543"
         },
         "created_time": "2010-12-31T23:32:54+0000",
         "updated_time": "2010-12-31T23:32:54+0000"
      }
   ],
   "paging": {
      "previous": "http://graph.facebook.com/samajshekhar/feed?limit=1&since=2010-12-31T23%3A32%3A54%2B0000",
      "next": "http://graph.facebook.com/samajshekhar/feed?limit=1&until=2010-12-31T23%3A32%3A53%2B0000"
   }
}

Don't get confused its just little more data of different types including arrays. ( To get data from facebook you can use System.Net.HttpWebRequest and System.Net.HttpWebResponse class). So Now the equivalent .Net classes will be as follows.

Note:

I have included only the classes needed for the above feed for a complete class that accommodate all fields returned in feed with and without access token can be found here at

http://thesharepage.codeplex.com/SourceControl/changeset/view/5405#100657

public class FacebookFeedsWithoutToken
{
 public FacebookFeedWithoutToken[] data { get; set; }
 public ReturnedDataPaging paging { get; set; }
}

public class FacebookFeedWithoutToken
{
 public string id { get; set; }
 public NameIdPair from { get; set; }
 public string message { get; set; }
 public Uri icon { get; set; }
 public NameLinkPair[] actions { get; set; }
 public string type { get; set; }
 public NameIdPair application { get; set; }
 public DateTime created_time { get; set; }
 public DateTime updated_time { get; set; }
}

public class NameIdPair
{
 public string name { get; set; }
 public string id { get; set; }
}

public class NameLinkPair
{
 public string name { get; set; }
 public Uri link { get; set; }
}

Now the classes are ready we just need to convert from json string to .Net object types. add the following line similar to above.

JavaScriptSerializer sr = new JavaScriptSerializer();
string jsondata = /*your json string here*/;
FacebookFeedsWithoutToken converted = sr.Deserialize<FacebookFeedsWithoutToken>(jsondata);

Thats all you have to do.

And once again Happy new year.

READ MORE - Serializing and Deserializing Data from Json to .Net Objects. ( Example Facebook Feeds)

Wednesday, December 15, 2010

Posted by SAMAJ SHEKHAR

1”

Creating a Facebook like badge


This a small walkthrough of how you can go about creating a Bage just like Facebook Badge.

Infact While developing my project i myself thought of creating a facebook like badge that can later be saved on the server and used with a link to it. Following is the complete class code to generate the badge(Its also available on codeplex, and following is basically explaination of code there).

(Note: replace the"Image.FromFile(@"C:\Users\SHEKHAR\Desktop\Test HTML\tsp1.png");" with a path to image that can be used as a title bar in the badge.)

The Badge Class

First Declare the Class and some variables to hold on required information. (made it sealed so it couldn't be inherited).

public sealed class TSPBadge
{
 /// <summary>
 /// Image for the TSP badge's title bar (Static Field)
 /// </summary>
 private static Image TSPBadgeTitleBar = Image.FromFile(@"C:\Users\SHEKHAR\Desktop\Test HTML\tsp1.png");

 /// <summary>
 /// The Default Width for TSP Badge (Constant Field)
 /// </summary>
 public const int DBadgeWidth = 300;

 /// <summary>
 /// The Default Height for TSP Badge (Constant Field)
 /// </summary>
 public const int DBadgeHeight = 500;

 /// <summary>
 /// Set this variable to true if a TSP badge has been successfully made
 /// </summary>
 public bool IsMade = false;

 /// <summary>
 /// Initializes the static members of the TSPBadge Class (Static Constructor)
 /// </summary>
}
Class Constructors

Now lets define both static and instance constructors.

/// <summary>
/// Initializes the static values of TSPBadge with default values
/// </summary>
static TSPBadge()
{
BadgeWidth = DBadgeWidth;
BadgeHeight = DBadgeHeight;
}

/// <summary>
/// Initializes a new Instance of TSPBadge with default values
/// </summary>
public TSPBadge()
{
 IsMade = false;
 UserPic = null;
 UserName = null;
 EmailID = null;
 UserStatus = null;
}

/// <summary>
/// Initializes a new Instance of TSPBadge with specified Width and Height
/// </summary>
/// <param name="Width">The Width for the TSP Badge</param>
/// <param name="Height">The Height for the TSP Badge</param>
public TSPBadge(int Width, int Height)
{
 BadgeWidth = Width;
 BadgeHeight = Height;
}

/// <summary>
/// Initializes a new Instance of TSPBadge with specified Image, Name, Status and EmailID.
/// </summary>
/// <param name="userpic">The user's picture</param>
/// <param name="username">The name of the user</param>
/// <param name="emailID">The user's EmailID</param>
/// <param name="userstatus">The user's most recent status text</param>
public TSPBadge(Image userpic, string username, string emailID, string userstatus)
{
 IsMade = false;
 UserPic = new Bitmap(userpic);
 UserName = username.ToUpper(CultureInfo.InvariantCulture);
 EmailID = emailID;
 UserStatus = userstatus;
}
Properties

Following are defination of some properties that will help you to alter the settings when required.

/// <summary>
/// Gets or Sets the Width to be used for drawing TSP badge. (Static Property)
/// </summary>
public static int BadgeWidth { get; set; }

/// <summary>
/// Gets or Sets the Height to be used for drawing TSP badge. (Static Property)
/// </summary>
public static int BadgeHeight
{
 get
 {
  return _BadgeHeight;
 }
 set
 {
  GraphicsUnit gu = GraphicsUnit.Pixel;
  //The TSP Badge's Minimum height is the height of TSP TitleBar's height
  if (value <= (int)TSPBadgeTitleBar.GetBounds(ref gu).Height)
  {
   _BadgeHeight = (int)TSPBadgeTitleBar.GetBounds(ref gu).Height;
  }
  else
  {
   _BadgeHeight = value;
  }
 }
}
private static int _BadgeHeight;

/// <summary>
/// Gets or Sets the User Picture to be used for drawing TSP Badge
/// </summary>
public Bitmap UserPic { get; set; }

/// <summary>
/// Gets or Sets the User Name to be used for drawing TSP Badge
/// </summary>
public string UserName { get; set; }

/// <summary>
/// Gets or Sets the User EmailID to be used for drawing TSP Badge
/// </summary>
public string EmailID { get; set; }

/// <summary>
/// Gets or Sets the User's Status text to be used for TSP Badge
/// </summary>
public string UserStatus { get; set; }
Methods for drawing

Lets draw the badge!

/// <summary>
/// Draws a TSP Badge on bitmap with specified Image, Name, Status and EmailID. (Static Method)
/// </summary>
/// <param name="userpic">The user's picture</param>
/// <param name="username">The name of the user</param>
/// <param name="emailID">The user's EmailID</param>
/// <param name="userstatus">The user's most recent status text</param>
/// <returns>Returns an  TSP Badge as an Bitmap Image</returns>
public static Bitmap MakeBadge(Image userpic, string username, string emailID, string userstatus)
{
 Bitmap bmp = new Bitmap(BadgeWidth, BadgeHeight);
 Graphics gf = Graphics.FromImage(bmp);
 GraphicsUnit gu = GraphicsUnit.Pixel;
 string BatchString = String.Format("{0}\n\nEMAIL:  {1}\n\nSTATUS:  {2}", username.ToUpper(CultureInfo.InvariantCulture), emailID, userstatus);
 //We are taking 60% of the bitmap space for User picture - (int)((float)BadgeHeight * (60F / 100F))
 //Write status, name etc in rest of 40% bitmap space
 float PicPer = 60F;
 float RstPer = 100F - PicPer;
 gf.Clear(Color.White);
 gf.DrawImage(userpic, new Rectangle(2, 2, BadgeWidth - 4, (int)((float)BadgeHeight * (PicPer / 100F)))); //NOTE: The rectangle here takes a non-zero based width/height so 300
 gf.DrawImage(TSPBadgeTitleBar, new Rectangle(0, 0, BadgeWidth, (int)TSPBadgeTitleBar.GetBounds(ref gu).Height));
 //TODO: Insert code to check name dosen't go out of title bar and get trimmed
 gf.DrawString(username.ToUpper(CultureInfo.InvariantCulture), new Font(new FontFamily("Arial"), 10F), Brushes.White, new PointF(5, 6));
 gf.DrawRectangle(Pens.Black, 0, 0, BadgeWidth - 1, BadgeHeight - 1); //NOTE: DrawRectangle takes a 0 based width/height so 300-1
 gf.DrawRectangle(Pens.Black, 1, 1, BadgeWidth - 3, ((int)((float)BadgeHeight * (PicPer / 100F))) + 1);
 gf.DrawRectangle(Pens.Black, 1, ((int)((float)BadgeHeight * (PicPer / 100F))) + 3, BadgeWidth - 3, ((int)((float)BadgeHeight * (RstPer / 100F))) - 5);
 gf.DrawString(BatchString, new Font(new FontFamily("Arial"), 10F), Brushes.Black, new RectangleF(5, ((int)((float)BadgeHeight * (PicPer / 100F))) + 6, BadgeWidth - 7, ((int)((float)BadgeHeight * (RstPer / 100F))) - 5), StringFormat.GenericTypographic);
 return bmp;
}

Now lets add some more methods in the class to make the MakeBadge static method accessible to instance methods and customizable too.

/// <summary>
/// Draws a TSP Badge on bitmap.
/// <para>NOTE: This function requires that all the requiremens are set already other wise it returns a null bitmap</para>
/// </summary>
/// <returns>Returns an  TSP Badge as an Bitmap Image</returns>
public Bitmap GetBadge()
{
 IsMade = false;
 Bitmap bmp = null;
 if (UserPic != null && UserName != null && EmailID != null && UserStatus != null)
 {
  bmp = TSPBadge.MakeBadge(UserPic, UserName, EmailID, UserStatus);
  IsMade = true;
 }
 return bmp;
}

/// <summary>
/// Draws a TSP Badge on bitmap with specified Image, Name, Status and EmailID.
/// </summary>
/// <param name="userpic">The user's picture</param>
/// <param name="username">The name of the user</param>
/// <param name="emailID">The user's EmailID</param>
/// <param name="userstatus">The user's most recent status text</param>
/// <returns>Returns an  TSP Badge as an Bitmap Image</returns>
public Bitmap GetBadge(Image userpic, string username, string emailID, string userstatus)
{
 IsMade = false;
 UserPic = new Bitmap(userpic);
 UserName = username.ToUpper(CultureInfo.InvariantCulture);
 EmailID = emailID;
 UserStatus = userstatus;
 Bitmap bmp = TSPBadge.MakeBadge(UserPic, UserName, EmailID, UserStatus);
 IsMade = true;
 return bmp;
}

That's all Happy Coding :)

READ MORE - Creating a Facebook like badge