Out of Browser (その2) Twitter につないでみる

OOBをTrusted Appで動かすとクロスドメインもいけるそうな。ってことで、いままでやとTwitterにはcliantaccesspolicy.xmlがおいてなかったので直接Silverlightからつなんかったんやけど、つないでみる。


まずは、Trusted Appで動かすように設定。Out of Browser(その1)で書いたように、プロジェクトのプロパティから設定します。


[Enable running application out of the browser]のチェックボックスの横にある、[Out-of-Browser Settings...]ボタンを押すと、ダイアログが表示されるので、下のほうにある[Require elevated trust when running outside the browser]にチェックをいれてOKボタンです。その他の項目はまた今度。



あとはOut of Browser(その1)で書いたように、インストールやらデバッグの設定をすれば準備は万端です。


Trusted Appにするとインストールのダイアログが変わるんですね。



さて、本題のTwitterへの接続です。コードは以下のような感じ。

string userId = "twitterのユーザーID";
string password = "twitterのパスワード";

//ClientHttpを使う
HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);  

WebClient client = new WebClient();

//UseDefaultCredentialsを明示的にfalseにしないとダメ
client.UseDefaultCredentials = false;

//Basic認証用にCredentialを設定
client.Credentials = new NetworkCredential(userId, password);

client.Encoding = Encoding.UTF8;
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);

//フォローしている人のつぶやき一覧を取得
client.DownloadStringAsync(new Uri("http://twitter.com/statuses/home_timeline.xml"));

ClientHttpを使うように設定して、UseDefaultCredentialsを明示的にfalseにするところを忘れないように。

受け取るコールバックは以下のような感じ。

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) {
  if (e.Error != null) {
    MessageBox.Show(e.ToString(), "エラーが発生しました。", MessageBoxButton.OK);
    return;
  }
  Tweets.ItemsSource = from s in XElement.Parse(e.Result).Descendants("status")
                       select new Status() {
                           Id = s.Element("id").Value,
                           Text = s.Element("text").Value,
                           ScreenName = s.Element("user").Element("screen_name").Value
                       };
}