Obtaining Permissions and SessionKey for Desktop app from Web

Dec 6, 2009 at 4:45 AM

I have created a simple desktop application that I want to use to post status updates for the users of my app. Here's the kicker though that I am having trouble figuring out, the desktop application runs as part of a batch process every night, in which I update the status of certain users.

I use the following code to accomplish this: (comes directly from the FDK samples)

        public FriendViewer()
            facebookService1.ApplicationKey = "2105d45e533ee78c9245d916c4cd8396";
            facebookService1.Secret = "c82a2fc780876de119f3176c5aea1111";
            facebookService1.SessionKey = "30432383bc49ddc0bb1a6093-12104657";

            facebookService1.IsDesktopApplication = true;


        private void TestService_Load(object sender, EventArgs e)
                if (!facebookService1.API.users.hasAppPermission(facebook.Types.Enums.Extended_Permissions.status_update))

                if (!facebookService1.API.users.hasAppPermission(facebook.Types.Enums.Extended_Permissions.offline_access))
                long uid = facebookService1.users.getLoggedInUser();

                facebook.Schema.user user = facebookService1.users.getInfo(uid);
                facebookService1.users.setStatus("Facebook Syndicator rules!");
                MessageBox.Show(String.Format("Status set for {0} {1}", user.first_name, user.last_name));

            catch (Exception ex)

My user's day to day activity is done a website front end. Since I dont have any user interaction in a nightly batch process, I cannot use the ConnectToFaceBook method on the FaceBookService to obtain a sessionKey for the user. Ideally I would like to prompt for authorization and extended permissions for my desktop app when a user logins into the web front end then save the sessionKey and uid in the database.

At night when my process runs, I would reference the sessionKey and uid in order and update the user's status.

I am finding myself fumbling between whether or not my app should be a web or desktop app. Having both a web and desktop app would be confusing to my users, because they would have to grant/manage permissions for both apps.

And I looking at this the wrong way? Any help would be greatly appreciated!

Dec 6, 2009 at 4:39 PM

My app does pretty much what you are describing.

When you say "Having both a web and desktop app would be confusing to my users, because they would have to grant/manage permissions for both apps." are you thinking the two components (web front end and batch updater) need to be setup as separate apps with Facebook?  They don't.  You can use the same api key for both.

One thing to be aware of is potentially running afoul of Facebook's policies around the user message "You must not pre-fill the user_message parameter or content sent via an extended permission (such as a status update or note), unless the user generated the content earlier in the workflow."  I avoid this by leaving the "message" blank, and posting an attachment with my application content.

Dec 7, 2009 at 12:04 AM

So I have the app configured as a desktop app. And have the IsDesktopApplication set to true, this code runs in the batch updater to perform the status updates. However, I need to set the session key and make sure that extended permissions are set so I can perform the update. I would like to get the session key from the database. In order to do that I would have to request permissions and store a session key in the database, so I can use the session key in the batch updater.

When I use the isDesktopApplication = false, from theA website I get an exception: Incorrect signature. I believe this is due to fact that the application is configured as a Desktop application and I am trying to invoke it from a website.

Any ideas about how to fix the signature error?

Also I have used the: 


<font size="4">



@"http://www.Facebook.com/login.php?api_key=" + fbService.ApplicationKey + @"&v=1.0";

The Canvas Callback Url gets called after the users authenicated via the above link. But my application is configured as a Desktop, so I am confused as what to do here. Why do I have to have a Canvas CallBack URL set here? Like I said above, I need to be able to request permissions and obtain a session key for a user from a website. Part of the reason why Im thinking I need to use two apps.

Patja, any you could email me some sample code as to how you did this? Doesnt need to compile or anything I just need to get a better idea of how to go about doing this.

Thanks for all your help so far!
Have a great day!

Dec 7, 2009 at 2:53 PM

I do it the other way around:  my app is defined as a web app, but I use a ConnectSession when in desktop/console app mode.  

My web app is an mvc app...here is some code from one of my controllers:


        [FacebookAuthorization(IsFbml = false)]
        public ActionResult Index()
            var api = this.GetApi();
            var userid = api.Session.UserId;
            var fbuser = api.Users.GetInfo();

I prompt for offline_access and other extended permissions using the new alpha javascript client library, and then save the user's session key in my database for later use.

Then in my console app that does batch updates I have code like:


                string APIKey = ConfigurationManager.AppSettings["API_Key"];
                string APISecret = ConfigurationManager.AppSettings["API_Secret"];
                Facebook.Session.ConnectSession connectsession = new Facebook.Session.ConnectSession(APIKey, APISecret);
                Facebook.Rest.Api api = new Facebook.Rest.Api(connectsession);
                CountdownDALDataContext dc = new CountdownDALDataContext();
                long KimpUID = long.Parse("100000004236821");
                long PatUID = long.Parse("566565738"); //527795277
                //var users = from u in dc.FacebookUsers where u.UserID == PatUID select u;
                var users = from u in dc.FacebookUsers where u.DueDate != null && u.AppRemoved == false select u;
                List<Factoid> factoids  = new List<Factoid>();
                factoids = (from f in dc.Factoids where f.Inactive == false select f).ToList();
                List<PregnancyBook> books = new List<PregnancyBook>();
                books = (from b in dc.PregnancyBooks where b.Inactive == false orderby dc.GetNewId() select b).ToList();
                numusers = users.Count();
                foreach (var user in users)
                        api.Session.SessionKey = null;
                        api.Session.UserId = user.UserID;
                        var response = api.Fql.Query(String.Format("SELECT first_name, last_name, locale from user where uid = {0}", user.UserID));


                string APIKey = ConfigurationManager.AppSettings["API_Key"];
                string APISecret = ConfigurationManager.AppSettings["API_Secret"];

                Facebook.Session.ConnectSession connectsession = new Facebook.Session.ConnectSession(APIKey, APISecret);
                Facebook.Rest.Api api = new Facebook.Rest.Api(connectsession);

                MyDataContext dc = new MyDataContext();
                var users = from u in dc.FacebookUsers select u;
                numusers = users.Count();
                foreach (var user in users)
                        api.Session.SessionKey = user.SessionKey;
api.Session.UserId = user.UserID; var response = api.Fql.Query(String.Format("SELECT first_name, last_name, locale from user where uid = {0}", user.UserID));





Dec 7, 2009 at 3:38 PM


That makes sense! I am going to give it a whirl and let you know.

My Web app is also mvc as well! Definitely dont miss the Webforms world, not to mention the PageLifeCycle (what a mess)

Thanks so much for your time.
I really appreciate it!

Dec 7, 2009 at 11:36 PM

In the batch code the SessionKey is not set, so I am having some issues with that. Im assuming because you are using a ConnectSession you are Facebook Connect to create from the website?

I have a session key that doesnt expire and Im trying to get this to work, but am still having trouble.

Thanks for your help!

Dec 8, 2009 at 12:28 AM

just re-read what I posted, =P. I have a valid session and when I try execute GetLoggedInUser and I get an exception: Session key invalid or no longer valid?



Dec 8, 2009 at 2:12 AM

So in your batch process you are setting the "infinite" session key that you saved from your web app, and then calling getloggedinuser()?  

Getloggedinuser() just gives you a userid.  Why don't you save the userid to your database when you get the user's sessionkey?  I would suspect GetLoggedInUser() is erroring out on you because nobody is really logged in.  Using a infinite session key doesn't mean you are logging the user in, it means your app has permission to perform some specific and narrowly defined actions on their behalf when they are not logged in.

In my MVC web app I am just using this.GetApi(), which comes from the Facebook.Web.Mvc contoller extension and gets a session of type FBMLCanvasSession.  I haven't run into any issue with the fact I am using a FBMLCanvasSession on my web app and a ConnectSession on my batch console app.  I suspect they are both just using the Facebook REST api under the covers of the FDT so they would be the same from a Facebook receiving perspective (just an assumption).

Mar 9, 2010 at 7:35 PM

Doing something very similar to what you guys, and have run into a bit of trouble and wondering if you had similar issues and could offer any guidance.

I'm requesting offline permission through the FBJS library (old library - word alpha scares me), and then acquiring the infinite session key on the server side with the FDT library and storing it in the database.

Now I can create a new valid session on the server side using that infinite session key, but if I want to do the same on the JavaScript side I just can't seem to make it work. I'm not sure if the right way to go about doing this is to be setting some specific cookies on the client side, or if it means I should be initializing the JS library somehow with the infinite session key of my logged in user.  I've also heard mention of something called a session secret session key, which I think may be part of the solution, but just can't make the parts fit together.

Any help would be hugely appreciated, as I've pretty much hit a wall with this, and am faced with relegating all of my FB requests through the server.