Windowsストアアプリ入門 vol76:LINQ to Twitterで本格的につぶやく(その1.認証編)

水曜日 , 17, 10月 2012 Leave a comment

LINQ to Twitterの概要

 

 以前にWindowsストアアプリ入門 vol73:TwitterRtでお手軽につぶやくでTwitterRtを紹介しました。

 TwitterRtは機能が少ない分、ソースコードが読みやすくOAuthの仕組みが理解しやすいライブラリでした。

 

 今回はほぼ完成されたライブラリのLINQ to Twitterを紹介します。

 LINQ to Twitterは文字通りLINQを使ってTwitterのデータを扱うことができるライブラリです。

 こんな感じに・・・

 

            var timelineResponse =
                (from tweet in twitterCtx.Status
                 where tweet.Type == StatusType.Home
                 select tweet)
                .ToList();

            Tweets =
                (from tweet in timelineResponse
                 select new Tweet
                 {
                     Name = tweet.User.Name,
                     Text = tweet.Text,
                     ImageUrl = tweet.User.ProfileImageUrl
                 })
                .ToList();

 

 今回は認証までを紹介しようと思います。

 

導入

 

 まずはLINQ to TwitterページのDOWNLOADリンクからファイルをダウンロードします。

 

 

 ダウンロードしたファイルを解凍します。

 winrt45というフォルダにWindowsストアアプリケーション用のライブラリLinqToTwitterRT.dllが入っています。

 

 プロジェクトの参照を追加します。

 

 

 

XAMLコード

 

 今回はWebViewコントロールにTwitterの認証ページを表示し、PINコードを取得、PINコードを入力することで認証を行います。

 XAMLコードにはWebViewコントロールと、PINコード入力用の TextBox、そして認証用のボタンを配置します。

 

<Page
    x:Class="LinqToTwitterSample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:LinqToTwitterSample"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <WebView x:Name="webView" HorizontalAlignment="Left" Height="540" Margin="49,122,0,0" VerticalAlignment="Top" Width="790"/>
        <TextBox x:Name="pinText" HorizontalAlignment="Left" Margin="49,706,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="391"/>
        <Button x:Name="authButton" Content="認証" HorizontalAlignment="Left" Margin="460,700,0,0" VerticalAlignment="Top" Click="authButton_Click"/>

     <TextBlock HorizontalAlignment="Left" Margin="49,679,0,0" TextWrapping="Wrap" Text="2.PINを取得後テキストボックスに入力して認証ボタンを押してください" VerticalAlignment="Top"/>
        <TextBlock HorizontalAlignment="Left" Margin="49,90,0,0" TextWrapping="Wrap" Text="1.Twitterアカウントでログインしてください" VerticalAlignment="Top"/>

    </Grid>
</Page>

 

コードビハインド

 

 C#コードは以下、

 

using LinqToTwitter;
using LinqToTwitterSample.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// 空白ページのアイテム テンプレートについては、http://go.microsoft.com/fwlink/?LinkId=234238 を参照してください

namespace LinqToTwitterSample
{
    /// <summary>
    /// それ自体で使用できる空白ページまたはフレーム内に移動できる空白ページ。
    /// </summary>
    public sealed partial class MainPage : Page
    {
        PinAuthorizer auth;

        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// このページがフレームに表示されるときに呼び出されます。
        /// </summary>
        /// <param name="e">このページにどのように到達したかを説明するイベント データ。Parameter 
        /// プロパティは、通常、ページを構成するために使用します。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            auth = new PinAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = "{ConsumerKey}",
                    ConsumerSecret = "{ConsumerSecret}"
                },
                UseCompression = true,
                GoToTwitterAuthorization = async pageLink =>
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                        () => webView.Navigate(new Uri(pageLink, UriKind.Absolute)))
            };

            auth.BeginAuthorize(async resp =>
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    switch (resp.Status)
                    {
                        case TwitterErrorStatus.Success:

                            break;
                        case TwitterErrorStatus.RequestProcessingException:
                        case TwitterErrorStatus.TwitterApiError:
                            new MessageDialog(resp.Error.ToString(), resp.Message).ShowAsync();
                            break;
                    }
                }));
        }

        private void authButton_Click(object sender, RoutedEventArgs e)
        {
            auth.CompleteAuthorize(this.pinText.Text,
            completeResp => Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                switch (completeResp.Status)
                {
                    case TwitterErrorStatus.Success:
                        SuspensionManager.SessionState["Authorizer"] = auth;
                        new MessageDialog("認証成功").ShowAsync();
                        break;
                    case TwitterErrorStatus.RequestProcessingException:
                    case TwitterErrorStatus.TwitterApiError:
                        new MessageDialog(completeResp.Error.ToString(), completeResp.Message).ShowAsync();
                        break;
                }
            }));
        }
    }
}

 

 ConsumerKeyとConsumerSecretはTwitterの開発者ページにてアプリケーションを登録することで取得でるものを入力してください。

 

動作を確認する

 

  アプリケーションを起動するといきなり認証画面が表示されます。

 

 

 TwitterのログインIDとパスワードを入力するとPINが取得できます。

 

 

 

 取得したPINをテキストボックスに入力して認証ボタンをクリックします。

 認証に成功すればメッセージダイアログが表示されます。

 

 

 以上で認証まで完了しました。

 

 


Please give us your valuable comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください