Quickest way to integrate into existing .NET project?

Nov 12, 2009 at 9:57 PM

Hi,

I'm just trying to post a message to a wall.  I've already created the application in Facebook and included the DLLs in my project.

I want a user to be able to input text into a textbox and then press a button and have it go to the wall.  Very simple.  I DON'T want them to have to login.  Could someone outline the best way to go about this?

I thought it might be something like this, but I think it would require them to login?:

      _connectSession = New ConnectSession(ConfigurationManager.AppSettings.[Get]("Facebook_APIKey"), ConfigurationManager.AppSettings.[Get]("Facebook_Secret"))

        If _connectSession.IsConnected() Then
            _facebookAPI = New Api(_connectSession)
            _facebookAPI.Stream.Publish(txtMessage.Text, Nothing, Nothing, "xxxxxxxxxxxxx", xxxxxxxxxxxxx)
        End If


Thanks in advance!
Jason

Nov 13, 2009 at 3:14 AM

Same question here.

Thanks

Nov 13, 2009 at 5:19 PM

I have a solution that works, but I don't know if it is the most straightforward way.  I use fb.WinForms.Components.FacebookService to connect, once the initial login is made, I save the settings for sessionKey and sessionSecret and any transactions after that do not require any login (unless the settings are reset).  Basically, if the sessionKey and sessionSecret are set, my if statement would take me to create a DesktopSession which is a parameter to New fb.Rest.Api.

Hope this helps

Nov 13, 2009 at 5:28 PM

Sorry this is an ASP.NET web application.  Would I still use fb.WinForms?  Also, do you have any example code you could post?

Thanks,
Jason

Nov 13, 2009 at 6:12 PM

No, you can't use the Winforms.

So you are writing a FB app, not adding FB functionality to your app?

If you are writing a FB app, are you using iFrame or Canvas?

But wait - if you are writing a FB app, any FB user would have to be logged in to even get to your app, right?

 

 

 

 

Nov 13, 2009 at 6:18 PM

I'll try to answer your questions by describing in more detail exactly what I'm trying to do.

I have an "Events" module within a custom content management system I built for a client.  The "Events" module allows the client to post events to a calendar on their website.  I would simply like to post the event not only to the calendar on their website, but also to the Wall on their Facebook Fan page.  So I'm not allowing the general public to login.

I created a Facebook App that looks like:

API Key
xxxx...
Application Secret
yyyy...
Application ID
zzzz....
Contact Email
me@mydomain.com
Support Email
me@mydomain.com
Canvas Callback URL
http://localhost/wp/autoWallPost.aspx
Connect URL
http://localhost/wp/autoWallPost.aspx
Canvas URL
http://apps.facebook.com/myappname/
FBML/iframe
FBML
Developer Mode
Off
Application Type
Website

Does that all make sense?

Thanks,
Jason

Nov 13, 2009 at 8:34 PM

Yes, it does :)

I believe FB Fan pages cna also have an events calendar, so you migth consider creating an Event and not just a wall post.

I think you need to look into FB Connect for integrating authentication and pushing content from your external site to FB.

It seems complicated but it's not too bad, just relax and let it happen LOL

I'll try to find some sample code but it's from v2.0 is there a better new sample? Have you looked at the samples released with v3.0?  I haven't.

Nov 13, 2009 at 8:41 PM

Yes I've looked at all of the samples but can't find anything that does what I'm looking for.  It seems like everything requires a manual login and/or integration with the CanvasBase.  I just can't figure out how to stinking create a new session automatically through the .NET code-behind.

The following worked in v2.0, but the stream.publish had an issue that was fixed in 3.0 which is why I'm trying to move to 3.0:

 

 

    Dim _fbService As facebook.Components.FacebookService = AuthenticateMe()
    _fbService.API.stream.publish(txtMessage.Text, Nothing, Nothing, "177926580964", Nothing)

 

 

    ''' <summary> 
''' Returns the user's authentication token
''' </summary>
''' <returns></returns>
Private Function AuthenticateMe() As Facebook.Components.FacebookService
Dim _fbService As New facebook.Components.FacebookService()
_fbService.ApplicationKey = ConfigurationManager.AppSettings.[Get]("Facebook_APIKey")
_fbService.Secret = ConfigurationManager.AppSettings.[Get]("Facebook_Secret")
_fbService.IsDesktopApplication = False

Dim sessionKey As String = TryCast(Session("Facebook_session_key"), [String])

' When the user uses the Facebook login page, the redirect back
' here will have the auth_token in the query params
Dim authToken As String = Request.QueryString("auth_token")

' We have already established a session on behalf of this user
If Not [String].IsNullOrEmpty(sessionKey) Then
_fbService.SessionKey = sessionKey
_fbService.uid = DirectCast(Session("Facebook_userId"), Long)
' This will be executed when Facebook login redirects to our page
ElseIf Not [String].IsNullOrEmpty(authToken) Then
_fbService.CreateSession(authToken)
Session("Facebook_session_key") = _fbService.SessionKey
Session("Facebook_userId") = _fbService.uid
Session("Facebook_session_expires") = _fbService.SessionExpires
Else
' Need to login
Response.Redirect("http://www.Facebook.com/login.php?api_key=" + _fbService.ApplicationKey + "&v=1.0\")
End If
Return _fbService
End Function

I just need to migrate that to work with v3.0 I think.

 

Nov 13, 2009 at 8:54 PM
Edited Nov 13, 2009 at 9:11 PM

I do apologize as I have only tested desktop apps, but does the session secret need to be applied? It may just be DesktopSession applicable, but I thought I would throw that out there.

 

svc.Api.Auth.Session.SessionSecret

Nov 13, 2009 at 8:58 PM

I'm really not sure.  I'm just trying to post a simple wall update from my .NET application.  I don't even have to use the toolkit if it's easier.  Can I just post using a WebResponse?  Something like: http://api.facebook.com?apikey=[api]&function=publishFeed&feed=[myWallPost]

I've been pulling my hair out on what seems like a very straight forward and simple task.  I'm not trying to do much integration with Facebook other than be able to remotely post a wall update.

Thanks,
Jason

Nov 13, 2009 at 9:20 PM

Jason, you can do that, the toolkit wraps up a lot of the handshaking for you.

I think you still don;t understand the difference between a Canvas application, and I-Frame application, and a website that integrates with FB Connect.  (Hint - you are the third).

 

This is pretty stripped down, prolly won't compile, but this is ALL YOU NEED to establish a session with FBConnect (in V2.0)

 

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPageSmallHeader.master" AutoEventWireup="true" CodeFile="IIAdminExtComm.aspx.cs" Inherits="IIAdminExtComm" %>


<asp:Content ID="Content1" ContentPlaceHolderID="contentplaceholderMasterCoach" Runat="Server">
    
    <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>
    <script type="text/javascript">
        //<![CDATA[
        function fb_login() {
            FB_RequireFeatures(["Api"], function() {
                FB.Connect.requireSession(function(exception) {
                    __doPostBack('ctl00','facebooklogin');
                });
            });
        }; //]]> 
    </script>
    

            
                <div ><p>If the link  is visible, that means the facebook connection is down.  Click the Facebook login link if it is shown.</p></div>
                <div>
                    <a id="ctl00_hlFacebookLogin"  onclick="fb_login(); return false;" href="#">Login with facebook</a>
                    <fb:prompt-permission perms="publish_stream,offline_access,photo_upload,create_event">Setup Permissions</fb:prompt-permission>
                    <br />
                </div>
                

<script type="text/javascript">
    FB.init('<%=System.Web.Configuration.WebConfigurationManager.AppSettings["APIKey"] %>', 'xd_receiver.htm');   
</script>

</asp:Content>

---------------------------

This is xd_receiver.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>

    <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js"
        type="text/javascript"></script>

</body>
</html>
   
Hopefully that will lead you to some successful googling.  You need to look into FBConnect.

 

Try to get JUST THIS code running, and see what it does.  It will be a HUGE eye-opener when you do.  Then it gets easy :)

 

 

Nov 13, 2009 at 9:27 PM

I'm trying to get this code running now, but won't this require that someone manually logins?

Thanks,
Jason

Nov 16, 2009 at 3:41 PM

well, it depends.

this line below tells FB to render a "wizard" sortof that your user can click through to give your app the listed permissions.  Go to the developer wiki and read everything there about FB connect and FBML.

<fb:prompt-permission perms="publish_stream,offline_access,photo_upload,create_event">Setup Permissions</fb:prompt-permission>

these were just the permissions the app I was working on needed. Notice "offline access" is in the permissions list, this allows my app to do certain things without requiring explicit login every time.
Nov 16, 2009 at 4:16 PM

Ok, I got this to work:

function FB_test_perm(api_key, xd_receiver, permission, callback)
    {           
	    FB.Bootstrap.requireFeatures(["Connect"], function()
	    {	       
		    FB.init(api_key, xd_receiver);
		    
		     //FB.Connect.showPermissionDialog("offline_access", function(result){ 
            //callback function when users accepts extended permissions
            //alert("sweet!");
            //});
		    
		    FB.Connect.requireSession(function()
		    {		         
			    FB.Facebook.apiClient.users_hasAppPermission(permission, function(result)
			    {
				    if (result != 0)				       
				        var message = URLDecode(getQueryVariable("message"));
                        var attachment = {
                                    'name':URLDecode(getQueryVariable("title")),
                                    'href':'http://www.url.org/calendar/default.aspx',   
                                    'description':URLDecode(getQueryVariable("message")),
                                    'media':[{
                                        'type':'image',
                                        'src':'http://www.blu-shine.com/public/images/icons/cgi/web_calendar45.png',
                                        'href':'http://www.url.org/calendar'
                                    }]
                                    }
                        var action_links = [{'text':'Click to view details', 'href':'http://www.url.org/calendar'}]; 

                        var pub = FB.Connect.streamPublish(message, attachment, action_links, '177926580964', '', null, true);
                        //alert(pub);
                
					    return callback(true);

				    FB.Connect.showPermissionDialog(permission, function(result)
				    {
					    return callback(result == null ? false : (result.indexOf(permission) != -1));
				    }, true, null);
			    });
		    });
	    });
    }

     function FB_perm_result(value){
	   alert(value ? "granted" : "not granted");
}

FB_test_perm("[my api key]", "xd_receiver.htm", "publish_stream", FB_perm_result);

Basically, I can just run this page with a [title] and [message] querystring variables and it will post to the wall.  Perfect.  The one problem is, it prompts me to login using Connect.  I need to be able to automatically login using the same account every time since this will all be happening as an automatic process in my workflow.  Any ideas?

Thanks,
Jason

Nov 16, 2009 at 4:42 PM

in our app we had a page where a user configured their profile.  On that page was the fb:prompt-permission tag. 

On another page we posted sutff to their wall,

The permissions only need to be done once for each user, if they grant off-line access the they won;t need to login to post wall stories.

Nov 16, 2009 at 5:43 PM

Ok.  If I login with my Facebook account A using Facebook Connect,  and then while logged in, run this:

FB.Connect.showPermissionDialog("offline_access", function(result){ 
            alert("granted!");
 });

On that computer, anytime I open the browser it should automatically log me in as user A?  It's not doing that.  I granted the offline_access for account A but when I close the browser and re-open it and go back to the page it prompts me for a login.

I just need a way that I can call a URL like this and have it automatically login as user A: http://www.mywebsite.com/publishtofacebook.html?apikey=[myapikey]&title=My Wall Post Title&message=My message

Make sense?

Thanks,
Jason

Nov 18, 2009 at 10:31 AM

 

Get permanent SessionKey

(New Version of Facebook & FaceBook API)

 

Through the use of extended Permissions

http://wiki.developers.facebook.com/index.php/Extended_permissions

 

offline_access

This permission grants an application access to user data when the user is offline or doesn't have an active session. This permission can be obtained only through the fb:prompt-permission tag or the promptpermission attribute. Read more about session keys

.

Manual Method to get the Offline Session Key

Use the following URL with your API Key

http://www.facebook.com/login.php?api_key=YOURAPIKEY&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&req_perms=offline_access

  1. Register for the Facebook Developer App on your facebook profile.
  2. Create a new app Web App(By default) through your "Facebook Developer App". Change the Application Type to "Desktop App".
    Note down the API Key & Secret Key for you app.
  3. Authorize the app & authenticate the user and then get the permanent session_key.
    Authentication

 

http://wiki.developers.facebook.com/index.php/Authorizing_Applications

 

Authenticating a Facebook application from another web application is not a simple task.  The user needs to first be logged into Facebook, then authorize your application to interact with the user's Facebook profile. In addition, in order to allow the application to interact with Facebook without having to redirect the user to a login for each new session, you will need an infinite session. There are also multiple other 'extended permissions' that Facebook requires to be approved individually. It is up to the client application to deal with these requirements. Here is some sample code demonstrating various authentication processes.

 

First, let's assume that the user has not done anything with your application yet. To check this we could do something like this:

One time Authotrize the application to let it access the users profile info infinitely.

Use the following link to ask the user for  "Allow Constant Authorization."

http://www.facebook.com/login.php?api_key=f2f5482a73e9921f546b4f815fb5c9c1&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&req_perms=offline_access

*api_key is the key of your application, you save in step 2.

Enter the user name & password to authenticate the user.
Click allow to let the application access your profile info & other details.

Next Page will say "success"
Copy the response URL and extract the session_key from it.
It will be of the  form "e008547690df35df64243591-2335652".
Verify that after "-" in the session key is your user_id (2335652).

This link will take the user to a page that will first ask them to login, and then requests permission for you application to interface with their Facebook profile. Once that happens, Facebook will redirect back to your callbackurl. Once back on your callback page, you will need to capture the values that Facebook has sent back to you.

 

  1. Now use this session_key (permanent/infinite session_key) for further querying from your application.
    Before this, change the application type of your facebook app back to "Web" (from "Desktop").
  2. Usage
    Now my application has the following things
    1. api_key
    2. secret_key
    3. user_id (part of session_key)
    4. session_key (permanent)
    5. call_id & sig (timehash & md5 hash - generate from your app)


With the help of above 6 keys, your application can directly communicate with the user's facebook profile, and extract the desired info.

Eg.
To get the user (in context) profile info:

 

"http://api.facebook.com/restserver.php?method=fql.query&query=SELECT uid, first_name, last_name, name, pic_small, pic_big, pic, affiliations, profile_update_time, timezone, religion, birthday, sex, hometown_location, meeting_sex, meeting_for, relationship_status, significant_other_id, political, current_location, activities, interests, is_app_user, music, tv, movies, books, quotes, about_me, hs_info, education_history, work_history, notes_count, wall_count, status FROM user WHERE uid IN (656513258)&session_key=e008547690df35df64243591-2335652&api_key=e77f1c7e6b1fa2d4d8495622bac2881a&v=1.0&call_id=8cc2c22a82768a4&sig=21850d21ac086498bddf894ea4b289a5"


This is a simple HTTP Request which will give the HttpResponse in XML format.
Use the FaceBookDevelopment Kit todo this or create your own methods, for the same.

Remember, you dont need to show the login page to the user again ever (unless the user unauthorizes the application himself from his profile)

-Abhinav Bhandawat

abhinav11@gmail.com