【C#】コンソールアプリからGoogle Cloud Datastoreに接続
お久しぶりでございます。
タイトルの通りコンソールアプリからGoogle Cloud Datastoreに接続でございます。
最近GCPと戦ってるんです。だるだる。
つってもGCPからAWSにお引っ越しするだけですけども。
お引っ越しなので当然エンティティは作成済のものとします。
あとGoogle Developers ConsoleからP12キーを作成しといてくださいねー。
とりあえずライブラリインストールから。
NuGet便利ねー。pm installなり、UIからやるなりしてください。
今回はbeta2を使ってます。正式版出てないし、サンプルもない。
http://www.nuget.org/packages?q=Google.Apis.Datastore
はい。サンプルコード。
どーせ全件かっさらってSQL Serverにつっこむだけなので今回はrunQueryで。
lookupとか他のものはドキュメント参照。
Entityの実装気に食わん。GetValue
つーかAndroidもだけどGoogleの実装ってほんといまいち。って思うのはぼくだけでしょうか。
https://developers.google.com/resources/api-libraries/documentation/datastore/v1beta2/csharp/latest/
using Google.Apis.Auth.OAuth2; using Google.Apis.Datastore.v1beta2; using Google.Apis.Datastore.v1beta2.Data; using Google.Apis.Services; using System; using System.Diagnostics; using System.Linq; using System.Security.Cryptography.X509Certificates; namespace DatastoreTest.Hoge { class Program { static void Main(string[] args) { var certificate = new X509Certificate2(@"作成したP12ファイルのパス", "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer("OAuth/サービスアカウント/メールアドレスの文字列") { Scopes = new[] { DatastoreService.Scope.Datastore, DatastoreService.Scope.UserinfoEmail } }.FromCertificate(certificate)); var service = new DatastoreService(new BaseClientService.Initializer { HttpClientInitializer = credential, }); var queryBody = new RunQueryRequest() { Query = new Query { Limit = 1, Kinds = new [] { new KindExpression { Name = "Hoge" } }, }, }; var request = new DatasetsResource.RunQueryRequest(service, queryBody, "プロジェクト名"); var response = request.Execute(); response.Batch.EntityResults.ToList().ForEach(x => { Console.WriteLine(x.Entity.Key.Path.First().Name); x.Entity.Properties.ToList().ForEach(y => { Console.WriteLine(y.Key); }); }); Console.ReadLine(); } } }