簡體   English   中英

帶有 ASP.NET 的 Google 日歷 API

[英]Google Calendar API with ASP.NET

我對使用 Google Calendar API 在 ASP.NET webforms (C#) 中添加/修改事件感到困惑。

我不確定我是否需要 oAuth 或什么。 我的應用程序在我自己的服務器上訪問我自己的域和我自己的日歷。 我不需要其他用戶讓我訪問他們的日歷; 我只需要通過我的應用程序訪問我自己的。

在我的一個 aspx 頁面上,我想將事件信息發送到我的 Google 日歷以添加(或稍后修改)事件。

我檢查了各種代碼示例和 Google 入門指南。 我只是不清楚到底需要什么。 我已經設置了一個 API 密鑰和一個 oAuth2 客戶端 ID。 谷歌的說明讓我轉了一圈,這可能是因為我需要澄清什么是需要的。

有人可以澄清我的困惑並指出正確的方向嗎?

概括 :

  • 調用谷歌雲 oauth2 保護資源

  • 從您的服務器到谷歌服務器

  • 無需用戶交互

  • 訪問您自己的數據

  • 使用 C#

代碼 :

    var private_key = @"-----BEGIN PRIVATE KEY-ccc-END PRIVATE KEY-----\n";
    string calendarId = @"xxxxxxxxxxxxx@group.calendar.google.com";
    var client_email = @"my-google-calender@xxx.iam.gserviceaccount.com";

    var credential =
        new ServiceAccountCredential(
        new ServiceAccountCredential.Initializer(client_email)
        {
            Scopes = new string[] { CalendarService.Scope.Calendar }
        }.FromPrivateKey(private_key));
    var service = new CalendarService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
    });
  • 使用服務方法獲取數據

  • 可以從此鏈接生成私鑰和 client_email

  • 日歷 ID 可以在 calendar.google.com 上找到

  • 您必須與 client_email 共享您的日歷,請參閱演示


  Google            You                             You
  Pay +             Pay +                           Pay +
  Google            Google                          You
  Manage            Manage                          Manage%
 +----------+    +----------+                     +----------+
 | Gmail    |    |          |                     |          |
 | Calendar |    |  G Suite |                     | Google   |
 | drive    |    |          |                     | Cloud    |
 |          |    |          |                     |          |
 +----^-----+    +----+-----+                     +------+---+
      |               ^                                  ^
      |               |                                  |
      |               |                                  |
      |               |                                  |
+-------------------------------------------------------------+
|     |               |                                  |    |
|     |               |                                  |    |
|     |               |       Google                     |    |
|     |               |       Oauth2                     |    |
|     |               |       Server                     |    |
|     |               |                                  |    |
|     |               |                                  |    |
+-------------------------------------------------------------+
      |               |                                  |
      |               |         +----------------+       |
      |               |         |                |       |
      |               |         |                |       | No
      |               |require  |                |       | Consent
      |               |admin    |                |       |
      |               |consent  |                |       |
      |require        |         |                +-------+
      |user           |         |                |
      |consent        +---------+   Your app     |
      |                         |                |
      |                         |                |
      |                         |                |
      |                         |                |
      +-------------------------+                |
                                |                |
                                |                |
                                |                |
                                +----------------+
                                     You
                                     Pay +
                                     You
                                     Manage

分步演示


步驟 01:打開谷歌控制台

https://console.developers.google.com/projectselector/apis/library/calendar-json.googleapis.com

步驟02:點擊選擇

在此處輸入圖片說明

步驟 03:選擇或創建一個新項目

在此處輸入圖片說明

步驟 04:點擊啟用或管理

在此處輸入圖片說明 在此處輸入圖片說明

步驟 05:單擊憑據

在此處輸入圖片說明

步驟 06:創建服務帳戶密鑰

在此處輸入圖片說明

步驟 07:輸入服務帳戶名稱,單擊創建

在此處輸入圖片說明

步驟 08:單擊無角色創建,然后將下載的 json 私鑰保存在安全的地方

在此處輸入圖片說明

步驟 09:復制您的 client_email 從

在此處輸入圖片說明

第十步:打開谷歌日歷

  • 日歷.google.com

第 11 步:打開您的日歷設置和共享

在此處輸入圖片說明

第 12 步:必須與特定人員共享並單擊添加

在此處輸入圖片說明

第 13 步:

  1. 添加您之前在步驟 09 中復制的服務帳戶的電子郵件
  2. 更改權限 進行更改並管理共享
  3. 點擊發送

    在此處輸入圖片說明

第 14 步:在同一頁面上復制並保存我們需要的日歷 ID

在此處輸入圖片說明

第 15 步:創建新的控制台應用程序

在此處輸入圖片說明

步驟16:將私鑰json文件添加到您的項目中

在此處輸入圖片說明

步驟17:右鍵單擊私鑰json,然后單擊Propertis

在此處輸入圖片說明

第 18 步:將“復制到輸出目錄”更改為“始終復制”

在此處輸入圖片說明

第 19 步:打開 PM 控制台並在默認項目 D 上選擇您的項目

在此處輸入圖片說明

第 20 步:安裝 Google.Apis 日歷包

Install-Package Google.Apis.Calendar.v3

在此處輸入圖片說明

第 21 步:用代碼替換 Program.cs

using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace CalendarQuickstart
{
    class Program
    {
        static void Main(string[] args)
        {
            string jsonFile = "xxxxxxx-xxxxxxxxxxxxx.json";
            string calendarId = @"xxxxxxxxxxxxx@group.calendar.google.com";

            string[] Scopes = { CalendarService.Scope.Calendar };

            ServiceAccountCredential credential;

            using (var stream =
                new FileStream(jsonFile, FileMode.Open, FileAccess.Read))
            {
                var confg = Google.Apis.Json.NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(stream);
                credential = new ServiceAccountCredential(
                   new ServiceAccountCredential.Initializer(confg.ClientEmail)
                   {
                       Scopes = Scopes
                   }.FromPrivateKey(confg.PrivateKey));
            }

            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Calendar API Sample",
            });

            var calendar = service.Calendars.Get(calendarId).Execute();
            Console.WriteLine("Calendar Name :");
            Console.WriteLine(calendar.Summary);

            Console.WriteLine("click for more .. ");
            Console.Read();


            // Define parameters of request.
            EventsResource.ListRequest listRequest = service.Events.List(calendarId);
            listRequest.TimeMin = DateTime.Now;
            listRequest.ShowDeleted = false;
            listRequest.SingleEvents = true;
            listRequest.MaxResults = 10;
            listRequest.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

            // List events.
            Events events = listRequest.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.WriteLine("click for more .. ");
            Console.Read();

            var myevent = DB.Find(x => x.Id == "eventid" + 1);

            var InsertRequest = service.Events.Insert(myevent, calendarId);

            try
            {
                InsertRequest.Execute();
            }
            catch (Exception)
            {
                try
                {
                    service.Events.Update(myevent, calendarId, myevent.Id).Execute();
                    Console.WriteLine("Insert/Update new Event ");
                    Console.Read();

                }
                catch (Exception)
                {
                    Console.WriteLine("can't Insert/Update new Event ");

                }
            }
        }


        static List<Event> DB =
             new List<Event>() {
                new Event(){
                    Id = "eventid" + 1,
                    Summary = "Google I/O 2015",
                    Location = "800 Howard St., San Francisco, CA 94103",
                    Description = "A chance to hear more about Google's developer products.",
                    Start = new EventDateTime()
                    {
                        DateTime = new DateTime(2019, 01, 13, 15, 30, 0),
                        TimeZone = "America/Los_Angeles",
                    },
                    End = new EventDateTime()
                    {
                        DateTime = new DateTime(2019, 01, 14, 15, 30, 0),
                        TimeZone = "America/Los_Angeles",
                    },
                     Recurrence = new List<string> { "RRULE:FREQ=DAILY;COUNT=2" },
                    Attendees = new List<EventAttendee>
                    {
                        new EventAttendee() { Email = "lpage@example.com"},
                        new EventAttendee() { Email = "sbrin@example.com"}
                    }
                }
             };
    }
}

第 22 步:將 json 文件名替換為您的 json 文件名

  string jsonFile = "xxxxxxx-xxxxxxxx.json";

第 23 步:將 calendarId 替換為第 14 步中的 calendarId

 string calendarId = @"xxxxxxxxxxxxx@group.calendar.google.com";

第 24 步:運行應用程序

在此處輸入圖片說明

第 25 步:訪問您的日歷,您應該會在其中看到事件

 2019/01/13

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM