Skip to main content

How to integrate Facebook in a Windows 8 Metro Style Application

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.

Comments

  1. Interesant - ai gasit undeva explicatia de ce au folosit.. dynamic?

    ReplyDelete
    Replies
    1. Folosind dynamic se poate parsa orice rezultat sau se poate forma orice request.
      Comunicarea cu FB se face in format JSON.
      Prin acest mod s-a eliminat nevoie de a folosii dictionare sau sa ai clase definite cu modelul folosit pentru comunicare.

      Delete
  2. Normal ca se poate orice cu dynamic, dar dezavantajul e ca nu mai e strongly typed si eventualele erori se prind doar mai tarziu la executie sau deloc, nu mai exista intellisense, type safety, refactoring etc.. Singura justificare ar fi daca API-ul de Facebook e in asa hal de weird sau instabil de la o versiune la alta, ca au renuntat sa intretina niste clase pentru asta.

    Normal ca pentru cine implementeaza libary-ul e mult mai comod asa :) , la fel cum era pe vremea library-urilor in C, unde user-ul trebuia sa compuna tot felul de struct-uuri alambicate care erau in final doar un mare bag de parameters, ca si in cazul dynamic, care e doar sintactic sugar pentru niste property bags..

    Am gasit si "explicatia" lor de la http://blog.ntotten.com/2010/09/07/dynamic-objects-and-the-facebook-c-sdk/ - practic tot ce spun e "a fost prea greu pentru noi, asa ca lasam programatorul sa se chinuie cu structurile de date.." :)

    ReplyDelete
    Replies
    1. In cazul acesta, lucrand deja cu API de la Facebook, mi s-a parut destul de simplu. De obicei cand ne integram cu Facebook-ul cea mai mare problema era la autentificare.

      Delete

Post a Comment

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

What to do when you hit the throughput limits of Azure Storage (Blobs)

In this post we will talk about how we can detect when we hit a throughput limit of Azure Storage and what we can do in that moment. Context If we take a look on Scalability Targets of Azure Storage ( https://azure.microsoft.com/en-us/documentation/articles/storage-scalability-targets/ ) we will observe that the limits are prety high. But, based on our business logic we can end up at this limits. If you create a system that is hitted by a high number of device, you can hit easily the total number of requests rate that can be done on a Storage Account. This limits on Azure is 20.000 IOPS (entities or messages per second) where (and this is very important) the size of the request is 1KB. Normally, if you make a load tests where 20.000 clients will hit different blobs storages from the same Azure Storage Account, this limits can be reached. How we can detect this problem? From client, we can detect that this limits was reached based on the HTTP error code that is returned by HTTP