Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9749

Google Calendar API #2

$
0
0

前回の記事
Google Calendar API #1

環境

IDE:VisualStudio2019
アプリケーション:コンソールアプリ
フレームワーク:.NET Core 3.1

カレンダーに予定を追加

前回は予定取得を試してみました。
今回はカレンダーの予定追加/更新を行ってみます。

まずわかりやすいように自分のカレンダーの直近の予定を空にします。
image.png

予定を追加するコードを記述します。
以下公式にサンプルがありました。
Events: insert

以下のようなスケジュール追加メソッドを用意

/// <summary>/// カレンダーイベントを追加/// </summary>/// <param name="calendarId">カレンダーID</param>publicvoidInsertEvent(stringcalendarId){varnewEvent=newEvent(){Summary="Google I/O 2020",Location="神奈川県横浜市",Description="テスト備考",Start=newEventDateTime(){DateTime=DateTime.Parse("2020/02/28 9:00:00"),TimeZone="Asia/Tokyo",},End=newEventDateTime(){DateTime=DateTime.Parse("2020/02/28 17:00: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 },//    }//}};varrequest=this.Serive.Events.Insert(newEvent,calendarId);varcreatedEvent=request.Execute();Console.WriteLine("Event created: {0}",createdEvent.HtmlLink);}

結果
image.png

サンプル全文

規定クラスを作りました。

usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Services;usingNewtonsoft.Json.Linq;usingSystem.IO;namespaceGoogleAPITest{/// <summary>/// GoogleAPI利用においての規定クラス/// </summary>publicabstractclassGoogleAPIBase<T>whereT:IClientService{/// <summary>/// クライアントサービスインターフェース/// </summary>protectedTSerive{get;set;}/// <summary>/// コンストラクタ/// </summary>/// <param name="keyJsonPath">APIキーのJSONファイルのパス</param>publicGoogleAPIBase(stringkeyJsonPath,string[]scope){varjObject=JObject.Parse(File.ReadAllText(keyJsonPath));varserviceAccountEmail=jObject["client_email"].ToString();varprivateKey=jObject["private_key"].ToString();varcredential=newServiceAccountCredential(newServiceAccountCredential.Initializer(serviceAccountEmail){Scopes=scope}.FromPrivateKey(privateKey));this.Serive=this.CreateService(credential);}/// <summary>/// サービス作成メソッド/// </summary>/// <param name="credential">認証情報</param>/// <returns>クライアントサービスインターフェース</returns>protectedabstractTCreateService(ICredentialcredential);}}

カレンダーAPI以外でも使用できるように、サービス作成メソッドを継承先に強制し、サービスの型をジェネリックにしている。

カレンダーAPIテストクラス

usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Calendar.v3;usingGoogle.Apis.Calendar.v3.Data;usingGoogle.Apis.Services;usingSystem;namespaceGoogleAPITest.Calendar{/// <summary>/// カレンダーAPIテストクラス/// </summary>publicclassCalendarAPITest:GoogleAPIBase<CalendarService>{/// <summary>/// アプリケーション名/// </summary>privateconststringAPP_NAME="Google Calendar API .NET";/// <summary>/// カレンダーテストクラス/// </summary>publicCalendarAPITest(stringkeyJsonPath):base(keyJsonPath,newstring[]{CalendarService.Scope.Calendar}){}/// <summary>/// クライアントサービス作成/// </summary>/// <param name="credential">認証情報</param>/// <returns>クライアントサービスインターフェース</returns>protectedoverrideCalendarServiceCreateService(ICredentialcredential){returnnewCalendarService(newBaseClientService.Initializer(){HttpClientInitializer=credential,ApplicationName=APP_NAME});}/// <summary>/// 予定読み取り/// </summary>/// <param name="calendarId">カレンダーID</param>publicvoidReadEvents(stringcalendarId){// ここで第2引数にサービスアカウントに公開したカレンダーIDを指定するvarrequest=newEventsResource.ListRequest(this.Serive,calendarId);request.TimeMin=DateTime.Now;request.ShowDeleted=false;request.SingleEvents=true;request.MaxResults=10;request.OrderBy=EventsResource.ListRequest.OrderByEnum.StartTime;// List events.varevents=request.Execute();Console.WriteLine("Upcoming events:");if(events.Items!=null&&events.Items.Count>0){foreach(vareventIteminevents.Items){varwhen=eventItem.Start.DateTime.ToString();if(String.IsNullOrEmpty(when)){when=eventItem.Start.Date;}Console.WriteLine("{0} start:({1}) end:({2})",eventItem.Summary,when,eventItem.End.DateTime.ToString());}}else{Console.WriteLine("No upcoming events found.");}}/// <summary>/// カレンダーイベントを追加/// </summary>/// <param name="calendarId">カレンダーID</param>publicvoidInsertEvent(stringcalendarId){varnewEvent=newEvent(){Summary="Google I/O 2020",Location="神奈川県横浜市",Description="テスト備考",Start=newEventDateTime(){DateTime=DateTime.Parse("2020/02/28 9:00:00"),TimeZone="Asia/Tokyo",},End=newEventDateTime(){DateTime=DateTime.Parse("2020/02/28 17:00: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 },//    }//}};varrequest=this.Serive.Events.Insert(newEvent,calendarId);varcreatedEvent=request.Execute();Console.WriteLine("Event created: {0}",createdEvent.HtmlLink);}}}

プログラムメインエントリ

usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Calendar.v3;usingGoogle.Apis.Services;usingGoogle.Apis.Util.Store;usingGoogleAPITest.Calendar;usingNewtonsoft.Json.Linq;usingSystem;usingSystem.IO;usingSystem.Threading;namespaceGoogleAPITest{/// <summary>/// メインクラス/// </summary>publicclassProgram{/// <summary>/// メインエントリ/// </summary>/// <param name="args">実行時引数</param>publicstaticvoidMain(string[]args){try{// カレンダーIDvarcalendarId="カレンダーID";// Googleカレンダーテストクラスインスタンス化varcalApi=newCalendarAPITest(@"C:\job\TestProject\GoogleAPITest\testproject-269217-813bf9be17a5.json");// イベント読み取りcalApi.ReadEvents(calendarId);// イベント追加calApi.InsertEvent(calendarId);}catch(Exceptionerr){Console.WriteLine(err.Message);}finally{Console.Read();}}}}

次回は更新をやってみたいと思います。


Viewing all articles
Browse latest Browse all 9749

Trending Articles