Facebook authentication from Windows Phone app ~$r!r@m

To start with Facebook in your Windows Phone  application, first of all you need to get the Facebook C# SDK I mentioned before. You can find it on the following links:

                               ithub – find the source code here

                               NuGet – get the library in your project from here

Once you have the SDK inside your app project, you need to understand what happens when you want your app to communicate with Facebook. First of all, you need to let Facebook know that you’ll be using their APIs. In other words, you need to register your app. You can register your app here:

https://developers.facebook.com/apps

by clicking on Create New App. The only compulsory field is App Name, and you’re done.

                                                                    image

After you’re done, you’ll get App ID/API Key and AppSecret. You’ll need those information later on to do stuff from your app, so I suggest you created the following classes in your project:

Code:

public class FacebookSettings
    {
        public static string AppID = "YOUR APPID"
        public static string AppSecret = "YOUR APPSECRET"
    }

public class FacebookAccess
    {
        public string AccessToken { get; set; }
        public string UserId { get; set; }
    }

FacebookSettings will hold the information about your app, and FacebookAccess will hold information about the user who authorized your app to access his or her Facebook.

Facebook authentication gives your app the ability to know the identity of a Facebook user who uses your app, and to do some stuff on his Facebook on his behalf. For example, you could post pictures on user’s Facebook without him explicitly going to the Facebook site and uploading it himself. According to the Facebook API documentation, a successful authentication flow results in your application obtaining a user access token which can then be used to make requests to Facebook’s APIs. After the successful authentication, you will want to save the obtained token to IsolatedStorage to be able to reuse it later, even after the user leaves your application. Therefor, you should use something like FacebookAccess class above and serialize it to IsolatedStorage for later use.

Let’s start by obtaining the token. After you added the Facebook C# SDK to your project, create a page with a Browser control on it.

Code:

<Grid x:Name="ContentPanel&quot; Grid.Row="1" Margin="12,0,12,0">
    <phone:WebBrowser Name="BrowserControl" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" IsScriptEnabled="True" Navigated="Browser_Navigated" Loaded="Browser_Loaded"/>
</Grid>

In the code behind, create the FacebookClient object and a string called ExtendedPermissions.

Code:

private const string ExtendedPermissions = "user_about_me,publish_stream";
private readonly FacebookClient _fb = new FacebookClient();

Facebook SDK enables you to ask for various permissions for you app depending on what it wants to do. You can find detailed information about permissions here:

https://developers.facebook.com/docs/authentication/permissions/

This app uses user_about_me and publish_stream. user_about_me means just basic information about the user, and that’s default. In order to be able to post photos to Facebook, you need to ask for publish_stream permission. The documentation says that it enables your app to post content, comments, and likes to a user’s stream and to the streams of the user’s friends. The next step is to get the log in URL for which you need to give Facebook C# SDK some parameters.

Code:

var parameters = new Dictionary<string, object>();

parameters["client_id"] = FacebookSettings.AppID;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "page";
parameters["scope"] = extendedPermissions;
BrowserControl.Navigate(_fb.GetLoginUrl(parameters));

GetLoginUrl method in FacebookClient class creates the login URL which you use for navigating in you BrowserControl added earlier. It takes parameters dictionary as a parameter. Dictionary contains string/object pairs.

  • “client_id” is your app ID
  • “redirect_uri” is where you navigate upon successful login
  • “response_type” is what you get back as a response – a token in this case
  • “display” defines how you display the login screen. Use page.
  • “scope” are permissions you’d like your app to ask for

And then you navigate your BrowserControl to that URL.

Do not use “touch” as “display” parameter. Many places online suggest you do that, because that opens the mobile version of Facebook for authentication. After you do that, you’ll get an error from Facebook saying that:

An error occurred with YOUR APP. Please try again later. API Error Code: 11 API Error Description: This method is deprecated Eror Message: Display=wap dialogs have been deprecated….

If you use “page”, everything works fine.

After that, the BrowserControl will open the Facebook site where the user will be expected to log in. Browser_Navigated event will be raised.

After login, you need to use FacebookOAuthResult object. It is created by parsing the URL using FacebookClient method TryParseOAuthCallbackUrl. If the parsing is not successful, you shouldn’t do anything, but if it is, get the AccessToken property.

Code:

private void Browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
	FacebookOAuthResult oauthResult;
	if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
	{
		return;
	}

	if (oauthResult.IsSuccess)
	{
		var accessToken = oauthResult.AccessToken;
		LoginSucceded(accessToken);
	}
	else
	{
		MessageBox.Show(oauthResult.ErrorDescription);
	}
}

If the parsing was successful, you now have the AccessToken. This token is needed for getting the UserID property, too. UserID is needed in some cases and for some URL constructs, so it’s worth getting that one, too. That’s what the LoginSucceded method is for.

Code:

private void LoginSucceded(string accessToken)
{
    var fb = new FacebookClient(accessToken);

    fb.GetCompleted += (o, e) =>
    {
        if (e.Error != null)
        {
            Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message));
            return;
        }

        var result = (IDictionary<string, object>)e.GetResultData();
        var id = (string)result["id"];

        SerializeHelper.SaveSetting<FacebookAccess>("FacebookAccess", new FacebookAccess
        {
            AccessToken = accessToken,
            UserId = id
        });
    };

    fb.GetAsync("me?fields=id");
}

Create a new FacebookClient object with the token as a parameter and call the asynchronous GetAsync method with “me?fields=id” parameter. When the async call is completed, you handle the result and create the FacebookAccess object and serialize it using SaveSetting<T> generic method:

Code:

public static void SaveSetting<T>(string fileName, T dataToSave)
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        try
        {
            using (var stream = store.CreateFile(fileName))
            {
                var serializer = new DataContractSerializer(typeof(T));
                serializer.WriteObject(stream, dataToSave);
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
            return;
        }
    }
}

 

XAML controls comparison between Windows Phone 8 and Windows 8

Image

This topic compares and contrasts the XAML control set available for Windows Phone 8 and Windows 8. As we’ll see, the types of controls available for both are very similar, allowing you to plan and design your user interfaces using the same concepts.

XAML UI controls for Windows Phone 8 are defined in the System.Windows.Controls andMicrosoft.Phone.Controls namespaces. In this release, we’ve added the LongListSelector to the control set and made some other improvements. The UI controls for Windows Store apps built using XAML are defined in theWindows.UI.Xaml.Controls namespace. The set of controls for each platform overlap conceptually. The following diagram shows this overlap in terms of types of controls available on both platforms.

In the preceding diagram, you can see that the majority of controls you are familiar with, whether coming from Windows Phone or Windows Store app development, exist on both platforms. These are not binary compatible, but the XAML used to define each one on your user interface and the properties available on each control are very similar. For example, if you have a page in your phone app that has a TextBox and two Button controls, you can copy and paste the XAML that defines these into a page in your Windows Store app. The controls will render. Of course, in a real app you would style your controls to suit the device on which the user interface is shown. The purpose here is to demonstrate the similarity of most of the controls on each platform. There is divergence in the controls used to manage the navigation of views within your app. On Windows Phone 8, you use Panorama andPivot to create rich view navigation suitable for the phone’s form factor. Similarly, on Windows 8 you can use theGridView and FlipView controls to create rich views of data in your app that are suitable for a store app.

The following table shows the set of controls and whether they are available on Windows Phone 8 or Windows 8. Differences or other notes are called out in the notes section.

Windows 8 Windows Phone 8 Notes
AppBar ApplicationBar
Border Border
Button Button
Canvas Canvas
CatureElement Renders a stream from a capture device, such as a camera or webcam. On the phone, use aVideoBrush and a PhotoCamera or CaptureSource.
CheckBox CheckBox
ComboBox For Windows Phone, use the ListPicker control from the Windows Phone Toolkit.
ContentControl ContentControl
ContentPresenter ContentPresenter Represents a control with a single piece of content. Controls, such as Button, CheckBox, andScrollViewer, directly or indirectly inherit from this class. This is only used when you create your own custom controls, not when you’re using the design surface.
DrawingSurface Defines an area within which 3-D content can be composed and rendered.
DrawingSurfaceBackgroundGrid A control that allows you to draw Direct3D graphics onto the background of your app. UseSwapChainBackgroundPanel in Windows 8.
Ellipse Ellipse
FlipView Represents an items control that displays one item at a time, and enables “flip” behavior for traversing its collection of items.
Frame Frame Represents a content control that supports navigation. On Windows Phone, this class is only a base class for PhoneApplicationFrame.
Grid Grid
GridView Represents a control that displays a horizontal grid of data items.
HyperlinkButton HyperlinkButton
Image Image
ItemsControl ItemsControl Represents a control that can be used to present a collection of items.
ItemsPresenter ItemsPresenter Specifies where items are placed in a control, usually an ItemsControl.
ListBox ListBox ListBox is not present in the Visual Studio toolbox for Windows Phone 8 in order to encourage use ofLongListSelector instead. However, it is still supported and you can manually add ListBox to XAML or code.
ListView Represents a control that displays a vertical list of data items. On the phone, use LongListSelector.
LongListSelector Displays a list of selectable items with a mechanism for users to jump to a specific section of the list.
MediaElement MediaElement Represents an object that contains audio, video, or both.
MultiScaleImage Enables users to open a multi-resolution image, which can be zoomed in on and panned across.
Panorama Creates a panoramic view of items that can be panned side-to-side.
PanoramaItem Represents an item in a Panorama control.
PasswordBox PasswordBox
Pivot Provides a quick way to manage the navigation of views within an app. The control can be used as a navigation interface for filtering large sets or switching between views.
PivotItem The container for items in the Pivot control.
Popup Popup
ProgressBar ProgressBar
ProgressRing Represents a control that indicates that an operation is ongoing. The typical visual appearance is a ring-shaped “spinner” that cycles an animation as progress continues.
RadioButton RadioButton
Rectangle Rectangle
RepeatButton RepeatButton Represents a control that raises its Click event repeatedly until the click mode is released. It’s on the phone, but only used as a base type (in Primitives namespace).
RichEditBox Represents a rich text editing control that supports formatted text, hyperlinks, and other rich content.
RichTextBlock Represents a rich text display container that supports formatted text, hyperlinks, inline images, and other rich content. On Windows Phone, useRichTextBox.
RichTextBox Represents a rich text control that displays formatted text, hyperlinks, inline images, and other rich content. On Windows 8, use RichTextBlock.
RichTextBlockOverflow Represents a rich text display overflow container. This element cannot have direct content. The only purpose of RichTextBlockOverflow is to display text content that does not fit in the bounds of aRichTextBlock or another RichTextBlockOverflowelement.
ScrollBar ScrollBar
ScrollContentPresenter ScrollContentPresenter Displays the content of a ScrollViewer control.
ScrollViewer ScrollViewer
SemanticZoom A semantic zoom control.
Slider Slider
StackPanel StackPanel
TextBlock TextBlock
TextBox TextBox
ToggleButton ToggleButton Base class for controls that can switch states, such as CheckBox and RadioButton.
ToggleSwitch Represents a switch that can be toggled between two states. On Windows Phone, use the Togglecontrol available in the Windows Phone Toolkit.
ToolTip ToolTip Provides an informational window that appears as a result of moving the pointer over a control or sometimes when tabbing to a control using the keyboard. While this control exists on Windows Phone, it isn’t intended to be used from your code.
UserControl UserControl
VariableSizedWrapGrid Provides a grid-style layout panel where each tile/cell can be variable size based on content. In Windows Phone 8, consider using the WrapPanelavailable in the Windows Phone Toolkit.
ViewBox ViewBox Defines a content decorator that can stretch and scale a single child to fill the available space.
VirtualizingStackPanel VirtualizingStackPanel
WebView Provides a UI element that hosts HTML content within the app.
WebBrowser Allows HTML rendering and navigation functionality to be embedded in an app.
WrapGrid Positions child elements sequentially from left to right or top to bottom. When elements extend beyond the container edge, elements are positioned in the next row or column. In Windows Phone 8, consider using the WrapPanelavailable in the Windows Phone Toolkit.