まぐらぼ

日々の雑記を書いています。

BING翻訳API

BINGの翻訳APIを使ってみました。(元ネタここ

◆前提、環境
OS : windows8.1
IDE : VS2013 expresss (VS2012のnugetだと「BING Translator Control」が表示されません)

1. WEB
AzureMarketPlaceアカウント作成 
MSアカウント等も必要かもしれません(私のPCは常時ログインしてる状態だったので)
f:id:o-maguro:20140319162244j:plain

2. Microsoft Translator の購入(無料)

月額0円のサービスを購入してください。クレジットカード情報は不要です。
f:id:o-maguro:20140319162242j:plain

3.アプリケーションの登録
[マイアカウント]-[開発者]-[登録]でアプリケーション情報の登録を行います。

クライアントID と名前を入力してください。後から編集OKです。
クライアントIDとClientSecret(顧客の秘密)は後で使用します。
リダイレクトWEBは入力必須です。今回は使用しないので適当なURLを使います。
https://datamarket.azure.com/account

f:id:o-maguro:20140319162240j:plain

コンポーネントの追加
VS2013で、[ツール]-[拡張機能と更新プログラム]より「BING Translator Control」を検索してインストールしてください。間のスペースは必要です。VS2012では表示されません。

◆プロジェクトの作成およびプロジェクト設定

[新しいプロジェクト]ダイアログ-[VisualC#]-[Windowsストア]-[新しいアプリケーション(XAML)]を
作成してください。

プロジェクト設定は、
[ソリューションエクスプローラー]-[参照設定]-(右クリック)->[参照の追加]から[Windows]-[拡張]-[Bing Transfer Control]にチェックを入れて下さい。
f:id:o-maguro:20140319162241j:plain
◆コード

MainPage.xaml

<Page
    x:Class="BINGTranslator1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:BINGTranslator1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:translator="using:Bing.Translator"
    mc:Ignorable="d">
   
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <translator:TranslatorControl x:Name="translatorControl" 
                                  ClientId="your id" 
                                  ClientSecret="please input you secret key" 
                                  />
        <Button Content="Button" HorizontalAlignment="Left" Margin="312,146,0,0" VerticalAlignment="Top" Click="Button_Click"/>
        <TextBlock x:Name="idTextBlock" HorizontalAlignment="Left" Margin="370,269,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Height="83" Width="230"/>
    </Grid>
</Page>


MainPage.cs
ButtonとTextBlockを配置してください。

テキストブロックのIDはidTextBlock にしてください。

async Task<string> test_translator() 
{
    var result = await translatorControl.TranslatorApi.TranslateAsync(
        "ja",           // Optional EmptyでもOK
        "en",           // Required
        "general",      // Optional Defaults is "general" .
        "こんにちは"    // Required
    );
    return result.TextTranslated;
}

async private void Button_Click(object sender, RoutedEventArgs e)
{
    string ret = await test_translator();
    if (ret != null)
    {
        idTextBlock.Text = ret;
    }
    else {
        idTextBlock.Text = "failed";
    }
}

◆おまけ:
言語コード一覧
http://msdn.microsoft.com/en-us/library/hh456380.aspx