PowerShellで操作したかったが難しそうなのでとりあえずリファレンスを見ながらC#で
まずはクイックスタートガイドのサンプルを実行してみる。
公式サイトの.NetQuickStartから
https://developers.google.com/calendar/quickstart/dotnet
カレンダーAPIを有効にする
Enable~APIをクリック→DOWNLOAD CLIENT CONFIGRATION
credentials.jsonファイルをダウンロード
VisualStudioを起動。
credentials.jsonをプロジェクトに追加する
- ここでサンプルのサイトではソリューションエクスプローラーでドラグするように指示があるが、VS2017ではドラグではなくcredentials.jsonをコピー⇒貼り付けで追加を行う。
- エクスプローラー上のcredentials.jsonを選択、プロパティウィンドウの出力ディレクトリにコピー→常にコピーするに変更。
クイックスタートページのソースコードと置き換える
using Google.Apis.Auth.OAuth2; using Google.Apis.Calendar.v3; using Google.Apis.Calendar.v3.Data; using Google.Apis.Services; using Google.Apis.Util.Store; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace CalendarQuickstart { class Program { // If modifying these scopes, delete your previously saved credentials // at ~/.credentials/calendar-dotnet-quickstart.json static string[] Scopes = { CalendarService.Scope.CalendarReadonly }; static string ApplicationName = "Google Calendar API .NET Quickstart"; static void Main(string[] args) { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. EventsResource.ListRequest request = service.Events.List("primary"); request.TimeMin = DateTime.Now; request.ShowDeleted = false; request.SingleEvents = true; request.MaxResults = 10; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; // List events. Events events = request.Execute(); Console.WriteLine("Upcoming events:"); if (events.Items != null && events.Items.Count > 0) { foreach (var eventItem in events.Items) { string when = eventItem.Start.DateTime.ToString(); if (String.IsNullOrEmpty(when)) { when = eventItem.Start.Date; } Console.WriteLine("{0} ({1})", eventItem.Summary, when); } } else { Console.WriteLine("No upcoming events found."); } Console.Read(); } } }
ビルドして実行する。 初回実行時にブラウザが起動してAPIの権限付与の確認ダイアログが表示されるので「許可」を選択する。
直近の予定10件がコンソールに表示される。
予定の追加方法
https://developers.google.com/calendar/v3/reference/events/insert?hl=ja
現在の認証は参照しか許されていないため、認証情報の修正を行う。
クイックスタートページのEnable~APIをクリックしてAPIConsoleのリンククリック。
左上の▼をクリック。
プロジェクトの選択ウィンドウが出現するので、「Quickstart」(サンプルの通りに作成している場合)をクリックする。
左側の「認証情報」をクリックするとOAuth 2.0 クライアント IDの一覧が表示される。
「OAuth同意画面」をクリック
「スコープを追加」をクリックして「../auth/calendar」にチェックを入れて「追加」をクリック、画面下の保存ボタンをクリック。
重要なスコープを追加したため、スコープの公開前に、同意画面で Google による確認が必要です。と表示される。
一度スコープを変更して実行
このままスケジュール作成のコードを記述しても403エラーになってしまうので、 最初にサンプルで実行したスケジュール取得ソースの
static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
これを
static string[] Scopes = { CalendarService.Scope.Calendar };
に変更して、一度実行する。
すると再度承認の確認画面がブラウザで起動するので、「許可」を選択しプログラムを完走させる。
最初のサンプルソースを以下に書き換える
※using ディレクティブ部分は同じなので省略
namespace CalendarQuickstart { class Program { // If modifying these scopes, delete your previously saved credentials // at ~/.credentials/calendar-dotnet-quickstart.json //"CalendarReadonly"から"Calendar"に変更 static string[] Scopes = { CalendarService.Scope.Calendar }; static string ApplicationName = "Google Calendar API .NET Quickstart"; static void Main(string[] args) { //追加する予定の中身 Event newEvent = new Event() { Summary = "Google I/O 2019", Location = "800 Howard St., San Francisco, CA 94103", Description = "A chance to hear more about Google's developer products.", Start = new EventDateTime() { DateTime = DateTime.Parse("2019-04-01T09:00:00+09:00"), TimeZone = "Asia/Tokyo", }, End = new EventDateTime() { DateTime = DateTime.Parse("2019-04-01T17:00:00+09:00"), TimeZone = "Asia/Tokyo", }, Recurrence = new String[] { "RRULE:FREQ=DAILY;COUNT=2" }, Attendees = new EventAttendee[] { new EventAttendee() { Email = "lpage@example.com" }, new EventAttendee() { Email = "sbrin@example.com" }, }, Reminders = new Event.RemindersData() { UseDefault = false, Overrides = new EventReminder[] { new EventReminder() { Method = "email", Minutes = 24 * 60 }, new EventReminder() { Method = "sms", Minutes = 10 }, } } }; UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // 予定を追加登録 string calendarId = "primary"; EventsResource.InsertRequest request = service.Events.Insert(newEvent, calendarId); Event createdEvent = request.Execute(); Console.WriteLine("Event created: {0}", createdEvent.HtmlLink); } } }
認証情報の追加修正は Google Cloud Console経由からでも可能。
ナビゲーションメニューから「APIとサービス」-「認証情報」