googleapis / google-api-dotnet-client

Google APIs Client Library for .NET
https://developers.google.com/api-client-library/dotnet
Apache License 2.0
1.36k stars 525 forks source link

Please Add Xamarin Forms Support #1173

Closed MelbourneDeveloper closed 6 years ago

MelbourneDeveloper commented 6 years ago

I would like to use the Google Calendar API from Xamarin Forms. I wasn't able to port the sample project to Xamarin Forms UWP, or Android. This is the code:

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);
        }
    }
}

I just get a non descriptive error on Windows 10 and Android. My guess is that the .NET Standard library is trying to pop up a browser window which would work fine from a .NET console app, but is failing on UWP, or Android.

Here is the repo. You will need to add your own client_secret.json resource file. https://ChristianFindlay@bitbucket.org/ChristianFindlay/xamarin-forms-scratch.git

I started a Stack Overflow question here: https://stackoverflow.com/questions/49102966/xamarin-google-calendar-sample/49186044#49186044

LindaLawton commented 6 years ago

Putting this here as it may help. There is someone who claims to have gotten this working.

https://stackoverflow.com/q/49397533/1841839 https://stackoverflow.com/a/44444388/1841839

https://github.com/dbelcher/TestXamAuthGoogleDrive/blob/master/TestXamAuthGoogleDrive/GoogleDriveAgent.cs#L169

My comment would be that it looks like he has a client id and client secret which would lead me to believe that he made browser or native credentials on the developer console. Now i wonder about the security of using native or browser credentials in a mobile app when your superposed to be using a different auth flow.

Nope i haven't tested it but in theory it looks like it would work.

chrisdunelm commented 6 years ago

Thanks @LindaLawton for the ideas.

@MelbourneDeveloper Xamarin is not currently supported, although we will take note of your request to support the platform. Closing this issue.