[C#][ASP.net] 串接 Google.Apis.Calendar.v3 簡單教學入門(二) - 新增刪除篇

2017-12-19

上一篇文章 串接 Google.Apis.Calendar.v3 簡單教學入門(一) - 授權篇 我們簡單的讓客戶可以進行授權,接下來就是要能夠新增跟刪除行事曆上面的事件

image

Step1 .  承襲上一篇範例,在專案下有一個GoogleStorage ,然後 App 的資訊都在裡面,並且有一個 Google.Apis.Auth.OAuth2.Responses.TokenResponse-sample_user_id 裡面已經有一個已經授權過的 user token 資訊

        /// <summary>
        /// App 憑證資料的檔案夾
        /// </summary>
        public static string Gfolder = AppDomain.CurrentDomain.BaseDirectory + "GoogleStorage" + System.IO.Path.DirectorySeparatorChar;

        /// <summary>
        /// 通常在就是用戶的資料庫 id 
        /// </summary>
        public static string UserId = "sample_user_id";

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        ///  傳入 Google Token 物件,處理成 CalendarService 後回傳
        /// </summary>
        /// <param name="GoogleTokenModelObj"></param>
        /// <returns></returns>
        public static CalendarService GetCalendarService(GoogleTokenModel GoogleTokenModelObj)
        {
            CalendarService service = null;

            GoogleClientSecrets clientSecret;

            using (var stream = new FileStream(Gfolder + @"\client_secret.json", FileMode.Open, FileAccess.Read))
            {
                clientSecret = GoogleClientSecrets.Load(stream);
            }

            IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
                new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = clientSecret.Secrets,
                    DataStore = new FileDataStore(Gfolder),
                    Scopes = new[] { CalendarService.Scope.Calendar }
                });

            var result = new AuthorizationCodeWebApp(flow, "", "").AuthorizeAsync(UserId, CancellationToken.None).Result;
            service = new CalendarService(new BaseClientService.Initializer
            {
                ApplicationName = "donma-test",
                HttpClientInitializer = result.Credential
            });

            return service;
        }

Step2. 建立事件
        protected void btnCreateEvent_Click(object sender, EventArgs e)
        {
            Event event1 = new Event()
            {
                Summary = "當麻部落格測試",
                Start = new EventDateTime()
                {
                    DateTime = DateTime.Now,
                    TimeZone = "Asia/Taipei"
                },
                End = new EventDateTime()
                {
                    DateTime = DateTime.Now.AddMinutes(1),
                    TimeZone = "Asia/Taipei"
                },

            };
            
            var d = JsonConvert.DeserializeObject<GoogleTokenModel>(File.ReadAllText(Gfolder + "Google.Apis.Auth.OAuth2.Responses.TokenResponse-"+UserId));
            CalendarService calService = GetCalendarService(d);
            EventsResource eventResource = new EventsResource(calService);
            

            var insertEntry = eventResource.Insert(event1, "primary").Execute();
            txtEventId.Text = insertEntry.Id;
           
        }

Step3. 建立成功後,我會把 EventId 暫時放到 txtEventId 裡面存放,之後,就可以透過此Id 將剛剛建立的刪除

        protected void btnDelEvent_Click(object sender, EventArgs e)
        {
            var d = JsonConvert.DeserializeObject<GoogleTokenModel>(File.ReadAllText(Gfolder + "Google.Apis.Auth.OAuth2.Responses.TokenResponse-" + UserId));
            CalendarService calService = GetCalendarService(d);
            EventsResource eventResource = new EventsResource(calService);

            eventResource.Delete("primary", txtEventId.Text).Execute();
            Response.Write("成功刪除 :" + txtEventId.Text);

        }

今天案例很簡單,直接可以下載試試看


Source : https://github.com/donma/CSharp.Google.Apis.Calendar.v3


Reference :

http://vito-note.blogspot.tw/2015/04/aspnet-google-oauth2.html
https://www.codeproject.com/Articles/36482/How-to-Create-Google-Calendar-Events-Using-NET
https://www.codeproject.com/Articles/201907/Using-Google-Calendar-in-an-ASP-NET-Website


當麻許的超技八 2014 | Donma Hsu Design.