Windows Phone - 使用Facebook SDK for .NET

Windows Phone - 使用Facebook SDK for .NET

剛好前陣子有學員詢問到我怎麼在Emulator的環境下,也可以與Facebook進行資料的交互。

關於這個問題,也許您會覺得那幹嘛不直接在Emulator登入Facebook帳號就好了呢!

必須說非常可惜,Emulator不支持直接透過「電子郵件+帳戶」進行帳號設定

那該怎麼解決這樣的問題呢?

(1) 使用RESTAPIs,透過自行開發OAuth驗證所需要的流程與Facebook進行交易;

(2) 透過Azure Mobile Service的身份證驗機制整合Facebook帳號權限;

(3) 學習「Facebook SDK for .NET」;

 

本篇將針對Facebook SDK for .NET中的功能加以說明。

 

Facebook SDK for .NET

    將與Facebook認證、交易與操作的APIs,包裝成一個完整的SDK。支持Windows 8、Windows Phone與Web

然而App要操作Facebook中的功能,需要做驗證後,其User experiense如下圖所示:

image

透過Facebook SDK即可以完成上述的經驗,即可以進行其他的操作。可參考以下二個連結連行資訊的取得:

Facebook SDK for .NET Reference

Facebook SDK for Windows 8 & Windows Phone Reference

 

本篇內容針對Windows Phone使用Facebook SDK加以說明。

Facebook SDK for Windows 8 & Windows Phone Reference

    以下先來了解一下該SDK提供了那些重要的類別,每一種類別針對不同的平台有不同的支援度,需要特別注意。

重要的類別如下:

類別 說明
DateTimeConvert Utilities to convert dates to and from unix time。
FacebookApiEventArgs Represents the Facebook api event args。
FacebookApiException Represent errors that occur while calling a Facebook API。
FacebookApiLimitException Represents errors that occur as a result of problems with the OAuth access token。
FacebookBatchParameter Represents a batch parameter for the creating batch requests。
FacebookClient Provides access to the Facbook Platform。
為Facebook SDK中最重要與Facebook互動的重要媒介,透過該類別可以與Facebook進行驗證、上傳狀態/圖像/影片,取得用戶資訊與記錄。
FacebookMediaObject Represents a media object such as a photo or video。
代表要media object,例如:圖像或影片。
FacebookMediaStream Represents a media stream such as a photo or a video。
用於搭配FacebookClient進行圖像、影片的上傳,先將圖像或影片轉換成media stream,再加以上傳至Facebook。
FacebookOAuthException Represents errors that occur as a result of problems with the OAuth access token。
用於進行FacebookOAuth驗證時,搭配例外事件取得的例外物件。
FacebookOAuthResult Represents the authentication result of Facebook。
用於進行FacebookOAuth驗證時,搭配事件取得的物件,可用於識別驗證結果。
FacebookUploadProgressChangedEventArgs Represents Facebook api upload progress changed event args。
可搭配上傳資訊時,進度狀態的改變。
HttpMethod Represents an HTTP request type,提供GET、POST、DELETE。
HttpWebRequestWrapper 覆寫原生http web request wrapper,提供FacebookClient進行交易使用。
HttpWebResponseWrapper 覆寫原生http web response,提供FacebookClient進行交易使用。
JsonArray Json Array。
JsonObject Json Object。
WebExceptionWrapper Wrapper for web exceptions。

 

另外,該SDK提供了Facebook.Client與Client.Controls二大namespace,提供了豐富的功能如下表:

‧Facebook.Client

類別 說明
FacebookDialog  
FacebookDialogPage An empty page that can be used on its own or navigated to within a Frame.
FacebookSession SesstionState
登入時狀態的改變順序:opening -> opened;
登出時狀態的改變順序:closed,如果登出失敗會收到closedLoginFailed;
FacebookSessionCacheProvider  
FacebookSessionClient  
FacebookSessionIsolatedStorageCacheProvider  
FacebookSessionRoamingSettingsCacheProvider  
FacebookWebDialog  
GraphLocation Provides a strongly-typed representation of a Facebook Location as defined by the Graph API.
GraphObject Base class for objects returned by the Facebook Graph API that provides access to its properties dynamically.
GraphPlace Provides a strongly-typed representation of a Facebook Place as defined by the Graph API.
GraphUser Provides a strongly-typed representation of a Facebook User as defined by the Graph API.
儲存登入Facebook後用戶的基本資訊。
‧Birthday             ‧Link
‧UserName          ‧Location
‧LastName           ‧MiddleName
‧FirstName          ‧ProfilePictureUrl
‧Id                      ‧Name
LoginPage 僅支援Windows Phone 8。

 

‧Client.Controls

類別 說明
Audience Identifies the default audience to use for sessions that post data to Facebook.
標識默認觀眾使用該資料張貼到Facebook會話。
AuthenticationErrorEventArgs Provides data for the AuthenticationError event.
BooleanToVisibilityConverter Translates boolean values to Visibility constants.
ColorLuminosityConverter Adjusts the color of a brush changing its luminosity by a given factor.
CropMode Specifies the cropping treatment of the profile picture.
DataItemRetrieveEventArgs Provides data for the DataItemRetrieved event.
DataReadyEventArgs Provides data for the LoadCompleted event.
FacebookSessionState Identifies the states of a Facebook session.
搭配SessionStateChangedEventArgs可識別目前登入Facebook的狀態。
‧Opening
‧Opened
‧OpenedTokenUpdated
‧Created
‧CreatedTokenLoaded
‧Closed
‧ClosedLoginFailed
FriendPicker Shows a user interface that can be used to select Facebook friends.
提供一個控件可列出用戶的Facebook朋友清單。
FriendPickerDisplayOrder Specifies whether to display the first or last name first.
指定在顯示要優先顯示first或last name。
FriendPickerGroupTemplateSelector 僅支援Windows Store。
FriendPickerSortOrder Specifies the order in which friends are listed in the friend picker.
指定在列出朋友清單時,要用first或last name來進行排序。
GroupTemplateSelector 僅支援Windows Store。
ImageSourceUriConverter Retrieves a BitmapImage object for the specified image source uri.
僅支援Windows Phone 8。
IsNullOrEmptyConverter Checks if a value is null or empty.
LoadFailedEventArgs Provides data for the LoadFailed event.
LocationCoordinate Represents the coordinates of a place.
用於呈現一個位置的座標資訊。
LoginButton Represents a button control that can log in or log out the user when clicked.
包裝好串聯Facebook提供在App中用戶可以登入/登出Facebook。
ParameterizedConverter Wraps a value converter allowing the converter parameters to be bound.
Picker Displays a list of selectable items with optional multi-selection.
PickerSelectionMode Specifies the selection mode of a Picker control.
PickerSelectionModeConveter Converts between PickerSelectionMode and ListViewSelectionMode values.
PlacePicker Shows a user interface that can be used to select Facebook places.
顯示目前可定位的清單,提供用戶發表於Facebook。
使用方式<PlacePicker Control>。
ProfilePicture Shows the profile picture for an object such as a user, place, or event.
用於顯示目前登入用戶的個人圖像物件。
ScaleConverter Scales a value by a given factor.
SessionStateChangedEventArgs Provides data for the SessionStateChanged event.
SizeToGridCellConverter Calculates the size of group templates used by the zoomed out view to arrange them evenly.
UserInfoChangedEventArgs Provides data for the UserInfoChanged event.
該事件需要特別注意,因為用戶的登出/入均會觸發該事件。

上述這些元件裡,幾個比較需要注意的已加上連結,例如:LoginButton、FriendPicker、ProfilePicture、FacebookSesstion…等。

 

 

了解該SDK提供了那些可用的元件後,往下便直接透過幾個步驟來體驗如何使用Facebook SDK吧。

步驟如下:

a. 申請Facebook Developer權限,建立專用於手機的應用程式,取得ApplicationID;

    a-1. 登入Facebook帳號,登記為Developer,點擊Apps進行管理應用程式;

           image

    a-2. 建立新的應用程式,輸入必要的資訊:

           image

           取得Applicatoin ID,並且加以記錄;

           image

 

 

b. 下載Facebook SDK for .NET,並加入新的專案;

    建立一個WP專案,利用NuGet(pacakge manager console)將Facebook SDK加入至專案中;

    image

    b-1. 輸入「Install-Package Facebook」:

           image

 

    b-2. 輸入「Install-Package Facebook.Client -pre」:

           image

 

 

c. 將Facebook.Client.Controls.LoginButton加入至畫面,並且設定對應的應用程式ApplicationID;

   c-1. 先定義xmlns:fb為載入Facebook.Controls的Assembly:

xmlns:fb="clr-namespace:Facebook.Client.Controls;assembly=Facebook.Client"

 

   c-2. 在MainPage.xaml加入LoginButton,設定步驟a-2. 取得的Application ID:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <Grid.RowDefinitions>
        <RowDefinition Height="10*" />
        <RowDefinition Height="90*" />
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0">
        <!-- LoginButton 用於登入Facebook,註冊相關事件 -->
        <fb:LoginButton 
        x:Name="fbLoginBtn"
        ApplicationId=""
        AuthenticationError="LoginButton_AuthenticationError" 
        SessionStateChanged="LoginButton_SessionStateChanged"                 
        UserInfoChanged="LoginButton_UserInfoChanged"         
        />
    </StackPanel>
    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="30*" />
            <ColumnDefinition Width="70*" />
        </Grid.ColumnDefinitions>
        <!-- 利用ProfilePicture放置用戶的圖像 -->
        <fb:ProfilePicture 
            Grid.Column="0"
            VerticalAlignment="Top"
            CropMode="Fill"
            ProfileId="{Binding CurrentSession.FacebookId, ElementName=fbLoginBtn}"
         />
        <StackPanel Grid.Column="1">
            <TextBlock x:Name="tblName" Margin="3" />
            <TextBlock x:Name="tblBirthday" Margin="3" />
        </StackPanel>
    </Grid>
</Grid>

   c-3. 註冊幾個必要的Event

private void LoginButton_AuthenticationError(object sender, Facebook.Client.Controls.AuthenticationErrorEventArgs e)
{
    Dispatcher.BeginInvoke(() =>
    {
        MessageBox.Show(e.Reason, "AuthenticationError", MessageBoxButton.OK);
    });
}
 
private void LoginButton_SessionStateChanged(object sender, Facebook.Client.Controls.SessionStateChangedEventArgs e)
{
    switch (e.SessionState)
    {
        case Facebook.Client.Controls.FacebookSessionState.Closed:
            break;
        case Facebook.Client.Controls.FacebookSessionState.ClosedLoginFailed:
            break;
        case Facebook.Client.Controls.FacebookSessionState.Created:
            break;
        case Facebook.Client.Controls.FacebookSessionState.CreatedTokenLoaded:
            break;
        case Facebook.Client.Controls.FacebookSessionState.Opened:
            break;
        case Facebook.Client.Controls.FacebookSessionState.OpenedTokenUpdated:
            break;
        case Facebook.Client.Controls.FacebookSessionState.Opening:
            break;
    }
}
 
private void LoginButton_UserInfoChanged(object sender, Facebook.Client.Controls.UserInfoChangedEventArgs e)
{
    //User資料改變,例如:登入、登出;
    GraphUser tUser = e.User;
    tblName.Text = tUser.FirstName;
    tblBirthday.Text = tUser.LastName;
}

 

 

d. 執行登入,並取得登入帳號的基本資訊;

    001000002

 

 

上述介紹了怎麼取得Facebook SDK協助開發人員登入Facebook並取得一個FacebookSession後,往下介紹幾個常用的任務。

但是在往下說明之前,如果您沒有使用過Facebook developer中的Graph API Explorer,可以先進入該網址:<Graph API Explorer>,

進一步了解發佈或取得資料前,需要先向Facebook要求對應的權限,才能進行使用,如下:

 

[提醒]

先置「Graph API Explorer」選擇目前使用的Facebook Application名稱,接著按下「取得存取代碼」,設定以下權限:

image

image

image

 

 

a. 發佈訊息至Facebook

private async void btnStatus_Click(object sender, RoutedEventArgs e)
{
    //取得目前可以發佈的token
    var facebookClient = new Facebook.FacebookClient(this.fbLoginBtn.CurrentSession.AccessToken);
    //建立要發送的參數
    var postParams = new
    {
        message = txtStatus.Text
    };
 
    try
    {
        //利用facebookClient.PostTaskAsync發送訊息至feed
        // /me/feed,為個人的狀態;
        dynamic fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", postParams);
 
        //取得執行結果,該result是json物件,但被Facebook SDK給包裝過了
        var result = (IDictionary<string, object>)fbPostTaskResult;
 
        Dispatcher.BeginInvoke(() =>
        {
            MessageBox.Show("Posted Open Graph Action, id: " +
                            (string)result["id"], "Result", MessageBoxButton.OK);
        });
    }
    catch (Exception ex)
    {
        Dispatcher.BeginInvoke(() =>
        {
            MessageBox.Show("Exception during post: " + ex.Message, "Error", MessageBoxButton.OK);
        });
    }
}

    裡面有幾個重點:

    (1) 要求Permissions:

          根據Facebook文件上的介紹:「Permissions are what you ask for when a person authorizes through Facebook Login.

          Facebook implements a wide set of permissions that range from basic,

          which lets you access someone's public profile and friend list,

          to extended permissions, which let you publish actions to a the person's Open Graph (and their timeline by effect.)

          We'll cover a couple of the permissions here, but there are a large number of permissions you can ask for,

          including manage_pages and publish_actions.」

          本篇使用了「extended permissions」(publish-stream)方式,藉由詢問是否提供發佈的方式來進行發送狀態。

          

    (2) 發佈的物件:

          可參考<Feed and Share Dialogs>得知,發佈訊息的物件裡具有以下的參數:

          ‧link:The link attached to this post.

          ‧picture:The URL of a picture attached to this post. The picture must be at least 200px by 200px.

                           See our documentation on maximizing distribution for media content for more information on sizes

          ‧name:The name of the link attachment.

          ‧caption:The caption of the link (appears beneath the link name).

                            if not specified, this field is automatically populated with the URL of the link.

          ‧description:The description of the link (appears beneath the link caption).

                                 If not specified, this field is automatically populated by information scraped from the link,

                                 typically the title of the page.

          ‧source:The URL of a media file (either SWF or MP3) attached to this post.

                           If SWF, you must also specify picture to provide a thumbnail for the video.

 

    (3) 發佈的Path:/me/feed;

         代表發佈於用戶自己的動態時報(feed)之中。該Path要怎麼去找到其他的部分呢?可以參考<Getting Started: The Graph API>、

         或是<Publish a Post - Quickstart for Graph API>、<Graph API: User >有更詳細說明。

 

 

b. 發佈具有連結的訊息

private async void btnLink_Click(object sender, RoutedEventArgs e)
{            
    //要求可以發佈的權限 publish_stream
    await this.fbLoginBtn.RequestNewPermissions("publish_stream");
    //取得目前可以發佈的token
    var facebookClient = new Facebook.FacebookClient(this.fbLoginBtn.CurrentSession.AccessToken);
    //建立要發送的參數
    var postParams = new
    {
        name = "Facebook SDK for .NET",
        caption = "Build great social apps and get more installs.",
        description = "The Facebook SDK for .NET makes it easier and faster to develop Facebook integrated .NET apps.",
        link = "http://facebooksdk.net/",
        //200x200
        picture = "http://facebooksdk.net/assets/img/logo75x75.png"
    };
    
    try
    {
        //利用facebookClient.PostTaskAsync發送訊息至feed
        // /me/feed,為個人的狀態;
        dynamic fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", postParams);
 
        //取得執行結果,該result是json物件,但被Facebook SDK給包裝過了
        var result = (IDictionary<string, object>)fbPostTaskResult;
 
        Dispatcher.BeginInvoke(() =>
        {
            MessageBox.Show("Posted Open Graph Action, id: " + 
                            (string)result["id"], "Result", MessageBoxButton.OK);
        });
    }
    catch (Exception ex)
    {
        Dispatcher.BeginInvoke(() =>
        {
            MessageBox.Show("Exception during post: " + ex.Message, "Error", MessageBoxButton.OK);
        });
    }
}

 

 

c. 上傳圖像至Facebook

private void btnPostPhoto_Click(object sender, RoutedEventArgs e)
{
    //提供用戶選擇需要的圖像
    Microsoft.Phone.Tasks.PhotoChooserTask tTask = 
                new Microsoft.Phone.Tasks.PhotoChooserTask();
    tTask.Completed += tTask_Completed;
    tTask.Show();
}
 
private async void tTask_Completed(object sender, Microsoft.Phone.Tasks.PhotoResult e)
{
    if (e.Error != null)
    {
        MessageBox.Show(e.Error.Message, "Error", MessageBoxButton.OK);
        return;
    }
    try
    {
        //要求可以發佈的權限 publish_stream
        await this.fbLoginBtn.RequestNewPermissions("publish_stream");
        //取得目前可以發佈的token
        var fb = new Facebook.FacebookClient(this.fbLoginBtn.CurrentSession.AccessToken);
 
        //建立FacebookMediaStream
        var tFile = new Facebook.FacebookMediaStream();
        tFile.ContentType = "image/jpeg";
        tFile.FileName = Path.GetFileName(e.OriginalFileName);
        tFile.SetValue(e.ChosenPhoto);
 
        //執行發佈圖像至我的照片:/me/photos/
        dynamic fbPostTaskResult = fb.PostTaskAsync("me/photos",
            new { message = "upload using Facebook SDK for .NET", tFile });
 
        Dispatcher.BeginInvoke(() =>
        {
            MessageBox.Show("Posted Open Graph Action, id: " +
                fbPostTaskResult.Id + ", Status: "+
                fbPostTaskResult.Status, "Result", MessageBoxButton.OK);
        });
    }
    catch (Exception ex)
    {
        Dispatcher.BeginInvoke(() =>
        {
            MessageBox.Show("Exception during post: " + 
                ex.Message, "Error", MessageBoxButton.OK);
        });
    }
}

     關鍵技術在於了解怎麼發佈至需要GraphPath與使用FacebookMediaStream類別,最後再處理回傳的物件結果。

 

 

d. 打卡至Facebook

    這個範例搭配PlacePicker來完成,非常的方便,僅需要保持登入後的CurrentSession,即可以搭配取得的Accesstoken擷取Place Data,

另外,更會介紹搭配設定目前所在的Location來取得附近的內容。以下範例以<PlacePicker Control>介紹的內容為主,加以補充相關技術說明。

 

[提醒] 由於打卡需要用到Location的資訊,記得開啟該 ID_CAP_LOCATION

 

d-1. 列出目前所在座標的Place清單,並且搭配Search功能;

       d-1-1. 設計XAML畫面:

                 大量使用Data Binding的方式,由PlacePicker物件取得相關的資料內容,例如:座標資訊、地點詳細資料、與目前交差距離…等。

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
 
    <fb:PlacePicker 
        x:Name="placePicker"
        SelectionMode="Single"
        LoadFailed="placePicker_LoadFailed" />
 
    <Grid Grid.Row="1" Margin="2">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="2*" />
            <ColumnDefinition Width="2*" />
            <ColumnDefinition Width="1*" />
        </Grid.ColumnDefinitions>
        <!-- 定義用戶選擇後,該位置的詳細資訊 -->
        <TextBlock 
            Grid.Row="3" Grid.Column="0"
            HorizontalAlignment="Right" 
            VerticalAlignment="Top"
            TextWrapping="Wrap" 
            TextAlignment="Left"
            FontSize="16"
            Text="Your selection:" />
        <StackPanel Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="2"
                    Margin="10,0,0,0" Orientation="Vertical">
            <TextBlock
                VerticalAlignment="Top"
                FontSize="16"
                Text="{Binding SelectedItem.Name, ElementName=placePicker}" />
            <TextBlock
                VerticalAlignment="Top"
                FontSize="16"
                Text="{Binding SelectedItem.Location.Street, ElementName=placePicker}" />
        </StackPanel>
        <Button Grid.Row="3" Grid.Column="3" Content="CI" Click="Button_Click" />
        <!-- 定義目前用戶所在的經緯度 -->
        <TextBlock 
            Grid.Row="0" Grid.Column="0" 
            HorizontalAlignment="Right" 
            VerticalAlignment="Center"
            FontSize="16"
            Text="Latitude:" />
        <TextBox 
            x:Name="latitude" 
            Grid.Row="0" Grid.Column="1" 
            Margin="0"
            FontSize="16"
            BorderThickness="0"
            HorizontalAlignment="Stretch" 
            VerticalAlignment="Center"
            Text="{Binding ElementName=placePicker, Path=Latitude, Mode=TwoWay}" />
        <TextBlock 
            Grid.Row="1" Grid.Column="0" 
            FontSize="16"
            HorizontalAlignment="Right" 
            VerticalAlignment="Center"
            Text="Longitude:" />
        <TextBox 
            x:Name="longitude" 
            Grid.Row="1" Grid.Column="1" 
            Margin="0"
            FontSize="16"
            BorderThickness="0"
            HorizontalAlignment="Stretch" 
            VerticalAlignment="Center"
            Text="{Binding ElementName=placePicker, Path=Longitude, Mode=TwoWay}" />
        <!-- 定義搜尋的距離(radius) -->
        <TextBlock
            Grid.Row="0" Grid.Column="2" 
            FontSize="16"
            HorizontalAlignment="Right" 
            VerticalAlignment="Center"
            Text="Radius:" />
        <TextBox 
            x:Name="radius" 
            Grid.Row="0" Grid.Column="3" 
            Margin="0"
            FontSize="16"
            BorderThickness="0"
            HorizontalAlignment="Stretch" 
            VerticalAlignment="Center"
            Text="{Binding ElementName=placePicker, Path=RadiusInMeters, Mode=TwoWay}" />
        <!-- location tracking -->
        <TextBlock                    
            Grid.Row="1" Grid.Column="2" 
            Margin="0"
            FontSize="16"
            HorizontalAlignment="Right" 
            VerticalAlignment="Center"
            TextWrapping="Wrap"
            Text="Track location:" />
        <CheckBox 
            x:Name="trackLocation" 
            Grid.Row="1" Grid.Column="3" 
            Margin="0,-20"
            HorizontalAlignment="Left"
            VerticalAlignment="Center"
            IsChecked="{Binding ElementName=placePicker, Path=TrackLocation, Mode=TwoWay}"/>
        <!-- search text -->
        <TextBlock 
            Grid.Row="2" Grid.Column="0" 
            FontSize="16"
            HorizontalAlignment="Right" 
            VerticalAlignment="Center"
            Text="Search for:" />
        <TextBox 
            x:Name="searchText" 
            Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3"
            Margin="0,0,-12,0"
            BorderThickness="0"
            FontSize="16"
            HorizontalAlignment="Stretch" 
            VerticalAlignment="Center"
            Text="{Binding ElementName=placePicker, Path=SearchText, Mode=TwoWay}" />
    </Grid>
</Grid>

 

      d-1-2. 定義載入的座標與註冊相關事件處理;

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    //給予CurrenSession讓PlacePicker可以正常取得Token向Facebook要資料;
    placePicker.AccessToken = MainPage.FBLoginBtn.CurrentSession.AccessToken;
    //給予初始化座標
    placePicker.Latitude = 25.0478;
    placePicker.Longitude = 121.5171;
}
 
private void placePicker_LoadFailed(object sender, Facebook.Client.Controls.LoadFailedEventArgs e)
{
    //載入失敗
    Dispatcher.BeginInvoke(() =>
    {
        MessageBox.Show(e.Description, e.Reason, MessageBoxButton.OK);
    });
}

 

d-2. 根據用戶選擇的地點,進行打卡的發佈:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    try
    {
        //要求可以發佈的權限 publish_stream
        //await MainPage.FBLoginBtn.RequestNewPermissions("publish_checkins");
        //取得目前可以發佈的token
        var fb = new Facebook.FacebookClient(MainPage.FBLoginBtn.CurrentSession.AccessToken);
 
        //取得定位資訊
        Facebook.Client.GraphPlace tPlace = placePicker.SelectedItem;
 
        //建立要發佈定位的方式
        var tPostParams = new
        {
            message = "Check in by Facebook SDK for .NET",
            place = tPlace.Id,
            coordinates = new Dictionary<string, string>
            {
                {"latitude",tPlace.Location.Latitude.ToString()},
                {"longitude",tPlace.Location.Longitude.ToString()}
            }
        };
 
        //執行發佈打卡至我的定位:/me/checkins/
        dynamic fbPostTaskResult = await fb.PostTaskAsync("/me/checkins",  tPostParams);
 
        Dispatcher.BeginInvoke(() =>
        {
            MessageBox.Show("Posted Open Graph Action, id: " +
                fbPostTaskResult.Id + ", Status: " +
                fbPostTaskResult.Status, "Result", MessageBoxButton.OK);
        });
    }
    catch (Exception ex)
    {
        Dispatcher.BeginInvoke(() =>
        {
            MessageBox.Show("Exception during post: " + 
                ex.Message, "Error", MessageBoxButton.OK);
        });
    }
}

       利用GraphPath為:/me/checkins,建立傳送的參數需注意place、coordinates中的latitude與longitude需來自PlacePicker所選擇的項目值。

 

[執行畫面]

004003

 

[範例程式]

======

以上是分享怎麼透過Facebook SDK for .NET讓自己的應用程式可以與Facebook加以整合。

有很多相關Facebook API中的功能沒有仔細談論到,這個部分可參考下方的Reference加以學習。

其中還有很多內容可以依自己實作的狀況進行調整,所以SDK真的包裝的非常厲害,可以馬下載範例來試用看看。

 

References

Making Synchronous Requests with the Facbeook C# SDK (重要)

Facebook Scrumptious tutorial for Windows Phone (非常重要)

Use Batch Requests

Making Synchronous Requests with the Facbeook C# SDK (重要)

Facebook Login with Single Sign On for Windows Store Apps

Facebook Client - Facebook SDK for .NET Reference

facebook-windows-phone-sample

FB.api & The Graph API

Facebook Query Language (FQL) Reference

Getting Started: The Graph API

How-To: Use the Graph API to Upload Photos to a user’s profile

Publish to Feed - Facebook SDK for .NET & Dialogs - Facebook SDK for .NET

Posting image from .NET to Facebook wall using the Graph API

How to check in or post user location on facebook wall in windows phone 8

facebook check in API (graph) 實作範例教學 & facebook 打卡 api 應用 (搭配google map)

Graph API: User (重要)

How to Check In into the Facebook.?

 

Dotblogs 的標籤: