Google Calendar API,只需知道自己的电子邮件地址即可将事件添加到某人的日历中

时间:2014-04-26 11:24:05

标签: c# asp.net api calendar google-api

我已下载Google.Apis名称空间:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;

我花了整整一天的时间在网上查看.NET示例,了解如何通过了解他们的电子邮件地址将事件添加到某人日历中。

我尝试了以下代码,但是它会带来错误,很明显它不会起作用:

Public void Method(string email, string text)
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets
                {
                    ClientId = "CLIENTID",
                    ClientSecret = "CLIENTSECRET",
                },
                new[] { CalendarService.Scope.Calendar },
                "user",
                CancellationToken.None).Result;

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


    Event event1 = new Event()
    {
      Summary = "Something",
      Location = "Somewhere",
      Start = new EventDateTime() {
          DateTime = DateTime.Now,
          TimeZone = "America/Los_Angeles"
      },
      End = new EventDateTime() {
          DateTime = DateTime.Now,
          TimeZone = "America/Los_Angeles"
      },
      Attendees = new List<EventAttendee>()
          {
            new EventAttendee() { Email: email } //bringing up an error "Syntax ',' expected
          }
    };

    Event thisevent = service.Events.Insert(event1, "primary").Fetch(); // Another error. "Does not contain a definition for Fetch"

}

任何帮助表示赞赏!甚至其他代码的样本:)

2 个答案:

答案 0 :(得分:11)

在您创建事件并插入事件的部分中存在语法错误。以下是一个具有Google API .NET库正确语法的代码段:

Event myEvent = new Event
{
  Summary = "Appointment",
  Location = "Somewhere",
  Start = new EventDateTime() {
      DateTime = new DateTime(2014, 6, 2, 10, 0, 0),
      TimeZone = "America/Los_Angeles"
  },
  End = new EventDateTime() {
      DateTime = new DateTime(2014, 6, 2, 10, 30, 0),
      TimeZone = "America/Los_Angeles"
  },
  Recurrence = new String[] {
      "RRULE:FREQ=WEEKLY;BYDAY=MO"
  },
  Attendees = new List<EventAttendee>()
      {
        new EventAttendee() { Email = "johndoe@gmail.com" }
      }
};

Event recurringEvent = service.Events.Insert(myEvent, "primary").Execute();

答案 1 :(得分:1)

public static string ApplicationName = "Google Console ApplicationName";
        public static string ClientId = "Google Console ClientId";
        public static string ClientSecret = "Google Console ClientSecret";
        public static string RedirectURL = "Google Console RedirectURL";

        public static ClientSecrets GoogleClientSecrets = new ClientSecrets()
        {
            ClientId = ClientId,
            ClientSecret = ClientSecret
        };

        public static string[] Scopes =
        {
                                CalendarService.Scope.Calendar,
                                CalendarService.Scope.CalendarReadonly
                            };

        public static UserCredential GetUserCredential(out string error)
        {
            UserCredential credential = null;
            error = string.Empty;

            try
            {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets
                {
                    ClientId = ClientId,
                    ClientSecret = ClientSecret
                },
                Scopes,
                Environment.UserName,
                CancellationToken.None,
                null).Result;
            }
            catch (Exception ex)
            {
                credential = null;
                error = "Failed to UserCredential Initialization: " + ex.ToString();
            }

            return credential;
        }

        public static IAuthorizationCodeFlow GoogleAuthorizationCodeFlow(out string error)
        {
            IAuthorizationCodeFlow flow = null;
            error = string.Empty;

            try
            {
                flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = GoogleClientSecrets,
                    Scopes = Scopes
                });
            }
            catch (Exception ex)
            {
                flow = null;
                error = "Failed to AuthorizationCodeFlow Initialization: " + ex.ToString();
            }

            return flow;
        }

        public static UserCredential GetGoogleUserCredentialByRefreshToken(string refreshToken, out string error)
        {
            TokenResponse respnseToken = null;
            UserCredential credential = null;
            string flowError;
            error = string.Empty;
            try
            {
                // Get a new IAuthorizationCodeFlow instance
                IAuthorizationCodeFlow flow = GoogleAuthorizationCodeFlow(out flowError);

                respnseToken = new TokenResponse() { RefreshToken = refreshToken };

                // Get a new Credential instance                
                if ((flow != null && string.IsNullOrWhiteSpace(flowError)) && respnseToken != null)
                {
                    credential = new UserCredential(flow, "user", respnseToken);
                }

                // Get a new Token instance
                if (credential != null)
                {
                    bool success = credential.RefreshTokenAsync(CancellationToken.None).Result;
                }

                // Set the new Token instance
                if (credential.Token != null)
                {
                    string newRefreshToken = credential.Token.RefreshToken;
                }
            }
            catch (Exception ex)
            {
                credential = null;
                error = "UserCredential failed: " + ex.ToString();
            }
            return credential;
        }

        public static CalendarService GetCalendarService(string refreshToken, out string error)
        {
            CalendarService calendarService = null;
            string credentialError;
            error = string.Empty;
            try
            {
                var credential = GetGoogleUserCredentialByRefreshToken(refreshToken, out credentialError);
                if (credential != null && string.IsNullOrWhiteSpace(credentialError))
                {
                    calendarService = new CalendarService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = ApplicationName
                    });
                }
            }
            catch (Exception ex)
            {
                calendarService = null;
                error = "Calendar service failed: " + ex.ToString();
            }
            return calendarService;
        }

        public static string AddCalenderEvents(string refreshToken, string emailAddress, string summary, DateTime? start, DateTime? end, out string error)
        {
            string eventId = string.Empty;
            error = string.Empty;
            string serviceError;

            try
            {
                var calendarService = GetCalendarService(refreshToken, out serviceError);

                if (calendarService != null && string.IsNullOrWhiteSpace(serviceError))
                {
                    var list = calendarService.CalendarList.List().Execute();
                    var calendar = list.Items.SingleOrDefault(c => c.Summary == emailAddress);
                    if (calendar != null)
                    {
                        Google.Apis.Calendar.v3.Data.Event calenderEvent = new Google.Apis.Calendar.v3.Data.Event();

                        calenderEvent.Summary = summary;
                        //calenderEvent.Description = summary;
                        //calenderEvent.Location = summary;
                        calenderEvent.Start = new Google.Apis.Calendar.v3.Data.EventDateTime
                        {
                            //DateTime = new DateTime(2018, 1, 20, 19, 00, 0)
                            DateTime = start//,
                            //TimeZone = "Europe/Istanbul"
                        };
                        calenderEvent.End = new Google.Apis.Calendar.v3.Data.EventDateTime
                        {
                            //DateTime = new DateTime(2018, 4, 30, 23, 59, 0)
                            DateTime = start.Value.AddHours(12)//,
                            //TimeZone = "Europe/Istanbul"
                        };
                        calenderEvent.Recurrence = new List<string>();

                        //Set Remainder
                        calenderEvent.Reminders = new Google.Apis.Calendar.v3.Data.Event.RemindersData()
                        {
                            UseDefault = false,
                            Overrides = new Google.Apis.Calendar.v3.Data.EventReminder[]
                            {
                                                    new Google.Apis.Calendar.v3.Data.EventReminder() { Method = "email", Minutes = 24 * 60 },
                                                    new Google.Apis.Calendar.v3.Data.EventReminder() { Method = "popup", Minutes = 24 * 60 }
                            }
                        };

                        #region Attendees
                        //Set Attendees
                        calenderEvent.Attendees = new Google.Apis.Calendar.v3.Data.EventAttendee[] {
                                                new Google.Apis.Calendar.v3.Data.EventAttendee() { Email = "kaptan.cse@gmail.com" },
                                                new Google.Apis.Calendar.v3.Data.EventAttendee() { Email = emailAddress }
                                            };
                        #endregion

                        var newEventRequest = calendarService.Events.Insert(calenderEvent, calendar.Id);
                        newEventRequest.SendNotifications = true;
                        var eventResult = newEventRequest.Execute();
                        eventId = eventResult.Id;
                    }
                }
            }
            catch (Exception ex)
            {
                eventId = string.Empty;
                error = ex.Message;
            }
            return eventId;
        }
        public static Google.Apis.Calendar.v3.Data.Event UpdateCalenderEvents(string refreshToken, string emailAddress, string summary, DateTime? start, DateTime? end, string eventId, out string error)
        {
            Google.Apis.Calendar.v3.Data.Event eventResult = null;
            error = string.Empty;
            string serviceError;
            try
            {
                var calendarService = GetCalendarService(refreshToken, out serviceError);
                if (calendarService != null)
                {
                    var list = calendarService.CalendarList.List().Execute();
                    var calendar = list.Items.SingleOrDefault(c => c.Summary == emailAddress);
                    if (calendar != null)
                    {
                        // Define parameters of request
                        EventsResource.ListRequest request = calendarService.Events.List("primary");
                        request.TimeMin = DateTime.Now;
                        request.ShowDeleted = false;
                        request.SingleEvents = true;
                        request.MaxResults = 10;
                        request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

                        // Get selected event
                        Google.Apis.Calendar.v3.Data.Events events = request.Execute();
                        var selectedEvent = events.Items.FirstOrDefault(c => c.Id == eventId);
                        if (selectedEvent != null)
                        {
                            selectedEvent.Summary = summary;
                            selectedEvent.Start = new Google.Apis.Calendar.v3.Data.EventDateTime
                            {
                                DateTime = start
                            };
                            selectedEvent.End = new Google.Apis.Calendar.v3.Data.EventDateTime
                            {
                                DateTime = start.Value.AddHours(12)
                            };
                            selectedEvent.Recurrence = new List<string>();

                            // Set Remainder
                            selectedEvent.Reminders = new Google.Apis.Calendar.v3.Data.Event.RemindersData()
                            {
                                UseDefault = false,
                                Overrides = new Google.Apis.Calendar.v3.Data.EventReminder[]
                                {
                                                        new Google.Apis.Calendar.v3.Data.EventReminder() { Method = "email", Minutes = 24 * 60 },
                                                        new Google.Apis.Calendar.v3.Data.EventReminder() { Method = "popup", Minutes = 24 * 60 }
                                }
                            };

                            // Set Attendees
                            selectedEvent.Attendees = new Google.Apis.Calendar.v3.Data.EventAttendee[]
                            {
                                                    new Google.Apis.Calendar.v3.Data.EventAttendee() { Email = "kaptan.cse@gmail.com" },
                                                    new Google.Apis.Calendar.v3.Data.EventAttendee() { Email = emailAddress }
                            };
                        }

                        var updateEventRequest = calendarService.Events.Update(selectedEvent, calendar.Id, eventId);
                        updateEventRequest.SendNotifications = true;
                        eventResult = updateEventRequest.Execute();
                    }
                }
            }
            catch (Exception ex)
            {
                eventResult = null;
                error = ex.ToString();
            }
            return eventResult;
        }
        public static void DeletCalendarEvents(string refreshToken, string emailAddress, string eventId, out string error)
        {
            string result = string.Empty;
            error = string.Empty;
            string serviceError;
            try
            {
                var calendarService = GetCalendarService(refreshToken, out serviceError);
                if (calendarService != null)
                {
                    var list = calendarService.CalendarList.List().Execute();
                    var calendar = list.Items.FirstOrDefault(c => c.Summary == emailAddress);
                    if (calendar != null)
                    {
                        // Define parameters of request
                        EventsResource.ListRequest request = calendarService.Events.List("primary");
                        request.TimeMin = DateTime.Now;
                        request.ShowDeleted = false;
                        request.SingleEvents = true;
                        request.MaxResults = 10;
                        request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

                        // Get selected event
                        Google.Apis.Calendar.v3.Data.Events events = request.Execute();
                        var selectedEvent = events.Items.FirstOrDefault(c => c.Id == eventId);
                        if (selectedEvent != null)
                        {
                            var deleteEventRequest = calendarService.Events.Delete(calendar.Id, eventId);
                            deleteEventRequest.SendNotifications = true;
                            deleteEventRequest.Execute();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result = string.Empty;
                error = ex.ToString();
            }
        }

        public static void Run()
        {
            string refreshToken = string.Empty;
            string credentialError;
            var credential = GetUserCredential(out credentialError);
            if (credential != null && string.IsNullOrWhiteSpace(credentialError))
            {
                //Save RefreshToken into Database 
                refreshToken = credential.Token.RefreshToken;
            }

            string addEventError;
            string calendarEventId = string.Empty;

            calendarEventId = AddCalenderEvents(refreshToken, "kaptan.cse@gmail.com", "My Calendar Event", DateTime.Now, DateTime.Now.AddHours(12), out addEventError);

            string updateEventError;
            if (!string.IsNullOrEmpty(calendarEventId))
            {
                UpdateCalenderEvents(refreshToken, "kaptan.cse@gmail.com", "Modified Calendar Event ", DateTime.Now, DateTime.Now.AddDays(1), calendarEventId, out updateEventError);
            }

            string deleteEventError;
            if (!string.IsNullOrEmpty(calendarEventId))
            {
                DeletCalendarEvents(refreshToken, "kaptan.cse@gmail.com", calendarEventId, out deleteEventError);
            }
        }
    }