Windows Azure Tips from Prospex

システム開発 × インフラ構築・運用 × グラフィックデザイン = プロスペックス

連絡ボックス、メインページの主な機能と表示

clock March 30, 2012 18:37 by author fujii

(1)ボックス

閲覧可能なボックスの一覧が表示されます。

各ボックスをクリックすることで、ボックスに投稿されたスレッドとメッセージが表示されます。

ボックスはユーザー毎に閲覧権限が設定されているので、ユーザー毎に表示されるボックスは異なります。

ボックスの後ろの数字は、未読のスレッド数です。

image

(2)ごみ箱

「ごみ箱」をクリックすると、削除したスレッドやメッセージが表示されます。

「ごみ箱」に表示された状態のスレッドやメッセージを「削除」すると、スレッドやメッセージは連絡ボックスから削除されます。

「ごみ箱」に表示された状態のスレッドやメッセージを「復元」すると、スレッドやメッセージは元のボックスに復元されます。

閲覧権限があれば、他のユーザーが削除したメッセージも表示されますが、権限が無い場合は「削除」や「復元」をすることはできません。

image

(3)検索フォーム

スレッドリストの絞り込みに使用します。

「件名/本文」は間にスペースを入れることで、複数のキーワードを指定することができます。

image

(4)スレッドリスト

各ボックスをクリックした時、選択したボックスにあるスレッドが表示されます。

各スレッドをクリックすることで、右側にメッセージを表示します。

投稿権限があるボックスを選択している場合は、上部に「新規投稿(スレッド作成)」が表示され、

押すことでスレッドを新規作成することができます。

左側の「封筒マーク」はスレッドの開封状態で、クリックすることで切り替えることができます。

image

(5)表示言語

メッセージの表示言語を選択します。

メッセージが投稿された言語(投稿言語)以外を選択すると、翻訳文があれば翻訳文が表示されます。

image

(6)削除ボタン(復元ボタン)

スレッドリストで選択したスレッドを削除します。

ごみ箱を選択しているときは、「削除」ボタンと「復元」ボタンが表示されます。

スレッドを削除する権限が無い場合は、押すことができません。

image

(7)スレッド情報

スレッドの情報が表示されます。

投稿権限があるボックスを選択している場合は、右下に「このスレッドに追加投稿(返信)」が表示され、押すことでスレッドにメッセージを追加することができます。

「更新時にメールで通知する」にチェックを入れると、スレッドが更新された時にメール通知を受け取ることができます。

「メールで通知に本文を掲載する」にチェックをすると、メール通知に本文を含めることができます。

image

(8)メッセージ

投稿したメッセージを表示されます。

本人が投稿したメッセージは編集や削除することができます。

image

(9)閲覧状態

スレッドリストで選択したスレッドを閲覧することができるユーザーの写真が表示されます。

メッセージを未開封にしているユーザーの写真は、暗く表示されます。

写真にマウスカーソルを重ねることで、ユーザーの名前を確認することができます。

スレッドに返信時にメール通知が届くユーザーには、ユーザーの名前の下に「メール通知する」と表示されます。

image



連絡ボックス、グループの作成方法

clock March 30, 2012 17:04 by author fujii

(1)「メインページ」で「管理画面」を押し、「グループ管理」を押してください。

image

(2)右上の「グループを追加する」を押し、グループを追加してください。

image

(3)追加したグループを選択し、右の「グループに追加するユーザーの設定」でグループに含めるユーザーを選択してください。

image

(4)「▼グループに所属しているユーザー」にユーザーを追加すれば、設定は完了です。

image



連絡ボックス、新規ユーザーの登録方法

clock March 30, 2012 14:33 by author fujii

 

(1)「管理画面」を押し、「ユーザー管理」の「新規ユーザー登録」を押してください。

image

(2)「新規ユーザー登録」の各項目に入力してください。

なお、「所属グループ」は「グループ管理」で設定したグループが表示されます。

(「所属グループ」を設定しておきますと、「アクセス権の付与」を簡単に行えます)

image

(3)「登録」ボタンを押すと、「メールアドレス」に入力したメールアドレスに、

「連絡ボックスから招待されました」というメールが送信されます。

(メール送信には少々時間がかかりますので、お待ちください)

メールには「アカウント(ログインID)」と「パスワード登録フォームのURL」が記載されています。

この段階ではユーザーは「仮登録」となりますので、必ず下記の手順を行ってください。

image

(4)メールを受信したユーザーが記載されているURLをクリックすると、

パスワード入力フォームが表示されますので、パスワードを入力してください。

image



連絡ボックス、ボックスの作成とメッセージの投稿方法

clock March 30, 2012 13:27 by author fujii

(1)ログインしたときに表示される「メインページ」の、右上の「管理画面」を押してください。

なお、「管理画面」は「管理者」のみ表示されます。

image

(2)「ボックス管理」を押して、「ボックスリスト」を表示してください。

image

(3)右上の「ボックスの追加」を押し、ボックスを追加してください。

image

(4)「ボックスリスト」で追加したボックス選択し、左側の「アクセス権」を押してください。

(5)「ボックスのアクセス権」の「▼グループ」または「▼ユーザー」でボックスに参加させるユーザーを選択し、

「▼付与する権限」にチェックを入れ、「▼追加」ボタンを押してください。

ボックスはアクセス権を付与しないユーザーには表示されませんので、

参加させるユーザーには必ずアクセス権を付与してください。

以上でボックスの追加は完了となります。

image

(6)画面右上の「メインページ」を押して、「メインページ」を表示してください。

画面左に「ボックス」が表示されていれば、ご使用可能です。

image

(7)画面左の「ボックス」を選択し、画面中央上の「新規投稿(スレッド作成)」を押し、

スレッドを作成してください。

image



舌の根も乾かぬうちにとは、まさにこの事である。

clock March 15, 2012 20:54 by author fujii

Windows Azure で開発をしている「連絡ボックス」ですが、実はベータ版(無料)のURLが変わりました。

https://www.renrakubox.com/regist/trial

行き違いで登録しようとしてくださった方には大変申し訳ございません!!

 

気軽に使用していただけるように、もっと簡単な登録フォームを作っちゃいました。

ものすごく簡単に登録(無料)できるので、登録(無料)だけでもいかがでしょうか。

本当に登録(無料)だけでもお願いします。

しつこいんですが、ベータ版は「無料」なんです。

 

(1)下記のページにアクセスしてください。

https://www.renrakubox.com/regist/trial

(2)「新規申込みサービス利用規約▼申込内容」で「その他(ベータ版)」を選択し、
「新規申込みサービス利用規約」にご同意の上、「規約に同意して次へ」ボタンを押してください。

なお、ベータ版は無料となりますので、「自動翻訳を利用する」の選択をお勧めします。

image

(3)「新規申込み利用者基本情報」画面の各項目にご入力の上、「次へ」ボタンを押してください。
image

(4)「新規申込み申込者情報」画面の各項目にご入力の上、「確認画面へ進む」ボタンを押してください。
(右上の「利用者基本情報からコピーする」ボタンを押しますと、前の画面の内容をコピーできます)

「メールアドレス」「ログインID」「パスワード」は、「連絡ボックス」で使用しますので、
必ずメモをとってください。

image

(5)「新規申込み確認」で内容をご確認の上、「申し込む」を押してください。

以上でベータ版のお申込みは完了となります。

image

image

(6)下記のページより「4.」で設定した「ログインID」「パスワード」でログインしていただければ、
ご使用いただけます。

https://www.renrakubox.com/

 

余分な二画面を減らしました!

 

肝心の「連絡ボックス」の使い方は……今度こそ説明します!

ここまで登録していただいた方には、度々大変申し訳ございません。



連絡ボックスβ版(無料)、ひっそりと公開中

clock March 12, 2012 21:39 by author fujii

Windows Azure で開発をしている「連絡ボックス」ですが、実はベータ版(無料)がひっそりと公開されています。

ひっそりと公開している場合ではないので、Azureブログに載せちゃいます。

とても簡単に登録(無料)できるので、登録(無料)だけでもいかがでしょうか。

しつこいんですが、ベータ版は「無料」なんです。

 

(1)下記のページにアクセスしてください。
https://www.renrakubox.com/regist/regist1

(2)「新規申込みサービス利用規約▼申込内容」で「その他(ベータ版)」を選択し、
「新規申込みサービス利用規約」にご同意の上、「規約に同意して次へ」ボタンを押してください。

なお、ベータ版は無料となりますので、「自動翻訳を利用する」の選択をお勧めします。

image 

(3)「新規申込み利用者基本情報」画面の各項目にご入力の上、「次へ」ボタンを押してください。

image

(4)「新規申込み申込者情報」画面の各項目にご入力の上、「次へ」ボタンを押してください。
(右上の「利用者基本情報からコピーする」ボタンを押しますと、前の画面の内容をコピーできます)

「メールアドレス」「ログインID」「パスワード」は、「連絡ボックス」で使用しますので、
必ずメモをとってください。

image

(5)大変お手数ですが「新規申込み請求書送付先」画面の各項目にご入力の上、「次へ」ボタンを押してください。

ベータ版は無料となりますので、請求書を送付することはございません。

image

(6)大変お手数ですが「新規申込み料金のお支払」画面の各項目にご入力の上、「確認画面へ進む」を押してください。
「支払形態」は「月極支払い」をご選択ください。

ベータ版は無料となりますので、お支払いは不要でございます。

image

(7)「新規申込み確認」で内容をご確認の上、「申し込む」を押してください。

以上でベータ版のお申込みは完了となります。

image

image

(8)下記のページより「4.」で設定した「ログインID」「パスワード」でログインしていただければ、
ご使用いただけます。

https://www.renrakubox.com/

 

肝心の「連絡ボックス」の使い方は……次回説明します!

ここまで登録していただいた方には大変申し訳ございません。



Microsoft Translator を使ってみました

clock January 31, 2012 21:30 by author fujii

「Microsoft Translator」を使ってみました。

詳細は下記のページです。

http://www.microsofttranslator.com/Tools/

image

上記のページから下記の「Windows Azure Marketplace」の「Microsoft Translator」のページにたどり着いたので、「¥0.00」の「2000 tx/month」を購入しました。

https://datamarket.azure.com/dataset/1899a118-d202-492c-aa16-ba21c33c06cb

image

下記のページに使用法があったので、使ってみました。

http://msdn.microsoft.com/en-us/library/hh454950.aspx

コンソールアプリケーションを作成し、SOAP web service を追加。

http://api.microsofttranslator.com/V2/Soap.svc

Oimage

image

「Access Token」を取得し、メソッドを並べてみました。

using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Web;
using System.Data;
using System.Linq;
 
namespace TranslationTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string uri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
            string clientId = "??????????";         //get it from https://datamarket.azure.com/developer/applications
            string clientSecret = "??????????";  //get it from https://datamarket.azure.com/developer/applications
            string headerValue = "";
            string request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", clientId, HttpUtility.UrlEncode(clientSecret));
 
            // Get an Access Token
            try
            {
                MTAccessToken mtToken = HttpPost(uri, request);
 
                // Create a header with only the access_token property of the returned token
                headerValue = "Bearer " + mtToken.access_token;
                Console.WriteLine(headerValue + "\r\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine( ex.Message);
            }
 
            // Use the Access Token in a Translate() call
            try
            {
                // Add the http header
                HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                httpRequestProperty.Method = "POST";
                httpRequestProperty.Headers.Add("Authorization", headerValue);
 
                // Call Translator with the header
                using (MTService.LanguageServiceClient myClient = new MTService.LanguageServiceClient())
                {
                    using (OperationContextScope scope = new OperationContextScope(myClient.InnerChannel))
                    {
                        OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
                        
                        // AddTranslation Test(辞書に単語や文章を追加します)
                        Console.WriteLine("AddTranslation Test:Press Enter");
                        Console.ReadLine();
                        
                        myClient.AddTranslation("","translate","übersetzen","en","de",1,"text/plain","general","username",null);
                        myClient.AddTranslation("", "prospex", "プロスペックス", "en", "ja", 1, "text/plain", "general", "username", null);
                        myClient.AddTranslation("", "prospex", "株式会社プロスペックス", "en", "ja", 1, "text/plain", "general", "username", null);
                        Console.WriteLine("Your translation has been added");
                        
                        Console.WriteLine("\n");
                        
                        // BreakSentences Test(文章の一文ごとの文字数を数えます)
                        Console.WriteLine("BreakSentences Test:Press Enter");
                        Console.ReadLine();
 
                        try
                        {
                            string text = "Please break up this string into sentences. I would like this string to be broken into its respective sentences. Is this possible?";
                            string from = "en";
                            int[] sentenceLengths = myClient.BreakSentences("", text, from);
                            var breakSentencesResult = "BreakSentences broke up the above sentence into " + sentenceLengths.Length + " sentences.";
                            var lengths = String.Join(",", sentenceLengths.Select(x => x.ToString()).ToArray());
                            
                            breakSentencesResult += "The lengths of the sentences are " + lengths + " characters respectively.";
                            Console.WriteLine(breakSentencesResult);
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Something unexpected has occurred. Try again later.");
                            Console.ReadLine();
                        }
 
                        Console.WriteLine("\n");
                
                // Detect Test(文章から文字コードを取得します)
                        Console.WriteLine("Detect Test:Press Enter");
                        Console.ReadLine();
 
                        string detectResult;
                        detectResult = myClient.Detect("", "I have no idea what this language may be");
                        Console.WriteLine("The detected language friendly code is: " + detectResult);
                        
                        Console.WriteLine("\n");
                
                        // GetLanguageNames Test(文字コードの名称を指定した言語で取得します)
                        Console.WriteLine("GetLanguageNames Test:Press Enter");
                        Console.ReadLine();
 
                        string[] languageCodes = { "de", "en", "fr", "ko" };
                        string[] languageNames = myClient.GetLanguageNames("", "ja", languageCodes);
 
                        for (int i = 0; i < languageNames.Length; i++)
                        {
                            Console.WriteLine("{0} = {1}", languageCodes[i], languageNames[i]);
                        }
 
                        Console.WriteLine("\n");
       
                        // GetLanguagesForTranslate Test(使用できる言語コードの配列を取得します)
                        Console.WriteLine("GetLanguageForTranslate Test:Press Enter");
                        Console.ReadLine();
 
                        string[] languagesForTranslate = myClient.GetLanguagesForTranslate("");
                        var availableLanguages = String.Join(",", languagesForTranslate.Select(x => x.ToString()).ToArray());
                        Console.WriteLine("The languages available for translation are: " + availableLanguages);
 
                        Console.WriteLine("\n");
 
                        // GetTranslations Test(AddTranslationsで保存した単語や文章を取り出します)
                        Console.WriteLine("GetTranslations Test:Press Enter");
                        Console.ReadLine();
 
                        MTService.TranslateOptions options = new MTService.TranslateOptions(); // Use the default options
 
                        options.User = "username"; // default is all
                        MTService.GetTranslationsResponse translations = myClient.GetTranslations("", "prospex", "en", "ja", 5, options);
                        string matches = "The matches are: ";
 
                        foreach (MTService.TranslationMatch translationMatch in translations.Translations)
                        {
                            matches += "\"" + translationMatch.TranslatedText + "\"";
                        }
                        Console.WriteLine(matches);
                        
                        Console.WriteLine("\n");
 
                        // Translate Test
                        Console.WriteLine("Translate Test:Press Enter");
                        Console.ReadLine();
 
                        string input;
                        
                        while(true)
                        {
                            Console.WriteLine("Please input Japanese(or press Enter):");
                            input = Console.ReadLine();
                            if (input == "") break;
                            Console.WriteLine(myClient.Translate("", input, "ja", "en", "text/html", null) + "(" + input.Length + ")");
                            Console.WriteLine("\n");
                        }
 
                        Console.WriteLine("\n");
 
                        // TranslateArray Test
                        Console.WriteLine("TranslateArray Test:Press Enter");
                        Console.ReadLine();
 
                        string[] texts = new string[2];
 
                        options = new MTService.TranslateOptions(); // Use the default options
 
                        while (true)
                        {
                            Console.WriteLine("Please input Japanese subject(or press Enter):");
                            texts[0] = Console.ReadLine();
                            if (texts[0] == "") break;
                            Console.WriteLine("Please input Japanese body(or press Enter):");
                            texts[1] = Console.ReadLine();
                            if (texts[1] == "") break;
 
                            MTService.TranslateArrayResponse[] translatedTexts = myClient.TranslateArray("", texts, "ja", "en", options);
 
                            Console.WriteLine("\n");
                            Console.WriteLine("Subject:" + translatedTexts[0].TranslatedText + "(" + texts[0].Length + ")");
                            Console.WriteLine("Body:" + translatedTexts[1].TranslatedText + "(" + texts[1].Length + ")");
                            Console.WriteLine("\n");
                        }
 
                        Console.WriteLine("\n");
                        
                        Console.WriteLine("End:Press Enter");
                        Console.ReadLine();
                    }
                }   
            }
            catch (Exception ex)
            {
                Console.WriteLine( ex.StackTrace);
                Console.WriteLine( ex.Message);
                Console.ReadLine();
            }            
        }
 
        [DataContract]
        public class MTAccessToken
        {
            [DataMember]
            public string access_token { get; set; }
 
            [DataMember]
            public string token_type { get; set; }
 
            [DataMember]
            public string expires_in { get; set; }
 
            [DataMember]
            public string scope { get; set; }
        }
 
        private static MTAccessToken HttpPost(string uri, string parameters)
        {
            WebRequest webRequest = WebRequest.Create(uri);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";
 
            byte[] bytes = Encoding.ASCII.GetBytes(parameters);
            Stream os = null;
 
            try
            { 
                webRequest.ContentLength = bytes.Length;
                os = webRequest.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);         
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Message, "HttpPost: Request error");
                Console.ReadLine();
            }
            finally
            {
                if (os != null)
                {
                    os.Close();
                }
            }
 
            try
            { 
                // get the response
                WebResponse webResponse = webRequest.GetResponse();
 
                if (webResponse == null)return null;
 
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MTAccessToken));
                MTAccessToken token = (MTAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
 
                return token;
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Message, "HttpPost: Response error");
                Console.ReadLine();
            }
            return null;
        }
    }
}
 

上記の「clientId」と「clientSecret」は、下記のページで登録する必要があるようなので、登録しました。(コードの「??????????」の部分です)

https://datamarket.azure.com/developer/applications

image 

あと、各メソッドの第一引数は空文字にしておくそうです。(Bing デベロッパーセンターでAppIDを登録した場合に使用するそうです)

できました。

image

「私は犬っぽい人です。」と入力すると、「I'm like a dog person.」と翻訳してくれました。

あと、個人的にはSpeakメソッドが気になるんだが……今日はここまで。



連絡ボックスは「Windows Azure Platform」を活用しています。

clock November 16, 2011 22:16 by author fujii

連絡ボックスとは、弊社が開発する、業務用の情報共有ツールです。

最大の特徴は、なんといっても「Windows Azure Platform」を活用していることです!

「Azure ブログ」の技術を、余すところなく詰め込みました。

ぜひ、紹介ページにお立ち寄りください!

連絡ボックス

 

image

 

ここからは、おまけです。

 

「連絡ボックス」のテストを行っていると、データを一括して直接更新したいことが、たまにあります。

SQL Azureは、SQLなので問題はないのですが、問題はTABLEストレージです。

一行の更新なら「Azure Storage Explorer」などで問題はないのですが、数百、数千、数万となると……

Azure Storage Explorer

コンソールアプリなら、一気に更新できると思い、調べると、MSDNにサンプルがありました。

コードのクイック スタート: ファイルを Windows Azure ストレージに保存するアプリケーションの作成

残念ながら、BLOBストレージ用だったので、TABLEストレージ用に変更しました。

実行したところ……

 

「コンテキストは現在エンティティを追跡していません。」

 

意味の分からんエラーがキターッ!

image

ここから私は迷走しました。

(ちなみにここから無駄に長いです。エラーメッセージをググって来られた方は、最後の方を見てください)

色々あって、プログラミングから距離を置いていた私は、久しぶりだから、何かが古いのではと思ってしまいました。

迷走するうちに、下記に「Web Platform Installer 3.0」にたどり着き、勢いで更新すると……

http://www.microsoft.com/web/gallery/install.aspx?appid=WindowsAzureToolsVS2010

image

色々なものが、モリモリ入っていき……

image

入っていき……

image

何か知らないうちに「v1.6」になってしまいました。

image

結局、SDKのバージョンは、全く関係ありませんでした。

なんだかんだで、本を見たら……

Windows Azureアプリケーション開発入門 第2版 (MSDNプログラミングシリーズ)

 

テーブルにアクセスするためのエンティティの定義で、「TableServiceEntity」を継承していませんでした。

 

完全に忘れてた……

下記の「Inherits TableServiceEntity」です。

コードを置いておきます。

(色々と省きましたので、詳細はMSDNのサンプルをご覧ください)

Imports Microsoft.WindowsAzure
Imports Microsoft.WindowsAzure.StorageClient
 
Public Class MessageBody
    Inherits TableServiceEntity
 
    Public Property Body As String
    Public Property CryptographID As Integer
    Public Property Subject As String
 
    Public Sub New()
        MyBase.New()
    End Sub
 
    Public Sub New(ByVal partitionKey As String, ByVal rowKey As String)
        MyBase.New(partitionKey, rowKey)
    End Sub
 
    Public Sub New(ByVal partitionKey As String, ByVal rowKey As String, ByVal timestamp As Date, ByVal body As String, ByVal cryptographID As String, ByVal subject As String)
        MyBase.New(partitionKey, rowKey)
        Me.Timestamp = timestamp
        Me.Body = body
        Me.CryptographID = cryptographID
        Me.Subject = subject
    End Sub
 
End Class
 
Module Module1
 
    Sub Main()
 
        Dim account As CloudStorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=your_storage_account_name;AccountKey=your_storage_account_key")
        Dim tableClient As CloudTableClient = account.CreateCloudTableClient()
        Dim context As TableServiceContext = tableClient.GetDataServiceContext
 
        Console.WriteLine("開始")
        Console.ReadLine()
 
        Dim query = From r In context.CreateQuery(Of MessageBody)("MessageBody")
 
        ' 表示
        For Each row In query
            Console.WriteLine(row.RowKey)
        Next
 
        ' 更新(RowKeyは更新できないかった……)
        Console.WriteLine("更新")
        Console.ReadLine()
 
        For Each row In query
 
            ' 更新
            Mid(row.RowKey, 17, 1) = "1"
            Console.WriteLine(row.RowKey)
            context.UpdateObject(row)
 
         Next
 
        ' 削除
        Console.WriteLine("削除")
        Console.ReadLine()
 
        For Each row In query
 
            If Mid(row.RowKey, 17, 1) = "1" Then
 
                Console.WriteLine(row.RowKey)
                context.DeleteObject(row)
 
            End If
 
        Next
 
        context.SaveChanges()
 
        ' 追加
        Console.WriteLine("追加")
        Console.ReadLine()
 
      
        For Each row In query
 
            Dim newRowKey As String = row.RowKey
            Mid(newRowKey, 17, 1) = "1"
 
            Dim newRow As New MessageBody(row.PartitionKey, newRowKey, row.Timestamp, row.Body, row.CryptographID, row.Subject)
 
            Console.WriteLine(newRow.RowKey)
            context.AddObject("MessageBody", newRow)
 
            context.SaveChanges()
 
        Next
 
        ' まとめてやると、エラーになった
        'context.SaveChanges()
 
        Console.WriteLine("終了")
        Console.ReadLine()
 
    End Sub
 
End Module
 

 

それでは、「連絡ボックス」をよろしくお願いいたします。



カッコイイのを作ろうと思ったのに……

clock June 29, 2011 19:26 by author fujii

 

前回はさービスを作ったので、今度はクライアントを作成する。

内容は、前々回と変わらず。

' エンドポイントのURIを生成
       Dim serviceUri As Uri = ServiceBusEnvironment.CreateServiceUri("sb", ConfigurationManager.AppSettings("solutionnamespace"), "NorthWind")
 
       ' エンドポイントに対する資格情報を生成し設定
       Dim SBCredential As New TransportClientEndpointBehavior
       SBCredential.CredentialType = TransportClientCredentialType.SharedSecret
       SBCredential.Credentials.SharedSecret.IssuerName = ConfigurationManager.AppSettings("issuer")
       SBCredential.Credentials.SharedSecret.IssuerSecret = ConfigurationManager.AppSettings("accountkey")
 
       ' クライアントチャンネルファクトリを生成し設定
       Dim channelFactory As New ChannelFactory(Of INorthWindAppChannel)("RelayEndpoint", New EndpointAddress(serviceUri))
       channelFactory.Endpoint.Binding = New NetTcpRelayBinding
       channelFactory.Endpoint.Behaviors.Add(SBCredential)
 
       ' クライアントチャンネルを生成しOpen
       Dim channel As INorthWindAppChannel = channelFactory.CreateChannel
       channel.Open()
 
       ' データを取得して、表示
       gvCurrentProductList.DataSource = = channel.GetCurrentProductList()
       gvCurrentProductList.DataBind()
 
       ' 閉じる
       channel.Close()
       channelFactory.Close()

 

今回は、順調にいける気がする。

image

 

データが帰ってくるも、エラーに……

image

 

下記はサービスの関数だが……

Public Function GetCurrentProductList() Implements INorthWind.GetCurrentProductList
 
       Console.WriteLine("リクエストがありました。")
 
       Using northwindContext As New NorthwindEntities()
 
           Dim query = From row In northwindContext.Current_Product_List
                       Select row
                       Order By row.ProductID Ascending
 
           Return query
 
       End Using
 
   End Function

 

「Return query」って何? ってことみたい。

何って言われても……「Current_Product_List」型じゃい!

分からないので、String にして返してみると、「Ikura」と帰ってきた。

「Ikura」って、あのイクラだよなぁ……

image

 

それはさておき、ネットで調べてみると、「@IT」に書いてあった。

よーく読むと、サービスで「EDM(.edmx)」を作成した時の「.Designer.vb」を、クライアントのプロジェクトに追加すると、

「Current_Product_List」型を分かってくれるらしい。

 

@IT アットマーク・アイティ
Windows Azure Platform AppFabricによるオンプレミス-クラウド連携

 

今回はサービスに「NorthWind.edmx」を作ったので、

「NorthWind.Designer.vb」をクライアントのプロジェクトに追加しました。

それでは。


カッコイイのを作りたい

clock June 14, 2011 22:08 by author fujii

サービスバスを使って、データベースを色々しちゃう、カッコイイのを作ろうか。

とりあえず、「コンソールアプリケーション」を作る。

名前は「NorthWindService」にした。

何故なら、以前、サンプルデータベース「NorthWind」を何処かのサーバーに作ったのを思い出したので……

image

 

「Entity Framework」を使用すべく、EDMを追加。

image

 

データベースからEDMを作ろうとしたが……

image

 

SQL Server が古くてダメでした……

image

 

DBから作るのかよ……

仕方ないので、「NorthWind」を作り直そうと、ダウンロードする。

image

 

「えっ? AdventureWorks にしないの?」と思った方……正解!

すっかり冷静さを失って、「NorthWind」を作ってしまった……ローカルに。

サーバーに二個目の「NorthWind」作ったら、怒られそうだったので。

ローカルに作った場合は、サーバー名は「PC名\SQLEXPRESS」等としてください。

(「\SQLEXPRESS」はSQL Server インストール時の設定により変わるそうです)

image

 

で、すべてのオブジェクトを選択。

image

 

「生成された~」のオプションは次の通り……必要ないので、チェックはしません。

image

 

できました。

image

 

次に「WCFサービス」を作ります。

名前は「NorthWind」で。

image

 

参照に「Microsoft.SeviceBus.dll」を追加して、こんな構成になりました。

image

 

「NameSpace」も作りました。

「NorthWindService」は誰も作っていなかったようなので、作れました。

(「NorthWind」はダメでした)

image

 

それにならって、「App.Config」を書く。

<?xml version="1.0"?>
<configuration>
 
  <appSettings>
    <add key="solutionnamespace" value="NorthWindService"/>
    <add key="issuer" value="owner"/>
    <add key="accountkey" value="省略"/>
  </appSettings>
 
  <connectionStrings>
    <add name="NorthwindEntities" connectionString="省略" providerName="System.Data.EntityClient"/>
  </connectionStrings>
 
  <system.serviceModel>
    <services>
      <service name="NorthWindService.NorthWind">
        <endpoint binding="netTcpRelayBinding" contract="NorthWindService.INorthWind"/>
      </service>
    </services>
  </system.serviceModel>
 
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
 
 
さて、ここからが問題である。
 
どんなカッコイイ機能にするんだい?
 
思った以上に時間かかっちゃったし……
 
簡単な View があったので、何とか参照できるようにしよう……最初の志はどうした?
 
create view [dbo].[Current Product List] AS
SELECT Product_List.ProductID, Product_List.ProductName
FROM Products AS Product_List
WHERE (((Product_List.Discontinued)=0))
 
 
これがうまく参照できたら、更新とかいろいろやるって事で……
 
「ProductID」と「ProductName」はどちらもキーなので、指定する関数と、全件取得する関数を作ってみようか。
 
インターフェース(INorthWind.vb )を書いた。
Imports System.ServiceModel
 
<ServiceContract()>
Public Interface INorthWind
 
    <OperationContract()>
    Function GetCurrentProductListById(ByVal productId As Integer)
 
    <OperationContract()>
    Function GetCurrentProductListByName(ByVal productionName As String)
 
    <OperationContract()>
    Function GetCurrentProductList()
 
End Interface
 
 
Public Interface INorthWindAppChannel
    Inherits INorthWind
    Inherits IClientChannel
 
End Interface

 

オーバーロードにしなかったのは、同じ名前だとエラーになったので。

image

 

クラス(NorthWind.vb )を書き……

Imports System.Text
Imports System.Data.Objects
 
Public Class NorthWind
    Implements INorthWind
 
    Public Function GetCurrentProductList(ByVal productId As Integer) Implements INorthWind.GetCurrentProductListById
 
        Using northwindContext As New NorthwindEntities()
 
            Dim query = From row In northwindContext.Current_Product_List
                        Select row
                        Where row.ProductID = productId
 
            Return query
 
        End Using
 
    End Function
 
    Public Function GetCurrentProductList(ByVal productionName As String) Implements INorthWind.GetCurrentProductListByName
 
        Using northwindContext As New NorthwindEntities()
 
            Dim query = From row In northwindContext.Current_Product_List
                        Select row
                        Where row.ProductName = productionName
 
            Return query
 
        End Using
 
    End Function
 
    Public Function GetCurrentProductList() Implements INorthWind.GetCurrentProductList
 
        Using northwindContext As New NorthwindEntities()
 
            Dim query = From row In northwindContext.Current_Product_List
                        Select row
                        Order By row.ProductID Ascending
 
            Return query
 
        End Using
 
    End Function
 
End Class

 

Main(Module1.vb)を書く。

Imports System.Configuration
Imports System.ServiceModel
Imports System.ServiceModel.Description
Imports Microsoft.ServiceBus
Imports Microsoft.ServiceBus.Description
 
Module Module1
 
    Sub Main(ByVal args As String())
 
        ' エンドポイントのURIを生成するメソッド
        Dim adress As Uri = ServiceBusEnvironment.CreateServiceUri("sb", ConfigurationManager.AppSettings("solutionnamespace"), "NorthWind")
 
        'エンドポイントに対する資格情報を生成
        Dim SBCredential As New TransportClientEndpointBehavior
        SBCredential.CredentialType = TransportClientCredentialType.SharedSecret
        SBCredential.Credentials.SharedSecret.IssuerName = ConfigurationManager.AppSettings("issuer")
        SBCredential.Credentials.SharedSecret.IssuerSecret = ConfigurationManager.AppSettings("accountkey")
 
        ' ServiceHostのインスタンスを生成
        Dim host As ServiceHost = New ServiceHost(GetType(NorthWind), adress)
 
        ' エンドポイントにServiceRegistryの設定を反映
        Dim serviceRegistryStteing As IEndpointBehavior = New ServiceRegistrySettings(DiscoveryType.Public)
 
        ' エンドポイント構成にServiceBusの資格情報を追加
        For Each endpoint As ServiceEndpoint In host.Description.Endpoints
            endpoint.Behaviors.Add(serviceRegistryStteing)
            endpoint.Behaviors.Add(SBCredential)
        Next
 
        ' サービスをオープン
        host.Open()
        Console.WriteLine("Service Started...")
        Console.WriteLine("Press [Enter] to exit")
        Console.ReadLine()
        host.Close()
 
    End Sub
 
End Module

 

ビルドするとエラーとなった。

image

 

対象のフレームワークを「.Net Faramework 4」に変更する。

(「.Net Faramework 4 Client Profile」になっていたので)

image

 

デバッグ実行すると……

image

 

出てきました。

image

 

「カッコイイのを作ろうか」と思ったのが、運の尽き。

そして、力も尽きた……Clientは、また今度で。

「えっ? 前々回と、あんま変わんねーじゃん」と思った方……ご愛読、ありがとうございます。

そして、ごめんなさい。

色々と思い出せず時間は前々回と同じくらいかかっているので、許してください……ダメじゃん……



Sign In