Social Icons

twitterfacebookgoogle pluslinkedinrss feedemail

Sunday, February 13, 2011

iPhone FBConnect: Facebook Connect Tutorial

Now a days social networking websites like facebook are becoming very popular, so integrating facebook with app has become a necessity to make you application popular. We are going to do the same through this tutorial. The Facebook Connect SDK provides code which third-party developers can embed into their applications to connect to their Facebook accounts and exchange information with iPhone apps. It’s a way of embedding “social context” to an iPhone app, according to Facebook.
Create a Viewbased Application with name ‘FacebookAPI’.
1.Download Facebook Connect for iPhone SDK (
Just go through the project. In particular, the “Connect” sample project. Sample Project gives demo of some of the functionality.
1.1.Open src/FBConnect.xcodeproj from SDK that you downloaded, and your own project as well.
1.2.Drag n drop FBConnect group. Make sure “Copy items into destination group folder” is NOT checked. It should look as shown below

1.3.Go to Project Menu ->Edit project settings and scroll down to “User Header Search Path” add entry which will point to “src folder”
1.4.To test import all .m n .h files in case any miss. And compile.
2.Login to Facebook. After that go to Developers Page ( as shown below.
3.Register your application with Facebook
3.1.Click on Set up New Application Button in the upper right hand corner.
3.2.Give Application name and click on create application button. Then you will see new application screen with detail including “API key”and “API Secret Key”
Note : This application will not work until you provide your Facebook application’s API keys.
Now to get started with actual coding:
Append Following code in


02#import "FBConnect/FBConnect.h"
03#import "FBConnect/FBSession.h"
05@class FacebookAPIViewController;
07@interface FacebookAPIAppDelegate : NSObject  {
08          UIWindow *window;
09          FacebookAPIViewController *viewController;
10          FBSession *_session;
13@property (nonatomic, retain) IBOutlet UIWindow *window;
14@property (nonatomic, retain) IBOutlet
15                           FacebookAPIViewController *viewController;
16@property (nonatomic,retain) FBSession *_session;
Append Following code in FacebookAPIAppDelegate.m

01#import "FacebookAPIAppDelegate.h"
02#import "FacebookAPIViewController.h"
04@implementation FacebookAPIAppDelegate
06@synthesize window;
07@synthesize viewController;
08@synthesize _session;
10- (void)applicationDidFinishLaunching:(UIApplication *)application {
12// Override point for customization after app launch
13[window addSubview:viewController.view];
14[window makeKeyAndVisible];
17- (void)dealloc {
18          [_session release];
19          [viewController release];
20          [window release];
21          [super dealloc];
Here in FacebookAPIAppDelegate we have just declared _session variable of type FBSession to keep track of the session and to check if session for current user exists or not.
Append Following code in FacebookAPIViewController.h

03#import "FBConnect/FBConnect.h"
04#import "FBConnect/FBSession.h"
06@interface FacebookAPIViewController : UIViewController   {
07             FBLoginButton *loginButton;
08             UIAlertView *facebookAlert;
09             FBSession *usersession;
10             NSString *username;
11             BOOL post;
14@property(nonatomic,retain) FBLoginButton *loginButton;
15@property(nonatomic,retain) UIAlertView *facebookAlert;
16@property(nonatomic,retain)  FBSession *usersession;
17@property(nonatomic,retain) NSString *username;
18@property(nonatomic,assign) BOOL post;
20- (BOOL)textFieldShouldReturn:(UITextField *)textField;
Append Following code in FacebookAPIViewController.m

01#import "FacebookAPIViewController.h"
02#import "FacebookAPIAppDelegate.h"
04#define _APP_KEY @"Your API Key Goes here"
05#define _SECRET_KEY @"Your Secrete Key Goes here"
07@implementation FacebookAPIViewController
08@synthesize loginButton;
09@synthesize facebookAlert;
10@synthesize usersession;
11@synthesize username;
12@synthesize post;
14- (void)viewDidLoad {
15               FacebookAPIAppDelegate *appDelegate =
16                          (FacebookAPIAppDelegate *)   [[UIApplication
17                                            sharedApplication]delegate];
18                if (appDelegate._session == nil){
19                appDelegate._session = [FBSession
20                                   sessionForApplication:_APP_KEY
21                                   secret:_SECRET_KEY delegate:self];
22                 }
23                 if(self.loginButton == NULL)
24                 self.loginButton = [[[FBLoginButton alloc] init] autorelease];
25                 loginButton.frame = CGRectMake(0, 0, 100, 50);
26                 [self.view addSubview:loginButton];
28                 [super viewDidLoad];
31- (void)dealloc {
32               [username release];
33               [usersession release];
34               [loginButton release];
35               [super dealloc];
38- (void)session:(FBSession*)session didLogin:(FBUID)uid {
39                self.usersession =session;
40                NSLog(@"User with id %lld logged in.", uid);
41                [self getFacebookName];
44- (void)getFacebookName {
45         NSString* fql = [NSString stringWithFormat:
46         @"select uid,name from user where uid == %lld",
47                               self.usersession.uid];
48        NSDictionary* params =
49        [NSDictionary dictionaryWithObject:fql
50        forKey:@"query"];
51   [[FBRequest requestWithDelegate:self]
52  call:@"facebook.fql.query" params:params];
56- (void)request:(FBRequest*)request didLoad:(id)result {
57              if ([request.method isEqualToString:@"facebook.fql.query"]) {
58                          NSArray* users = result;
59                          NSDictionary* user = [users objectAtIndex:0];
60                          NSString* name = [user objectForKey:@"name"];
61                          self.username = name;
63                          if ( {
64                                     [self postToWall];
65                            = NO;
66                          }
67              }
70- (void)postToWall {
72               FBStreamDialog *dialog = [[[FBStreamDialog alloc] init]
73                                             autorelease];
74               dialog.userMessagePrompt = @"Enter your message:";
75               dialog.attachment = [NSString
76                    stringWithFormat:@"{\"name\":\"Facebook Connect for
77                    iPhone\",\"href\":\"
78                    connect.phptab=iphone\",\"caption\":\"Caption\",
79                    \"description\":\"Description\",\"media\":[{\"type\":
80                    \"image\",\"src\":\"
81                     5914/iphoneconnectbtn.jpg\",\"href\":
82                     \"
83                      tab=iphone/\"}],\"properties\":{\"another link\":
84                      {\"text\":\"Facebook home page\",\"href\":
85                      \"\"}}}"];
87               [dialog show];
91- (BOOL)textFieldShouldReturn:(UITextField *)textField
93                [textField resignFirstResponder];
94                return YES;
Define API key and Secret key with the keys you received while registering your app on facebook.

1#define _APP_KEY @"43e37a535cc09c2013bd76fde78dfcc7"
2#define _SECRET_KEY @"cc14801521a0c4d1dc31b7cacb891072"
Validate session variable in ViewDidLoad. If it doesn’t exist then create the same for using API key and Secret key. For that, one needs to conform the protocol FBSessionDelegate in respective header file. Also create a login button using FBLoginButton.
While implementing protocol FBSessionDelegate one needs to implement following mandatory method

1(void)session:(FBSession*)session didLogin:(FBUID)uid
This methos is automatically called when user is logged in using FBConnect SDK.
In this method we get session for that user and it’s uid which unique identifier for that user.
Once FBSession session is avaiable, we can accesss all the APIs provided by Facebook.
For now, we will see how to post user name and status on the facebook wall.
To get Facebook username a request is send in which select query is written to get username using uid.

1NSString* fql = [NSString stringWithFormat:
2@"select uid,name from user where uid == %lld", self.usersession.uid];
3NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:@"query"];
4[[FBRequest requestWithDelegate:self] call:@"facebook.fql.query" params:params];
Override following FBRequestDelegate method to check the reponse of above query.

1(void)request:(FBRequest*)request didLoad:(id)result
The argument result is an array of NSDictionary Objects which contains info for that user as key-value pairs. Retrieve it as follows:

1NSArray* users = result;
2NSDictionary* user = [users objectAtIndex:0];
3NSString* name = [user objectForKey:@"name"];
Use FBStreamDialog class post message on the facbook wall. A dialog pops up with a message box to post on Wall.

1FBStreamDialog *dialog = [[[FBStreamDialog alloc] init] autorelease];
2dialog.userMessagePrompt = @"Enter your message:";
3dialog.attachment = [NSString stringWithFormat:@"{\"name\":\"Facebook Connect for iPhone\",\"href\":\"\",\"caption\":\"Caption\",\"description\":\"Description\",\"media\":[{\"type\":\"image\",\"src\":\"\",\"href\":\"\"}],\"properties\":{\"another link\":{\"text\":\"Facebook home page\",\"href\":\"\"}}}"];
4[dialog show];
Now Save project (Command +S). Build and Run Project.
Simulator will look like as follows

Click on Fconnect Button and Facebook Login Dialog will appear.

Login with your user name and Password . Wait for untill post to Wall Dialog pops up

You can download the source code from here

Tuesday, February 8, 2011

.NET Interview FAQs - 1

What are the different terms that are related to the life cycle of a Remoting object?

The related terms to the life cycle of a Remoting object are define as Lease Time, Sponsorship Time, RenewOnCallTime, and LeaseManagePollTime.

Lease Time: The LeaseTime property protects the object from the garbage collector. Every object created has a default leasetime for which it will be activated. Once the leasetime expires, the object is eligible again for garbage collector and is eventually destroyed. Default value is 5 minutes.
Sponsorship Time: Even though the leasetime of an object has expired, there still may be clients who would still need the remoting object on the server. In such cases the leasemanager keeps a track of such clients and asks them if they need the object and are ready to sponsor the object to extend its existence. This is done through SponsorshipTime property.
RenewOnCallTime: The RenewOnCallTime property defines the duration for which a remoting object's lease is extended if a sponsor is found. The default value is 2 minutes.
LeaseManagePollTime: The LeaseManager class has a property PollTime, which defines the frequency at which the LeaseManager polls the leases. Default is 10 seconds.

Explain the two different types of remote object creation mode in .NET?

The two different ways by which object can be created using Remoting is:-

SAO (Server Activated Object): It lasts the lifetime of the server. They are activated as SingleCall/Singleton objects. It makes objects stateless. A SingleCall object gets created for each request by client and A Singleton object is created once on the server and is shared by all the clients.

CAO (Client Activated Objects): CAO creates stateful objects. The object creation request is based on the request by client side. Therefore, the lifetime is based on client and not server. Single instance of object is created for every call.

What is the difference between URI and URL?

URI: (Uniform Resource Identifier)  
 It is a string and its responsibility is to identify a resource by meta-information. It gives information about only one resource. This is nothing but an address of some resource (page of a site) on the Web. URI is a generic term.

The World Wide Web can be considered as a large group of resources or contents placed in different computers all around the world. These contents can be found and can link each other through URIs.

Eg. A sample URI looks like :

•    /some/page.html

URL: (Uniform Resource Locator)
It identifies the resource on the net and tells it is obtainable using what protocols. This is a unique identifier which is usually a namespace. Even if it looks like a URL but it doesn’t have to necessarily locate any resource on the web. URL is a type of URI.

It can only identifies where and how to find it. A common URL is composed by four parts:
•    Protocol: Also called URL scheme, this specifies which protocol is used to access the document.
•    Computer name: Gives the name of the computer (usually a domain name or IP address) where the content is hosted.
•    Directories: Sequence of directories separated by slashes that define the path to follow to reach the document.
•    File: The name of the file where the resource is located.

Sample url looks like

•    http:/
Here, http is the protocol, is the domain name users is the folder name, login.aspx is the filename
Here http is the protocol, is the domain name, articles is the folder name and default.aspx is the file name

What is Fragment caching in

Fragment caching refers to the caching of individual user controls within a Web Form. Each user control can have independent cache durations and implementations of how the caching behavior is to be applied. It allows to cache specific portions of the page rather than the whole page.

The use of Fragment caching is to cache the subset of a page. The best examples for Fragment caching are navigation bars, headers, and footers etc.

Fragment cache is used to store user controls individually within a web form in cache instead of the whole webform.

<%@ OutputCache Duration="40" VaryByParam="none"%>

<%@ OutputCache Duration="60" VaryByParam="none"%>

Here the OutputCache duration is specified in seconds.

If control1 and control2 exist on a single webform together, the data of control1 and control2 would be cached for 40 and 60 seconds respectively based on @OutputCache directive. 

What are Partial classes in .net?

When there is a need to keep the business logic separate from the User Interface or when there is some class which is having multiple numbers of developers implement the methods in it, the class can be separated and written in different files called as partial class.

Below there is a sample class to know how to use partial class in case of C#
Public partial class MyPartialClass1
// this code could be in file1

Public partial class MyPartialClass1
// this code could be in file2

Partial classes allow us to divide the class definition into multiple files (physically). Logically, all the partial classes are treated as a single file by the compiler.

Differences between Window Services and Window Applications

Window Services:

1) They have no GUI (Graphical User Interface)

2) Used mainly for background processing or monitoring tasks.

3) They are found in the Services section of the Control Panel.

4)Installed using special utilities like InstallUtil.

5)They have startup types like Automatic, Manual


1) SMTP Service: used for sending emails across network

2)MSSQLServer Service: used for starting/stopping the SQL Server engine.

We can also create our own services and install them using InstallUtil.

Window Applications

1) They are GUI based.

2) Used for creating windows which can be run from their exe's stored a folder/desktop to enable the users to perform these kinds of tasks:

a)Data Entry(Ex: Inventory/Payroll management), Data viewing(view employee details)

b)Viewing hardware/software information of a system.

c) Games/ Graphics.

d)Customized calculators, Notepads, Explorers

3)They are not found in the Services section of Control Panel.

4)No startup types like Automatic/Manual.

We can start/stop Windows Service from a Windows Application .

Is it possible for a control to define a handler for an event, that the control can't itself raise?

Yes, It's is possible for a control to define a handler for an event, that the control can't itself raise.

These incidents are called attached events.

For example, a button controls in a grid. The button class defines a click event, but the grid class doest not. However, you can still define a handler for buttons in the grid by attaching the Click events of the button control.

Differences between method overloading and method overriding

Method Overloading and Method Overriding are both the techniques used to implement FUNCTIONAL POLYMORPHISM
They enhance the methods functionality using their respective features.

1) It involves having another method with the same name in a class or its derived class.

2)can be implemented with or without inheritance.

3)It is implemented by:

a)changing the number of parameters in different methods with same name.

b)changing the parameter data types (if the number of parameters are same)

c)changing parameter order.

4)applicable to static as well as non static methods:

5)no keywords needed before the method names in C#.

6)also called as COMPILE TIME Polymorphism.
example: int add(int a, int b)
return a+b;
int add(int a)
return a*5;


1) It involves having another method with the same name in a base class and derived class.

2)always needs inheritance.

3)It is implemented by having two methods with same name, same signature, but different implementations (coding)in a base class and derived class

4)applicable to nonstatic, nonprivate methods only.access modifiers of the methods are not changed in the base and derived classes.

5)virtual and override keywords are needed before the method names in base and derived classes.
For overriding in firther classes, override keyword will be used,

6)RUN TIME Polymorphism
class A
public virtual void demo()

class B:A
public override void demo()

static void Main()
B obj=new B();

Which namespace defines the collection classes?

Collection classes are defined by 2 namespaces


defines ArrayList, Stack, Queue


Defines the Generic Collections

example: List<>,Stack<>, Queue<>

What is the difference between User Settings and Application Settings in WPF?

The User Settings are Read/Write, they can be read or write even at runtime and can be saved.

The Application Settings are read-only, they can only be written at design time.

What is the use of yield keyword in C#?

Yield keyword is used in an iterator block to calculate the value for the enumerator object.

An iterator is a method,
get accessor, or operator that allows us to use foreach loop on object references of user-defined classes.

yield keyword can be used as:

1)yield return ;
2)yield break;

code snippet

using System;

//This namespace provides the IEnumerator interface

using System.Collections;

public class demo


//GetEnumerator method of IEnumerable interface creates the iterator

public IEnumerator GetEnumerator()


for (int i = 1; i <=5; i++)


yield return i;



static void Main()


demo t=new demo();

//foreach loop calls the GetEnumerator method

foreach (int i in t)








Found interesting?

Routed Events in WPF

Events are not a new part to know about if you are working in Microsoft Technologies, but now when WPF has introduce a new concept called as Rounted Events, we will look into the same.


 Download source code for Routed Events in WPF


The main thing we should take care in Routed Events is about control's hierarchy.  In WPF, a typical example of control's hierarchy is root level Window object, than Grid object and then the other controls which are resides on Grid Control.

The concept of Routed Events comes into the picture when we want to handle an event, that is originated from some other control in the hierarchy.  Say for example if any user clicks the Button control, that event which is normally a Button_click event, can be raised by The Button, The Label, The Gird or The Window.

Types of Routed Events :

  1. Direct Events
  2. Bubbling Events
  3. Tunneling Events

1.  Direct Events :

Direct Events are very well known to .NET people who has worked on standard .NET controls.  A direct event get raised by the control itself.  Say for example Button_click event which got raised by the Button control itself.

2.  Bubbling Events : 

Bubbling events are first raised by the control and then are raised by the controls in that control's hierarchy.  Taking our Button control example, If Button is clicked, first it will raise Button_click event, then the Grid event and at last the Window Event.

The below picture will clear all your doubts:


3.  Tunneling Events : 

The Tunneling Events are the opposite of the bubbling events as they are raised first by the root element in the hierarchy and then by the child elements.  Same as our previous example, First Window event will get raised, followed by the Grid Event and at last the Button_click event.


Let's take an example of the same to understand it better:

1.  Open Visual Studio 2010 (I have VS 2010, you may use 2010 or whichever the version you have)

2.  Create new WPF Application (I'm using VB.NET as the language)

3.  Add a simple Text Box to the designer window.

4.  Paste the below XAML Code to your Window:

5.  Paste the below VB.NET Code to your source code file.

Class MainWindow 

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
        MessageBox.Show("Event Raised By TextBox")

    End Sub

    Private Sub Grid_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
        MessageBox.Show("Event Raised By Grid")

    End Sub

    Private Sub Window_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
        MessageBox.Show("Event Raised By Window")

    End Sub
End Class
6.  Press F5 to run.

7.  Write something into the Text Box.

Thanks & Have Fun!!
There was an error in this gadget
Get Twitter Fan Box Widget

Like Us On Facebook and Receive All Updates!

You can also receive Free Email Updates:

Powered By Tutorails