使用C#访问公开的Google日历

时间:2015-05-22 13:37:08

标签: c# google-calendar-api google-api-dotnet-client

我有一个WPF应用程序,想要访问我已添加到我的Google帐户的公共Google日历,以便查找即将举办的活动。我使用quickstart provided by Google,但我无法弄清楚如何选择我想要访问的日历。如何选择从哪个日历获取活动?

更新:将代码和解决方案移至a separate answer

2 个答案:

答案 0 :(得分:1)

使用CalenderList API获取日历列表。

根据documentation

  

日历列表 - 日历用户界面中用户日历列表中所有日历的列表。

向下滚动你会发现:

  

关于calendarList条目资源

     

用户日历列表中的日历是在我的日历或其他日历下的Google日历网络界面中可见的日历:

答案 1 :(得分:1)

事实证明,访问日历很简单!我只需要更改<{p>中的primary

EventsResource.ListRequest request = service.Events.List("primary");

到我要访问的日历的日历ID。现在我可以从主日历中获取活动了!

解决方案:

public class GoogleCalendar
{
    static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
    static string ApplicationName = "Calendar API Quickstart";


    public static string GetEvents()
    {
        UserCredential credential = Login();

        return GetData(credential);
    }

    private static string GetData(UserCredential credential)
    {
        // Create Calendar Service.
        var service = new CalendarService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });

        // Define parameters of request.
        EventsResource.ListRequest request = service.Events.List("The calendar ID to the calender I want to access");
        request.TimeMin = DateTime.Now;
        request.ShowDeleted = false;
        request.SingleEvents = true;
        request.MaxResults = 10;
        request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

        Console.WriteLine("Upcoming events:");
        Events events = request.Execute();
        if (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.");
        }
        return "See console log for upcoming events";
    }

    static UserCredential Login()
    {
        UserCredential credential;

        using (var stream = new FileStream(@"Components\client_secret.json", FileMode.Open,
            FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(System.Environment
              .SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials");

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
               GoogleClientSecrets.Load(stream).Secrets,
              Scopes,
              "user",
              CancellationToken.None,
              new FileDataStore(credPath, true)).Result;
        }

        return credential;
    }
}