【问题标题】:Xamarin Google Calendar SampleXamarin Google 日历示例
【发布时间】:2018-03-05 03:11:23
【问题描述】:

我正在尝试让此示例与 Xamarin(Xamarin 表单)一起使用

https://developers.google.com/google-apps/calendar/quickstart/dotnet

我修改了代码,以便 Xamarin Forms 应用程序可以从资源文件加载凭据 json。我通过单步执行代码检查了资源文件是否正在加载。我还修改了 DataStore 类,因为 Xamarin Forms 无法访问示例中指定的路径。

using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TestXamarinFormsLibrary.Pages
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class CalendarPage : ContentPage
    {
        public CalendarPage()
        {
            InitializeComponent();
            Go();
        }

        static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
        static string ApplicationName = "Google Calendar API .NET Quickstart";

        private async void Go()
        {
            UserCredential credential;

            var assembly = GetType().Assembly;
            using (var stream = assembly.GetManifestResourceStream("TestXamarinFormsLibrary.client_secret.json"))
            {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new DataStore()).Result;
            }

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

            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List("primary");
            request.TimeMin = DateTime.Now;
            request.ShowDeleted = false;
            request.SingleEvents = true;
            request.MaxResults = 10;
            request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

            // List events.
            Events events = request.Execute();
            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;
                    }
                    await DisplayAlert("ok", $"{eventItem.Summary} ({when})", "ok");
                }
            }
        }
    }

    public class DataStore : IDataStore
    {
        private Dictionary<string, object> Data = new Dictionary<string, object>();

        public Task ClearAsync()
        {
            throw new NotImplementedException();
        }

        public Task DeleteAsync<T>(string key)
        {
            throw new NotImplementedException();
        }

        public async Task<T> GetAsync<T>(string key)
        {
            if (Data.ContainsKey(key))
            {
                return (T)Data[key];
            }

            return default(T);
        }

        public async Task StoreAsync<T>(string key, T value)
        {
            Data.Add(key, value);
        }
    }
}

这是我运行时遇到的错误:

也不例外。我在 Android 上遇到类似的错误。我的猜测是它依赖 oAuth 库来打开 Web 浏览器,以尝试允许身份验证,但 Xamarin Forms 没有实现此行为。我也尝试过打开所有 UWP 功能,但这没有帮助。

如何让 Xamarin Forms 运行示例?

【问题讨论】:

  • 假设您正在创建一个控制台应用程序,calendar-dotnet-quickstart.json 是成功登录后由GoogleWebAuthorizationBroker.AuthorizeAsync 方法创建的凭据输出文件。它的位置实际上并不重要,因为它的位置在使用的 UserCredential 对象中维护,但它应该是用户/应用程序私有的,因为它确实包含在登录期间授予的授权范围。
  • 这不是控制台应用程序。我正在尝试让它在 Xamarin Forms 中工作。
  • 我在 Xamarin.iOS 和 Xamarin.Android 中使用了本机 Google Cal API,在 Xamarin.Forms|iOS|Android|UWP 中使用了 Rest API。上次我查看 Dotnet 库不支持 UWP(有一堆与此相关的 SO 问题/答案),但我有一段时间没有检查到最后,所有高级 Google Cal。 SDK 使用 Rest API,这就是我现在使用的(也像许多 Google 高级 SDK 一样,它们不会 100% 公开 Rest API 功能集(Calendar / OneDrive SDK 是主要示例,如果您需要那些缺少的功能,你必须去 REST API 级别
  • 您发布的链接描述了控制台应用程序的步骤,如果您向下滚动到底部有一个 webapp 链接,也许这就是您所需要的?
  • 该示例非常愚蠢,因为它将内容存储在文件中,并向我隐藏内容。我宁愿使用这个库而不是 REST。他们把这个库设计得如此糟糕,这很烦人。

标签: c# xamarin uwp google-calendar-api


【解决方案1】:

.NET 客户端的 repo 在这里: https://github.com/google/google-api-dotnet-client

我想我可以从源代码中弄清楚这一点,但我还没有尝试过。

【讨论】:

    【解决方案2】:

    我的 UWP 应用中有 Google .NET 客户端。诀窍是您必须将其放入 .NET Standard 2.0 类库中,公开您需要的 API 服务,然后从您的 UWP 应用程序中引用该库。

    此外,您必须自己处理获取身份验证令牌。这不是很多工作,Drive API 和 Calendar API 工作得很好(我唯一尝试过的)。您可以看到,我将一个包含身份验证令牌和其他身份验证详细信息的简单类传递给了一个名为 Initialize 的方法。

    这是我在 .NET Standard 2.0 类库中使用的单个类:

    namespace GoogleProxy
    {
    public class GoogleService
    {
        public CalendarService calendarService { get; private set; }
    
        public DriveService driveService { get; private set; }
    
    
        public GoogleService()
        {
    
        }
    
        public void Initialize(AuthResult authResult)
        {
            var credential = GetCredentialForApi(authResult);
            var baseInitializer = new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "{your app name here}" };
    
            calendarService = new Google.Apis.Calendar.v3.CalendarService(baseInitializer);
            driveService = new Google.Apis.Drive.v3.DriveService(baseInitializer);
        }
    
        private UserCredential GetCredentialForApi(AuthResult authResult)
        {
            var initializer = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId = "{your app client id here}",
                    ClientSecret = "",
                },
                Scopes = new string[] { "openid", "email", "profile",  "https://www.googleapis.com/auth/calendar.readonly", "https://www.googleapis.com/auth/calendar.events.readonly", "https://www.googleapis.com/auth/drive.readonly" },
            };
    
            var flow = new GoogleAuthorizationCodeFlow(initializer);
    
            var token = new TokenResponse()
            {
                AccessToken = authResult.AccessToken,
                RefreshToken = authResult.RefreshToken,
                ExpiresInSeconds = authResult.ExpirationInSeconds,
                IdToken = authResult.IdToken,
                IssuedUtc = authResult.IssueDateTime,
                Scope = "openid email profile https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar.events.readonly https://www.googleapis.com/auth/drive.readonly",
                TokenType = "bearer" };
    
            return new UserCredential(flow, authResult.Id, token);
        }
    
    }
    }
    

    UWP 的完整答案在这里: https://stackoverflow.com/a/53971436/1938624

    【讨论】:

      猜你喜欢
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 2012-06-15
      相关资源
      最近更新 更多