带有 ASP.NET 的 Google 日历 API

2024-04-09

我对使用 Google Calendar API 在 ASP.NET Webforms (C#) 中添加/修改事件感到困惑。

我不确定我是否需要 oAuth 或者什么。我的应用程序位于我自己的服务器上,访问我自己的域和我自己的日历。我不需要其他用户允许我访问他们的日历;我只需要通过我的应用程序访问我自己的。

在我的 aspx 页面之一上,我想将事件信息发送到我的 Google 日历以添加(或稍后修改)事件。

我检查了各种代码示例和 Google 入门指南。我只是不清楚到底需要什么。我已经设置了 API 密钥和 oAuth2 客户端 ID。谷歌的指示让我陷入了困境,这可能是因为我需要澄清需要什么。

有人可以澄清我的困惑并指出我正确的方向吗?


概括 :

  • 调用 google cloud oauth2 受保护资源

  • 从您的服务器到谷歌服务器

  • 无需用户交互

  • 访问您自己的数据

  • 使用C#

Code :

    var private_key = @"-----BEGIN PRIVATE KEY-ccc-END PRIVATE KEY-----\n";
    string calendarId = @"[email protected] /cdn-cgi/l/email-protection";
    var client_email = @"[email protected] /cdn-cgi/l/email-protection";

    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获取数据的方法

  • 私钥和 client_email 可以从以下位置生成这个链接 https://console.developers.google.com/projectselector/iam-admin/serviceaccounts/create?supportedpurview=project

  • 日历 ID 可以在 calendar.google.com 上找到

  • 您必须与 client_email 共享您的日历看演示


  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

逐步演示


步骤01:打开谷歌控制台

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

步骤02:点击选择

步骤03:选择或创建一个新项目

步骤04:点击启用或管理

步骤05:点击凭证

步骤06:创建服务帐户密钥

步骤07:输入服务帐户名称点击创建

步骤08:点击创建无角色然后将下载的json私钥保存在安全的地方

第 09 步:复制您的 client_email

第10步:打开谷歌日历

  • 日历.google.com

第 11 步:打开日历设置和共享

第12步:必须与特定人员分享然后点击添加

Step 13:

  1. 添加您之前复制的服务帐户的电子邮件step 09
  2. 也更改权限进行更改并管理共享
  3. 单击发送

第14步:在同一页面上复制并保存日历ID我们会需要它

第 15 步:创建新的控制台应用程序

第16步:将私钥json文件添加到您的项目中

第 17 步:右键单击私钥 json,然后单击“属性”

步骤 18:将“复制到输出目录”更改为“始终复制”

第 19 步:打开 PM Console 并在默认项目 D 上选择您的项目

第20步:安装Google.Apis日历包

Install-Package Google.Apis.Calendar.v3

第21步:用代码替换Program.cs

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 = @"[email protected] /cdn-cgi/l/email-protection";

            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 = "[email protected] /cdn-cgi/l/email-protection"},
                        new EventAttendee() { Email = "[email protected] /cdn-cgi/l/email-protection"}
                    }
                }
             };
    }
}

步骤 22:将 json 文件名替换为您的 json 文件名

  string jsonFile = "xxxxxxx-xxxxxxxx.json";

步骤 23:将 calendarId 替换为步骤 14 中的 calendarId

 string calendarId = @"[email protected] /cdn-cgi/l/email-protection";

第 24 步:运行应用程序

第 25 步:访问您的日历,您应该会在其中看到该事件

 2019/01/13
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带有 ASP.NET 的 Google 日历 API 的相关文章

随机推荐

  • 防止 Google Play 上的虚假评论 [关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 我将 Android 应用程序发布到 Google Play 一切都很好 我收到了大约 5000 条用户评论 平均分为 4 6 分 但在某个时刻 我开
  • 如果 URL 参数很长,控制器操作不会调用

    仅供参考 我的问题不是重复的MVC 3 中的长 url 为 404 20 https stackoverflow com questions 20798392 404 20 for long url in mvc 3所以请不要混淆 我有一个
  • 谁在为kafka集群设置授权

    我有一个 3 节点 Kafka 集群和 2 个用于生产者和消费者的 kafka 客户端 我已启用 SSL 身份验证 我想为集群启用授权 我已在代理节点的 server properties 中添加了以下属性 authorizer class
  • 检测不同分辨率下的图像相等性

    我正在尝试构建一个脚本来浏览我的原始高分辨率照片 并替换我在拥有专业帐户之前上传到 Flickr 的旧的低分辨率照片 对于其中许多 我可以只使用 Exif 信息 例如拍摄日期 来确定匹配 但有些确实很旧 要么原始文件没有 Exif 信息 要
  • 如何使用java从linux环境获取tomcat中当前目录的相对路径

    我想用来从我的网络应用程序外部读取属性文件 我在 Windows 环境中的 tomcat 中部署了一个 war 文件 并且可以使用以下代码从 Web 应用程序外部读取属性文件 Method 1 String filePath new jav
  • Android OpenCV 并行化循环

    我知道 OpenMP 包含在 NDK 中 使用示例如下 http recursify com blog 2013 08 09 openmp on android http recursify com blog 2013 08 09 open
  • 通过转发构造函数参数构建基于可变参数模板的 mixin

    我正在尝试构建一个 mixin 模板 其基础全部作为可变参数模板参数传递 我想通过将每个 mixin 类的构造函数参数作为参数传递给可变参数模板构造函数来构造 mixin 当使用每个 mixin 类类型的对象调用时 可变参数模板构造函数会进
  • 在 Objective-C 中观察文件或文件夹

    侦听文件夹或文件以查看其是否已保存或是否已添加新文件的最佳方法是什么 如果您只想监视目录但不处理单个文件的监视 那么 FSEvents API 是理想的选择 Stu Connolly 有一个很棒的 FSEvents C API 的 Obje
  • 如何使用“%f”将双精度值填充到具有正确精度的字符串中

    我正在尝试使用 a 来填充带有双精度值的字符串sprintf像这样 sprintf S f val 但精度被截断至小数点后六位 我需要大约 10 位小数来保证精度 如何才能做到这一点 宽度 精度 宽度应包括小数点 8 2表示8个字符宽 点前
  • UIButton 在 UIScrollView 中时不起作用

    我的观点结构 UITableView UITableViewCell UIScrollView CustomView UIButton 问题是当我触摸 UIButton 时它不起作用 我用代码创建它 btn UIButton alloc i
  • 继续打开 OpenFileDialog 直到选择有效文件

    我有打开 OpenFileDialog 的代码 我正在检查文件的大小以确保它不超过特定限制 但是 如果用户选择了一个大尺寸的文件 我需要警告他并引导他返回对话框以选择不同的文件或单击 取消 这是我尝试过的 OpenFileDialog di
  • 获取 PHP 中动态选择的类常量的值

    我希望能够做这样的事情 class ThingIDs const Something 1 const AnotherThing 2 thing Something id ThingIDs thing 这是行不通的 有没有一种简单的方法可以做
  • 调试 Windows 消息内容和目标的好方法是什么?

    我正在开发一个基于其他行为模拟 Windows 鼠标的应用程序 一个示例是按键盘上的 或 键将 WM MOUSEWHEEL 消息发送到具有适当增量的目标窗口 问题是 在某些情况下 我很难复制那些消息i thinkwindows 正在发送到目
  • CUDA:如何检查计算能力是否正确?

    使用较高计算能力编译的 CUDA 代码将在计算能力较低的设备上完美执行很长一段时间 然后有一天在某些内核中默默地失败 我花了半天时间追寻一个难以捉摸的错误 结果发现构建规则已经sm 21而该设备 Tesla C2050 是2 0 是否有任何
  • 如何在 HTML 中打印每个项目之间有延迟的列表

    Id for each item p p p p p p
  • 如何在 Asp.Net-MVC 中添加自定义 HTTP 标头

    我创建了一个自定义处理程序 如下所示 public class SitHandler DelegatingHandler protected override async Task
  • facebook php,如何使用结果分页?

    您好 我正在使用 Facebook PHP SDK v 3 1 1 我不明白如何使用结果分页 url 我想获取我所有朋友的列表 这是我的代码 friends fb gt api me friends friend Array data gt
  • Invalid Uri : uri 方案无效

    我正在尝试通过 WebRequest 登录网站 我此时遇到异常 WebRequest req WebRequest Create formUrl Trim string url string username string password
  • iOS 6 中使用 AudioFileServices 进行粒度合成

    我对我正在开发的声音合成应用程序有疑问 我正在尝试读取音频文件 使用创建随机 颗粒 颗粒合成技术 http en wikipedia org wiki Granular synthesis 将它们放入输出缓冲区 然后能够使用 OpenAL
  • 带有 ASP.NET 的 Google 日历 API

    我对使用 Google Calendar API 在 ASP NET Webforms C 中添加 修改事件感到困惑 我不确定我是否需要 oAuth 或者什么 我的应用程序位于我自己的服务器上 访问我自己的域和我自己的日历 我不需要其他用户