Windows Mobile Support

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Wednesday, 25 April 2012

How to integrate Facebook in a Windows 8 Metro Style Application

Posted on 03:21 by Unknown

In ziua de azi aproape toate aplicatile pentru un consumator normal au nevoie de integrare cu Facebook. Chiar daca noua, dezvoltatorilor, ne place sau nu trebuie sa facem acest lucru.

Cand scriem o aplicatie Windows Metro Style trebuie sa luam cateva decizii legate de modul in care o sa ne integram cu Facebook.

O varianta pe care o avem la indemana este sa ne folosim de Windows 8 "Contracts". Desi in prima faza este destul de simplu, in cazul in care avem un flow mai complex, o sa ne dam seama ca nu ne este atat de usor sa facem acest lucru. Si asa ajungem la a doua varianta, care implica apeluri directe spre Facebook. Nu faceti greseala sa incepeti sa reinventati roata.

In primul rand avem niste librari ajutatoare in .NET, care ne ajuta sa facem toata partea de autentificare. Acest brower ne cere sa setam doar adresa de logare si url de redirectare. Toata magina care se intampla in spate pentru OAuth este rezolvata. .NET se ocupa se afisearea unui pop-up unde userul sa isi introduca credentialele and so on. Mai jos gasiti un exemplu de autentificare pentru o aplicatie Windows Metro Style:

 WebAuthenticationResult result =
await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
new Uri("loginUri"),
new Uri("redirectUri"));
Rezultatul returnat o sa contine o proprietate ResponseStatus, pe baza careia putem sa stim daca autentificare a fost cu success, userul a dat cancel sau a aparut o eroare in acest proces. Datele pe care serverul le returneaza precum auth. token pot sa fie gasite in result.ResponseData.

Exista deja o librarie pentru acest lucru oferita de catre Prabir. Aceasta este deja la versiunea a sasea. Din punctul meu de vedere este una din cele mai mature librarii pentru Facebook care exista in momentul de fata.

Ce mi-a placut cel mai mult la aceasta librarie este modul in care se executa o comanda. In loc sa aibe un API complex si greu de tinut la zi, iti permite sa setezi comanda (metoda) pe care vrei sa o apelezi si toti parametrii aferenti, iar apoi sa executi un GET sau POST prin intermediul clasei FacebookClient.

Primul pas este sa ne logam pe Facebook. Avem nevoie de url-ul pentru logare si de o modalitate de a extrage access token din rezultat. Acest lucru se poate face usor face ne folosim de FacebookClient. Aceasta clasa contine metoda GetLoginUrl, prin intermediul careia putem sa obtinem url pentru login, iar metoda ParseOAuthCallbackUrl parseaza ResponseData returnat de catre WebAuthenticationBroker a.i. sa putem accesa fara nici o problema toate datele:

FacebookClient fbClient = new FacebookClient();
fbClient.AppId = "1234";
WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
fbClient.GetLoginUrl(CreateLoginParameters()),
new Uri("https://www.facebook.com/connect/login_success.html));
Este bine de stiut ca AppId (application id) trebuie setat in cazul in care avem nevoie ca aplicatia noastra de Facebok sa poata accesa datele clientului.

Urmatorul pas este sa verificam care este statusu la result, daca acesta este in regula atunci putem sa extragem AccessToken. O sa avem nevoie de acesta cand o sa dorim sa executasm anumite actiuni.

if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
FacebookOAuthResult fbResult = fbClient.ParseOAuthCallbackUrl(new Uri(result.ResponseData));
accessToken = fbResult.AccessToken;
}
Prin intermediul comenzii GetTaskAsync putem sa executam orice metoda din API de Facebook. Rezultatul returnat este de tip dynamic. In exemplul de mai jos extragem toate datele unui user.
dynamic userInfo = await fbClient.GetTaskAsync("me");
Trace.WriteLine(userInfo.name);
Trace.WriteLine(userInfo.id);
In cazul unor comenzi mai complexe, este nevoie sa ne cream un obiect de tip ExpandoObject si sa setam toti parametrii pe care commanda ii cere. Avem si cateva objecte ajutatoare care ne ajuta sa comunicam cu Facebook. Unu din ele este FacebookMediaObject, prin intermediul caruia putem sa facem upload sau download la continut media. In exemplul de mai jos putem vedea cum putem sa facem upload la o poza pe Facebook.
byte[] imageBytes = null;
FacebookClient fbClient = new FacebookClient(accessToken);
dynamic fbParams = new ExpandoObject();
fbParams.access_token = accessToken;
fbParams.caption = "Romania";
fbParams.method = "facebook.photos.upload";
fbParams.uid = "12344314232342323";
FacebookMediaObject fbMediaObject = new FacebookMediaObject()
{
FileName = "MyRomaniaPicture",
ContentType = "image/jpg"
};
fbMediaObject.SetValue(await _mediaFileManipulator.GetBytes(imageBytes));
fbParams.source = fbMediaObject;
dynamic result = await fbClient.PostTaskAsync(fbParams);
Mi s-a parut destul de usor de folosit acest SDK pentru Facebook si va invit sa il incercati si voi.
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in windows 8 | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Service Bus Topic - Automatic forward messages from a subscription to a topic
    Windows Azure Service Bus Topic is a service that enables us to distribute the same messages to different consumers without having to know e...
  • Patterns in Windows Azure Service Bus - Message Splitter Pattern
    In one of my post about Service Bus Topics from Windows Azure I told you that I will write about a post that describe how we can design an a...
  • CDN is not the only solution to improve the page speed - Reverse Caching Proxy
    I heard more and more often think like this: “If your website is to slow, you should use a CDN.” Great, CDN is THE solution for any kind of ...
  • E-Learning Vendors Attempt to Morph Mobile
    The sign should read: " Don't touch! Wet Paint !" I had a good chuckle today after receiving my latest emailed copy of the eLe...
  • Content Types - Level 6: Rich Media
    Level 6: Rich Media NOTE: This is part 7 of 7 and the conclusion of this continuing series; please see earlier posts for more background inf...
  • Publishing our CellCast Widget for iPad
    The rush has been on this week as our development team worked to design a new version of our CellCast Widget specifically for Apple's up...
  • Content Types - Level 5: Courseware
    Level 5: Content and Courseware NOTE: This is part 6 of 7 in a continuing series; please see earlier posts for more background information. ...
  • SQL - UNION and UNION ALL
    I think that all of us used until now UNION in a SQLstatement. Using this operator we can combine the result of 2 queries. For example we wa...
  • Cum sa salvezi un stream direct intr-un fisier
    Cred ca este a 2-a oara când întâlnesc aceasta cerința in decurs de câteva săptămâni. Se da un stream și o locație unde trebuie salvat, se c...
  • Content Types - Level 4: Reference
    Level 4: Reference Materials & Static Content NOTE: This is part 5 of 7 in a continuing series; please see earlier posts for more backgr...

Categories

  • .NET
  • .NET nice to have
  • #if DEBUG
  • 15 iunie 2011
  • 15 octombrie 2011
  • 2011
  • abstracta
  • action
  • adaugare
  • ajax
  • Amsterdam
  • Android
  • aplicatii
  • App Fabric
  • Apple iSlate
  • array
  • as
  • ASP.NET
  • AsReadOnly
  • Assembly comun
  • async
  • Asynchronous programming
  • asyncron
  • Autofac
  • AutoMapper
  • az
  • Azure
  • Azure AppFabric Cache
  • Azure backup solution
  • Azure Storage Explorer
  • azure. cloud
  • backup
  • BCP utility
  • bing maps v7
  • BitArray
  • BlackBerry
  • blob
  • BlobContainerPublicAccessType
  • breakpoint
  • bucuresti
  • C#
  • cache
  • CallerMemberName
  • CellCast
  • Certificate
  • CES
  • change
  • ChannelFactory
  • clasa
  • classinitialize
  • clean code
  • click event
  • close
  • Cloud
  • Cluj
  • cluj-napoca
  • Code contracts
  • code retrat
  • codecamp
  • CollectionAssert
  • Compact Edition
  • compara
  • Comparer T .Default
  • CompareTo
  • comparison
  • comunitate
  • concurs
  • Conditional attribute
  • configurare
  • connection string
  • container
  • content type
  • control
  • Convert
  • convertAll
  • convertor
  • cross platform
  • CRUD
  • css
  • custom properties
  • custom request
  • DACPAC
  • Daniel Andres
  • data sync service
  • database
  • date time
  • datetime
  • debug
  • default
  • delegate
  • dependency injection
  • deploy
  • DeploymentItem
  • design patterns
  • Dev de Amsterdam
  • development stoage
  • dictionary
  • diferente
  • digging
  • director
  • Directory.Exist
  • disable
  • dispatcher
  • dispose
  • dropdown
  • dynamic
  • EF
  • email
  • encoding
  • entity framework
  • enum
  • enumerable
  • Environment.NewLine
  • error
  • error 404
  • error handling
  • eveniment
  • event
  • ews
  • excel
  • exception
  • exchange
  • exita
  • explicit
  • export
  • extension
  • field
  • File.Exist
  • finalize
  • fire and forget
  • Fluent interface pattern
  • format
  • func
  • GC.SuppressFinalize
  • generic
  • getdirectoryname
  • globalization
  • gmail
  • hackathon
  • Hadoop
  • handle
  • HTML
  • html 5
  • Html.ActionLink
  • http://www.blogger.com/img/blank.gif
  • HttpModule
  • IComparable
  • IE
  • ienumerable
  • IIS
  • image
  • implicit
  • import
  • int
  • internationalization
  • Internet Explorer
  • interop
  • Ioc
  • IP Filter
  • iPhone
  • iQuest
  • IStructuralEquatable
  • ITCamp
  • itspark
  • java script
  • javascript
  • July 2012
  • KeyedByTypeCollection
  • KeyNotFoundException
  • Kinect SDK
  • lambda expression
  • LightSwitch Microsoft Silverlight
  • linq
  • list
  • lista
  • lista servicii
  • liste
  • Live Connect
  • Live ID
  • load
  • localization
  • lock
  • m-learning
  • MAC
  • Mango
  • map
  • mapare
  • mapare propietati
  • messagequeue
  • meta properties
  • method
  • MethodImpl
  • Metro App
  • Microsoft
  • Microsoft Sync Framework
  • mlearning
  • mlearning devices
  • Mobile Apps
  • mobile in the cloud
  • mobile learning
  • mobile services
  • Mobile Web
  • mongoDb
  • monitorizare
  • msmq
  • multitasking
  • MVC
  • MVC 3
  • MVVM
  • namespace
  • nextpartitionkey
  • nextrowkey
  • Ninject
  • nivel acces
  • no result
  • normalize
  • nosql
  • null expcetion
  • null object pattern
  • NullReferenceException
  • OAuth API
  • office
  • offline
  • Open ID
  • openhackeu2011
  • operations
  • operator
  • optimization
  • option
  • outputcache
  • OutputCacheProvider
  • override
  • paginare
  • pagination
  • path
  • persistare
  • Portable Library tool
  • Post event – CodeCamp Cluj-Napoca
  • predicate
  • predictions
  • prezentare
  • process
  • proiect
  • property
  • propietati
  • query
  • ReadOnlyCollection
  • ReadOnlyDictionary
  • referinta
  • reflection
  • remote
  • reply command
  • request
  • request response
  • resouce
  • REST
  • REST Client
  • RESTSharp
  • ronua
  • rss
  • rulare
  • salvare in fisier
  • sc
  • schimbare timp
  • select
  • select nodes
  • send
  • serializare
  • serialization
  • Server.Transfer. Resposen.Redirect
  • service bus
  • ServiceBase
  • servicecontroller
  • sesiune
  • session
  • Session_End
  • Session_Start
  • setup
  • Sibiu
  • signalR
  • Silverlight
  • sincronizare
  • Single Responsibility Principle
  • SkyDrive
  • skype
  • smartphones
  • smtp
  • Snapguide
  • sniffer
  • socket
  • solid
  • spec#
  • sql
  • Sql Azure
  • SQL CE
  • sql server 2008 RC
  • SRP
  • startuptype
  • stateful
  • stateless
  • static
  • stergere
  • store
  • store procedure
  • stream
  • string
  • string.join
  • struct
  • StructuralEqualityComparer
  • submit
  • switch
  • Symbian
  • Synchronized
  • system
  • tabele
  • table
  • techEd 2012
  • tempdata
  • test
  • testcleanup
  • testinitialize
  • testmethod
  • thread
  • timer
  • ToLower
  • tool
  • tostring
  • Total Cost Calculator
  • trace ASP.NET
  • transcoding
  • tuplu
  • tutorial
  • TWmLearning
  • type
  • unit test
  • unittest
  • UrlParameter.Optional
  • Validate
  • validation
  • verificare
  • video
  • view
  • ViewBag
  • virtual
  • visual studio
  • VM role
  • Vunvulea Radu
  • wallpaper
  • WCF
  • WebBrower
  • WebRequest
  • where clause
  • Windows
  • windows 8
  • Windows Azure
  • Windows Azure Service Management CmdLets
  • windows live messenger
  • Windows Mobile
  • Windows Phone
  • windows service
  • windows store application
  • Windows Task
  • WinRT
  • word
  • workaround
  • XBox
  • xml
  • xmlns
  • XNA
  • xpath
  • YMesseger
  • Yonder
  • Zip

Blog Archive

  • ►  2013 (139)
    • ►  November (17)
    • ►  October (12)
    • ►  September (10)
    • ►  August (7)
    • ►  July (8)
    • ►  June (15)
    • ►  May (12)
    • ►  April (17)
    • ►  March (16)
    • ►  February (9)
    • ►  January (16)
  • ▼  2012 (251)
    • ►  December (9)
    • ►  November (19)
    • ►  October (26)
    • ►  September (13)
    • ►  August (35)
    • ►  July (28)
    • ►  June (27)
    • ►  May (24)
    • ▼  April (18)
      • Directory.GetFiles - odd result
      • WIndows 8 versions
      • How to integrate Facebook in a Windows 8 Metro Sty...
      • DataContract and XMLIgnore attribute
      • Cannot serialize member ... because it implements ...
      • Bug on Windows Phone 7 Exchange Client Automatic R...
      • Windows Azure Media Service - Overview
      • DB error not handled by the web application
      • ITCamp 2012
      • "This Week in mLearning" Podcast: Week #2
      • Background task in Windows 8 Metro Style App
      • URI in Windows 8 Metro Style App
      • How to read/write data from Windows Metro Style App
      • VS2011 BETA: Error : DEP3000 : Attempts to stop th...
      • Dependency Injection framework for WinRT - Widows ...
      • Manifest refereces file 'Bing.Maps.dll' which is n...
      • Luni 09.04.2012 - Emisiune live despre Windows Azure
      • New Podcast - "This Week in mLearning"
    • ►  March (17)
    • ►  February (20)
    • ►  January (15)
  • ►  2011 (127)
    • ►  December (11)
    • ►  November (20)
    • ►  October (8)
    • ►  September (8)
    • ►  August (8)
    • ►  July (10)
    • ►  June (5)
    • ►  May (8)
    • ►  April (9)
    • ►  March (14)
    • ►  February (20)
    • ►  January (6)
  • ►  2010 (26)
    • ►  December (1)
    • ►  November (1)
    • ►  October (1)
    • ►  June (2)
    • ►  May (1)
    • ►  April (4)
    • ►  March (1)
    • ►  February (1)
    • ►  January (14)
Powered by Blogger.

About Me

Unknown
View my complete profile