如何使用Visual Studio连接到Google日历的API? (C#)

时间:2016-04-13 21:06:45

标签: c# google-calendar-api

我花了更多的时间来研究这个话题而不是我想承认,但是这些指令对我来说非常复杂。我正在开发一个带有日历GUI的程序,用户可以在其中选择一天,并键入他/她当天可能拥有的事件。完成后,我希望能够将用户的数据导入到我创建的Google日历中。我怎样才能做到这一点?如果可以,我会非常感谢简单的回答,因为我是学生,而不是专业人士。谢谢!

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

I was able to follow the Google Calendar API .NET Quickstart Guide to add a Google Calendar integration to an ASP.NET MVC application.

Essentially, you will need to download an authentication file (either JSON or P12) from the Google Developer's Console and use it to create a credential:

using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
   string credPath = @"/location/to/store/credentials"
   UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
   GoogleClientSecrets.Load(stream).Secrets,
   CalendarService.Scope.Calendar,
   "user",
   CancellationToken.None,
   new FileDataStore(credPath, true)).Result;
}

With the default settings in the developer's console, you'll end up launching an OAuth 2.0 authentication pop-up each time you need permission from a new user. If they give you permission in that screen, use the credential to authorize a CalendarService object:

// Create Google Calendar API service.
var service = new CalendarService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "Your Cool Calendar Application",
});

The service will then allow you to execute Create/Read/Update/Delete requests for the user you are currently authenticated for:

Event newEvent = new Event()
{
    Summary = "new event",
    Start = new EventDateTime()
    {
        DateTime = DateTime.Parse("2016-07-11T09:00:00"),
        TimeZone = "America/Los_Angeles"
    },
    End = new EventDateTime()
    {
        DateTime = DateTime.Parse("2016-07-11T10:00:00"),
        TimeZone = "America/Los_Angeles"
    }
};

Event createdEvent = service.Events.Insert(newEvent, "primary").Execute();

You can find more information about what events are available for different Google Calendar objects in the API documentation and more information on the .NET wrappers here (though the .NET examples aren't very complete; you're better off looking at SO). You can create these objects from anywhere in your application.