首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用C# / .NET在G日历中创建事件的最简单方法是什么

使用C# / .NET在G日历中创建事件的最简单方法是什么
EN

Stack Overflow用户
提问于 2022-02-25 14:58:35
回答 2查看 1K关注 0票数 1

问题解决方案:我正在使用c# / .NET构建一个窗口表单,并且我想添加一个功能来在我的个人Google日历中添加一个事件。我已经在互联网上研究了几天了,但我发现的每一个解决方案似乎都被夸大了。

我只需要:

代码语言:javascript
运行
复制
event title = textbox1.text;
event description = textbox2.text;
event date = datetimepicker.text;
addEvent();

但我不知道如何编写它,也找不到任何简单的解决方案(大多数解决方案都过于复杂)。我可以说,我有一些业余爱好编码经验,足以建立一个简单的项目,但我承认,这是超出我的水平,我需要一些指导。

我想我已经设置了Calendar API和Google。还在Visual中安装了Google包,但是如果有方法通过密码和用户名来连接,而不是API & SDK,我会很感激。

提前感谢!

!解决方案!

在@Dalmto的最初帮助下,我设法将他的代码链接到一个按钮上,并使它实际上触发了一个事件,因为以前它没有。

下面是我的最后一段代码,您可以简单地将其用作复制粘贴。把你的证件加进去。

代码语言:javascript
运行
复制
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.IO;
using System.Threading;
using Google.Apis.Calendar.v3.Data;


namespace googleCalendarTesting
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string clientSecretJson = ""; //add your json path here
            string userName = ""; // add your google account here
            string[] scopes = new string[n] {"n1", "n2", "n3" }; // replace n with the number of scopes you need and write them one by one
            CalendarService service = GetCalendarService(clientSecretJson, userName, scopes);

            Event newEvent = new Event()
            {
                Summary = "event title",
                Description = "event description",
                Start = new EventDateTime()
                {
                    DateTime = DateTime.Parse("2022-02-28T09:00:00-07:00"),
                    TimeZone = "America/Los_Angeles",
                },
                End = new EventDateTime()
                {
                    DateTime = DateTime.Parse("2022-02-28T09:00:00-08:00"),
                    TimeZone = "America/Los_Angeles",
                },
            }; //// more options here https://developers.google.com/calendar/api/v3/reference/events/insert#.net

            String calendarId = "primary"; // choose a calendar in your google account - you might have multiple calendars
            EventsResource.InsertRequest request = service.Events.Insert(newEvent, calendarId);
            Event createdEvent = request.Execute();
        }
        public static CalendarService GetCalendarService(string clientSecretJson, string userName, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(userName))
                    throw new ArgumentNullException("userName");
                if (string.IsNullOrEmpty(clientSecretJson))
                    throw new ArgumentNullException("clientSecretJson");
                if (!File.Exists(clientSecretJson))
                    throw new Exception("clientSecretJson file does not exist.");

                var cred = GetUserCredential(clientSecretJson, userName, scopes);
                return GetService(cred);

            }
            catch (Exception ex)
            {
                throw new Exception("Get Calendar service failed.", ex);
            }
        }

        private static UserCredential GetUserCredential(string clientSecretJson, string userName, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(userName))
                    throw new ArgumentNullException("userName");
                if (string.IsNullOrEmpty(clientSecretJson))
                    throw new ArgumentNullException("clientSecretJson");
                if (!File.Exists(clientSecretJson))
                    throw new Exception("clientSecretJson file does not exist.");

                // These are the scopes of permissions you need. It is best to request only what you need and not all of them               
                using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
                {
                    string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

                    // Requesting Authentication or loading previously stored authentication for userName
                    var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                             scopes,
                                                                             userName,
                                                                             CancellationToken.None,
                                                                             new FileDataStore(credPath, true)).Result;

                    credential.GetAccessTokenForRequestAsync();
                    return credential;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Get user credentials failed.", ex);
            }
        }

       private static CalendarService GetService(UserCredential credential)
        {
            try
            {
                if (credential == null)
                    throw new ArgumentNullException("credential");

                // Create Calendar API service.
                return new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Calendar Oauth2 Authentication Sample"
                });
            }
            catch (Exception ex)
            {
                throw new Exception("Get Calendar service failed.", ex);
            }
        }
    }
}

我在项目中使用的范围:

代码语言:javascript
运行
复制
https://www.googleapis.com/auth/calendar,  
https://www.googleapis.com/auth/calendar.events,
https://www.googleapis.com/auth/calendar.events.readonly  
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-02-25 16:18:47

如果有办法用密码和用户名来连接,而不是API & SDK,我会很感激。

不,这叫做客户端登录,谷歌在2015年关闭了这个选项。

我想添加一个功能,以添加事件在我的个人谷歌日历。

我将假设个人谷歌日历,你指的是一个标准的gmail帐户谷歌日历。

为此,您将需要使用Oauth2请求脱机访问一次授权您的应用程序。之后,您应该存储一个刷新令牌。

这方面的代码可以合理地向前推进。

Oauth2Authentication.cs

代码语言:javascript
运行
复制
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.IO;
using System.Threading;

namespace GoogleSamplecSharpSample.Calendarv3.Auth
{
    public static class Oauth2Example
    {
        /// <summary>
        /// ** Installed Aplication only ** 
        /// This method requests Authentcation from a user using Oauth2.  
        /// </summary>
        /// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
        /// <param name="userName">Identifying string for the user who is being authentcated.</param>
        /// <param name="scopes">Array of Google scopes</param>
        /// <returns>CalendarService used to make requests against the Calendar API</returns>
        public static CalendarService GetCalendarService(string clientSecretJson, string userName, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(userName))
                    throw new ArgumentNullException("userName");
                if (string.IsNullOrEmpty(clientSecretJson))
                    throw new ArgumentNullException("clientSecretJson");
                if (!File.Exists(clientSecretJson))
                    throw new Exception("clientSecretJson file does not exist.");

                var cred = GetUserCredential(clientSecretJson, userName, scopes);
                return GetService(cred);

            }
            catch (Exception ex)
            {
                throw new Exception("Get Calendar service failed.", ex);
            }
        }

        /// <summary>
        /// ** Installed Aplication only ** 
        /// This method requests Authentcation from a user using Oauth2.  
        /// Credentials are stored in System.Environment.SpecialFolder.Personal
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
        /// <param name="userName">Identifying string for the user who is being authentcated.</param>
        /// <param name="scopes">Array of Google scopes</param>
        /// <returns>authencated UserCredential</returns>
        private static UserCredential GetUserCredential(string clientSecretJson, string userName, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(userName))
                    throw new ArgumentNullException("userName");
                if (string.IsNullOrEmpty(clientSecretJson))
                    throw new ArgumentNullException("clientSecretJson");
                if (!File.Exists(clientSecretJson))
                    throw new Exception("clientSecretJson file does not exist.");

                // These are the scopes of permissions you need. It is best to request only what you need and not all of them               
                using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
                {
                    string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

                    // Requesting Authentication or loading previously stored authentication for userName
                    var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                             scopes,
                                                                             userName,
                                                                             CancellationToken.None,
                                                                             new FileDataStore(credPath, true)).Result;

                    credential.GetAccessTokenForRequestAsync();
                    return credential;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Get user credentials failed.", ex);
            }
        }

        /// <summary>
        /// This method get a valid service
        /// </summary>
        /// <param name="credential">Authecated user credentail</param>
        /// <returns>CalendarService used to make requests against the Calendar API</returns>
        private static CalendarService GetService(UserCredential credential)
        {
            try
            {
                if (credential == null)
                    throw new ArgumentNullException("credential");

                // Create Calendar API service.
                return new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Calendar Oauth2 Authentication Sample"
                });
            }
            catch (Exception ex)
            {
                throw new Exception("Get Calendar service failed.", ex);
            }
        }
    }
}

此代码将将凭据存储到您的个人google日历帐户中的文件中,该文件位于计算机上的credPath目录中。如果要将该目录存储在服务器上,则可能需要更改它。

当您第一次运行它(我建议在本地执行此操作)时,它将使用刷新令牌填充该文件。然后,代码将使用刷新令牌在需要时请求新的访问令牌。

一些关于这个的笔记。您需要在google云控制台中将项目设置为生产,否则刷新令牌只有效7天。您还必须确保每六个月使用一次此刷新令牌,否则它将过期。如果未能加载刷新令牌,则此代码将失败,因为它是为已安装的应用程序设计的。这可能是一件好事,因为你没有一个网络托管的应用程序请求用户同意他们的个人谷歌日历帐户。

服务帐户票据。

大多数google支持所谓的服务帐户身份验证。它用于预先授权帐户访问。Google日历只支持对Google工作区帐户的服务帐户授权,而不支持标准gmail帐户。

如果你想用一个服务帐户来做这件事,那就更容易了,但是同样的,你需要注册一个工作区帐户,然后你只能使用它,而不是标准的gmail帐户。

票数 1
EN

Stack Overflow用户

发布于 2022-02-25 15:13:19

您需要一个来自(https://console.developers.google.com/apis/dashboard?pli=1)的API密钥,以便连接到日历,并将事件读写到日历上。普通用户名和密码将无法工作(据我所知)。Google的文档非常直接,并解释了每个步骤,以便从API中检索事件。https://developers.google.com/calendar/api/quickstart/dotnet

在了解了SDK之后,您可以增强应用程序将事件添加到日历中。如果我有时间,我将链接我的GitHub Repos中的一个例子,您可以参考。

编辑:正如DalmTo提到的,我没有创建API密钥。我在开发人员仪表板上创建了客户端凭据。快速启动指南中也提到了如何创建这些凭据。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71267723

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档