Google Calendar API with ASP.NET

前端 未结 1 1600
灰色年华
灰色年华 2021-02-04 18:48

I\'m confused about using the Google Calendar API for adding/modifying events in ASP.NET webforms (C#).

I\'m not sure if I need oAuth or what. My app is on my own serve

相关标签:
1条回答
  • 2021-02-04 18:59

    Summary :

    • To Call a google clould oauth2 protected resource

    • From your server to google server

    • Without user interaction

    • Accessing your own data

    • Using C#

    Code :

        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,
        });
    
    • Use service methods to get the data

    • Private Key and client_email can be generated from this link

    • Calendar Id can be found on calendar.google.com

    • You must share your calendar with client_email see the demo


      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
    

    Step by Step demo


    Step 01 : open google console

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

    Step 02 : click select

    Step 03: select or create a new project

    Step 04: click enable or manage

    Step 05: click Credentials

    Step 06: Create service account key

    Step 07: Enter a service account name the click create

    Step 08: click Create without role then keep the downloaded json private key in safe place

    Step 09: copy your client_email from

    Step 10: open google calendar

    • calendar.google.com

    Step 11: open your calendar Settings and sharing

    Step 12: got to Share with specific people and click add

    Step 13:

    1. Add the email for the service account that you copied before in step 09
    2. change the Permissions too Make changes and manage sharing
    3. click send

    Step 14: on the same page copy and save the Calendar ID we will need it

    Step 15: crate new console application

    Step 16: add the private key json file to your project

    Step 17: r-click private key json and click Propertis

    Step 18: change "Copy to output Direcory to "Copy always"

    Step 19: open PM Console and chose your project on Default project D

    Step 20: Install Google.Apis Calendar Package

    Install-Package Google.Apis.Calendar.v3
    

    Step 21: replace Program.cs with code

    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"}
                        }
                    }
                 };
        }
    }
    

    Step 22: replace json File Name with your json file name

      string jsonFile = "xxxxxxx-xxxxxxxx.json";
    

    Step 23: replace calendarId with your calendarId from step 14

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

    Step 24: run the app

    Step 25 : visit you calendar you should see the event in

     2019/01/13
    

    0 讨论(0)
提交回复
热议问题