Login Login
MORE

WIDGETS

Widgets

Wanted articles
Who is online?
Article tools

CSharp:Google Calendar

From Aino Wiki

Jump to: navigation, search

Introdzione

Esempio pilota

Si espone una semplice applicatione Windows Form che inserisce un nuovo evento nel Calendar di un utente.
Puunti salienti sono (| dettagli):

  • Prima di procedere occorre creare il file "credential.json" usando il tool on-line Google Developers console. Questo file è la chiave di accesso al servizio particolare di Google.
Autorizzazione uso Servizi Google 11.jpg
  • Grazie alla chiave creata al punto precedente, in associazione alla chiave costruita nel punto precedente, verrà generato un file "token.json" che per la prima volta richiede una interazione con l'utente attraverso specifica pagina web che si aprirà in automatico. A parità di file "Credential.json" se si cambia user verrà cambiato il file token.json con la solità conferma da fare sulla stessa pagina Web.

Segue un esempio di creazione del file Toke:

Token user Servizi Google 01.jpg

Segue la richiesta di autorizzazione alla prima esecuzione col nuovo utente:

Autorizzazione uso Servizi Google 13 creazione file token.jpg

Nel caso lo utilizzi un utente diverso da te si chiederà una autorizzazione specifica all'applicazione:

Autorizzazione uso Servizi Google 13 utente di test.jpg
  • Al progetto vanno aggiunte le librerie Google "Google.Apis".
Prj esempio Google Calendar 01.jpg

Classe helper

Al progetto si aggiunge la seguente classe di helper che sarà usata nella Form, "OAuth2Google_Helper.cs":

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 WF_GoogleCalendar
{
    public static class OAuth2Google_Helper
    {
        private static string c_CredTokenFileName = "token.json";
 
        /// <summary>
        /// Restituisce la classe dei servizi Calendar di Google e richiede lautenticazione e usa l'OAuth2.  
        /// </summary>
        /// <param name="cliSecretJsonFilePath">Path del client secret json file costruito dalla Google Developers console.</param>
        /// <param name="userName">Nome utente che si stà autenticando.</param>
        /// <param name="scopes">Array di Google scopes</param>
        /// <returns>CalendarService usato per fare richieste alla Calendar API</returns>
        public static CalendarService GetCalendarService(string cliSecretJsonFilePath, string userName,
                                                        string applicationName, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(userName))
                    throw new ArgumentNullException("userName");
                if (string.IsNullOrEmpty(cliSecretJsonFilePath))
                    throw new ArgumentNullException("clientSecretJson");
                if (!File.Exists(cliSecretJsonFilePath))
                    throw new Exception("clientSecretJson file does not exist.");
 
                UserCredential cred = GetUserCredential(cliSecretJsonFilePath, userName, scopes);
                if (cred == null)
                    throw new Exception("UserCredential is null. Authentication failed.");
 
                CalendarService calendarService = GetService(cred, applicationName);
                if (calendarService == null)
                    throw new Exception("CalendarService is null. Service creation failed.");
 
                return calendarService;
 
            }
            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="cliSecretJsonFilePath">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 it is best to request only what you need and not all of them</param>
        /// <returns>authencated UserCredential</returns>
        private static UserCredential GetUserCredential(string cliSecretJsonFilePath, string userName, string[] scopes)
        {
        /*  Esempio di file Json di credenziali per il servizio
             {
                "installed": {
                                "client_id":"309572305793247-kdfvnòlsdfvdfvlsdnfdfnvn.apps.googleusercontent.com",
                                "project_id":"xxxxxxx-1231231321313121",
                                "auth_uri":"https://accounts.google.com/o/oauth2/auth",
                                "token_uri":"https://oauth2.googleapis.com/token",
                                "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
                                "client_secret":"sdfsdfgvbsdfgbsdfgb",
                                "redirect_uris":["urn:ietf:wg:oauth:2.0:oob",
                                "http://localhost"]
                              }
            }
         */
            try
            {
                if (string.IsNullOrEmpty(userName))
                    throw new ArgumentNullException("userName");
                if (string.IsNullOrEmpty(cliSecretJsonFilePath))
                    throw new ArgumentNullException("clientSecretJson");
                if (!File.Exists(cliSecretJsonFilePath))
                    throw new Exception("clientSecretJson file does not exist.");
 
                // Si legge il file json delle credenziali del client (è generato dalla Google Developers console
                // a questo URL:        https://console.developers.google.com  )
                // NOTA Dopo aver aggiunto nella root del progetto il file "credentials.json" IMPOSTARE
                //      la property del file a "Copy always" !!!
                using (var stream = new FileStream(cliSecretJsonFilePath, FileMode.Open, FileAccess.Read))
                {
                    //string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    //credPath = Path.Combine(credPath
                    //                    , ".credentials/"
                    //                    , System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
 
                    // The file token in credFileTokenFullPath (token.json) stores the user's access and refresh tokens, 
                    // and is created automatically when the authorization flow completes for the first time.
                    string credFileTokenFullPath = c_CredTokenFileName;
                    // Requesting Authentication or loading previously stored authentication for userName
                    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                             scopes,
                                                                             userName, //Es. user
                                                                             CancellationToken.None,
                                                                             new FileDataStore(credFileTokenFullPath, 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, string applicationName)
        {
            try
            {
                if (credential == null)
                    throw new ArgumentNullException("credential");
 
                // Create Calendar API service.
                CalendarService gCalendarService = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = applicationName
                });
 
                //gCalendarService.HttpClient.Timeout = TimeSpan.FromMinutes(10);
                return gCalendarService;
            }
            catch (Exception ex)
            {
                throw new Exception("Get Calendar service failed.", ex);
            }
        }
    }
}

Progetto

Il progetto e i due file chiave rispondono al seguente schema:

Prj esempio Google Calendar 03.jpg

Il Form

Il form è così fatto:

Prj esempio Google Calendar 02.jpg
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Calendar.v3;
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;
 
namespace WF_GoogleCalendar
{
    public partial class FrmMain : Form
    {
        public static string[] c_GoogleServiceScopes = {
            CalendarService.Scope.Calendar,            // Calendar API scope
            CalendarService.Scope.CalendarEventsOwned, // Calendar Events Owned scope
            //? CalendarService.Scope.CalendarCalendars,
            //? CalendarService.Scope.CalendarCalendarlist, 
        };
 
        public static string c_ApplicationName = "WF_GoogleCalendar"; // Set your application name here
 
        public FrmMain()
        {
            InitializeComponent();
        }
 
        private void BtnInsertNewEvent_Click(object sender, EventArgs e)
        {
            string clientSecretJson = "credentials.json";   //  Json file with credential path
 
            // NOTA lo userName può essere qualsiasi (anche non esistente su Google), quel che è determinante è la scelta che 
            //      si fa la prima volta che ci si connette con successo al servizio perché è in quel momento che si è guidati
            //      nella scelta di uno user di Google. In questa prima fase si genererà un file "TOKEN" che è associato allo 
            //      user scelto.
            string userName = FrmMain_Txt_User.Text.Trim();                //  User google account
 
 
            string eventTitle = FrmMain_Txt_EventTitle.Text.Trim();
            string eventDescription = FrmMain_Txt_EventDescription.Text.Trim();
            try
            {
                if (FrmMain_DtPick_From.Value >= FrmMain_DtPick_To.Value)
                {
                    MessageBox.Show("La data e ora di partenza NON piò esser superiore o uguale a quella di arrivo!"
                                , "BtnInsertNewEvent_Click", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
 
 
                // c_GoogleServiceScopes array con gli scopes (ambiti) di permesso necessari
                CalendarService service = OAuth2Google_Helper.GetCalendarService(clientSecretJson, userName
                                                                                , c_ApplicationName, c_GoogleServiceScopes);
                Event newEvent = new Event()
                {
                    Summary = eventTitle,
                    Description = eventDescription,
                    Start = new EventDateTime()
                    {
                        //DateTimeDateTimeOffset = DateTimeOffset.Parse("2025-05-25T09:00:00-07:00"), //18:00
                        DateTimeDateTimeOffset = FrmMain_DtPick_From.Value,
                        TimeZone = "Europe/Rome", // Es.: "America/Los_Angeles",
                    },
                    End = new EventDateTime()
                    {
                        //DateTimeDateTimeOffset = DateTimeOffset.Parse("2025-05-25T09:00:00-08:00"), //19:00
                        DateTimeDateTimeOffset = FrmMain_DtPick_To.Value,
                        TimeZone = "Europe/Rome", // Es.: "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();
 
                MessageBox.Show("OK. Evento \"" + eventTitle + "\" inserito", "BtnInsertNewEvent_Click"
                                , MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "BtnInsertNewEvent_Click", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

Il file ***Designer.cs :

namespace WF_GoogleCalendar
{
    partial class FrmMain
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
 
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
 
        #region Windows Form Designer generated code
 
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.BtnInsertNewEvent = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.FrmMain_Txt_EventTitle = new System.Windows.Forms.TextBox();
            this.FrmMain_Txt_EventDescription = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.FrmMain_Txt_CalendarID = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.FrmMain_DtPick_From = new System.Windows.Forms.DateTimePicker();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.FrmMain_DtPick_To = new System.Windows.Forms.DateTimePicker();
            this.FrmMain_Txt_User = new System.Windows.Forms.TextBox();
            this.label6 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // BtnInsertNewEvent
            // 
            this.BtnInsertNewEvent.Location = new System.Drawing.Point(429, 27);
            this.BtnInsertNewEvent.Name = "BtnInsertNewEvent";
            this.BtnInsertNewEvent.Size = new System.Drawing.Size(76, 28);
            this.BtnInsertNewEvent.TabIndex = 0;
            this.BtnInsertNewEvent.Text = "Inserisci";
            this.BtnInsertNewEvent.UseVisualStyleBackColor = true;
            this.BtnInsertNewEvent.Click += new System.EventHandler(this.BtnInsertNewEvent_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(13, 38);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(72, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "Titolo evento:";
            // 
            // FrmMain_Txt_EventTitle
            // 
            this.FrmMain_Txt_EventTitle.Location = new System.Drawing.Point(100, 35);
            this.FrmMain_Txt_EventTitle.Name = "FrmMain_Txt_EventTitle";
            this.FrmMain_Txt_EventTitle.Size = new System.Drawing.Size(305, 20);
            this.FrmMain_Txt_EventTitle.TabIndex = 2;
            this.FrmMain_Txt_EventTitle.Text = "Titolo evento prova";
            // 
            // FrmMain_Txt_EventDescription
            // 
            this.FrmMain_Txt_EventDescription.Location = new System.Drawing.Point(100, 61);
            this.FrmMain_Txt_EventDescription.Multiline = true;
            this.FrmMain_Txt_EventDescription.Name = "FrmMain_Txt_EventDescription";
            this.FrmMain_Txt_EventDescription.Size = new System.Drawing.Size(305, 75);
            this.FrmMain_Txt_EventDescription.TabIndex = 4;
            this.FrmMain_Txt_EventDescription.Text = "Descrizione evento, multilinea.";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(14, 64);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(65, 13);
            this.label2.TabIndex = 3;
            this.label2.Text = "Descrizione:";
            // 
            // FrmMain_Txt_CalendarID
            // 
            this.FrmMain_Txt_CalendarID.Location = new System.Drawing.Point(100, 195);
            this.FrmMain_Txt_CalendarID.Name = "FrmMain_Txt_CalendarID";
            this.FrmMain_Txt_CalendarID.Size = new System.Drawing.Size(115, 20);
            this.FrmMain_Txt_CalendarID.TabIndex = 6;
            this.FrmMain_Txt_CalendarID.Text = "primary";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(14, 198);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(73, 13);
            this.label3.TabIndex = 5;
            this.label3.Text = "ID calendario:";
            // 
            // FrmMain_DtPick_From
            // 
            this.FrmMain_DtPick_From.CustomFormat = "dd/MM/yyyy hh:mm tt";
            this.FrmMain_DtPick_From.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
            this.FrmMain_DtPick_From.Location = new System.Drawing.Point(100, 142);
            this.FrmMain_DtPick_From.MaxDate = new System.DateTime(2040, 12, 31, 0, 0, 0, 0);
            this.FrmMain_DtPick_From.MinDate = new System.DateTime(2025, 1, 1, 0, 0, 0, 0);
            this.FrmMain_DtPick_From.Name = "FrmMain_DtPick_From";
            this.FrmMain_DtPick_From.Size = new System.Drawing.Size(144, 20);
            this.FrmMain_DtPick_From.TabIndex = 7;
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(14, 149);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(24, 13);
            this.label4.TabIndex = 8;
            this.label4.Text = "Da:";
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(14, 174);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(17, 13);
            this.label5.TabIndex = 10;
            this.label5.Text = "A:";
            // 
            // FrmMain_DtPick_To
            // 
            this.FrmMain_DtPick_To.CustomFormat = "dd/MM/yyyy hh:mm tt";
            this.FrmMain_DtPick_To.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
            this.FrmMain_DtPick_To.Location = new System.Drawing.Point(100, 168);
            this.FrmMain_DtPick_To.MaxDate = new System.DateTime(2040, 12, 31, 0, 0, 0, 0);
            this.FrmMain_DtPick_To.MinDate = new System.DateTime(2025, 1, 1, 0, 0, 0, 0);
            this.FrmMain_DtPick_To.Name = "FrmMain_DtPick_To";
            this.FrmMain_DtPick_To.Size = new System.Drawing.Size(144, 20);
            this.FrmMain_DtPick_To.TabIndex = 9;
            // 
            // FrmMain_Txt_User
            // 
            this.FrmMain_Txt_User.Location = new System.Drawing.Point(100, 9);
            this.FrmMain_Txt_User.Name = "FrmMain_Txt_User";
            this.FrmMain_Txt_User.Size = new System.Drawing.Size(305, 20);
            this.FrmMain_Txt_User.TabIndex = 12;
            this.FrmMain_Txt_User.Text = "user";
            // 
            // label6
            // 
            this.label6.AutoSize = true;
            this.label6.Location = new System.Drawing.Point(15, 12);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(79, 13);
            this.label6.TabIndex = 11;
            this.label6.Text = "Utente Google:";
            // 
            // FrmMain
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(528, 227);
            this.Controls.Add(this.FrmMain_Txt_User);
            this.Controls.Add(this.label6);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.FrmMain_DtPick_To);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.FrmMain_DtPick_From);
            this.Controls.Add(this.FrmMain_Txt_CalendarID);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.FrmMain_Txt_EventDescription);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.FrmMain_Txt_EventTitle);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.BtnInsertNewEvent);
            this.Name = "FrmMain";
            this.Text = "Test calendario Google";
            this.ResumeLayout(false);
            this.PerformLayout();
 
        }
 
        #endregion
 
        private System.Windows.Forms.Button BtnInsertNewEvent;
        private System.Windows.Forms.Label label1;
        protected internal System.Windows.Forms.TextBox FrmMain_Txt_EventTitle;
        protected internal System.Windows.Forms.TextBox FrmMain_Txt_EventDescription;
        private System.Windows.Forms.Label label2;
        protected internal System.Windows.Forms.TextBox FrmMain_Txt_CalendarID;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.DateTimePicker FrmMain_DtPick_To;
        private System.Windows.Forms.DateTimePicker FrmMain_DtPick_From;
        protected internal System.Windows.Forms.TextBox FrmMain_Txt_User;
        private System.Windows.Forms.Label label6;
    }
}

Classi Helper

Autenticazione

E' funzionale al Calendar ma può esser estesa:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using NLog;
using System;
using System.IO;
using System.Threading;
 
namespace WebLib.GoogleHlp
{
    public class OAuth2Google_Helper
    {
        private static readonly Logger m_logger = LogManager.GetCurrentClassLogger();
        private static string c_CredTokenFileName = "token.json";
 
        public OAuth2Google_Helper()
        {
            m_logger.Info("OAuth2Google_Helper initialized.");
        }
 
        /// <summary>
        /// Restituisce la classe dei servizi Calendar di Google richiedendo preventivamente l'autenticazione usando l'OAuth2.  
        /// </summary>
        /// <param name="cliSecretJsonFilePath">Path del client secret json file costruito dalla Google Developers console.</param>
        /// <param name="userName">Nome utente che si stà autenticando.</param>
        /// <param name="scopes">Array di Google scopes</param>
        /// <returns>CalendarService usato per fare richieste alla Calendar API</returns>
        public CalendarService GetCalendarService(string cliSecretJsonFilePath, string userName,
                                                        string applicationName, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(userName))
                    throw new ArgumentNullException("userName");
                if (string.IsNullOrEmpty(cliSecretJsonFilePath))
                    throw new ArgumentNullException("clientSecretJson");
                if (!File.Exists(cliSecretJsonFilePath))
                    throw new Exception(string.Format("clientSecretJson file, \"{0}\", does not exist."
                                                    , cliSecretJsonFilePath));
 
                UserCredential cred = GetUserCredential(cliSecretJsonFilePath, userName, scopes);
                if (cred == null)
                    throw new Exception("UserCredential is null. Authentication failed.");
 
                CalendarService calendarService = GetService(cred, applicationName);
                if (calendarService == null)
                    throw new Exception("CalendarService is null. Service creation failed.");
 
                return calendarService;
 
            }
            catch (Exception ex)
            {
                throw new Exception("Get Calendar service failed.", ex);
            }
        }
 
        #region Private Methods
        /// <summary>
        /// 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="cliSecretJsonFilePath">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 it is best to request only what you need and not all of them</param>
        /// <returns>authencated UserCredential</returns>
        private UserCredential GetUserCredential(string cliSecretJsonFilePath, string userName, string[] scopes)
        {
        /*  Esempio di file Json di credenziali per il servizio
             {
                "installed": {
                                "client_id":"458295759590-9btvkanp95rgeifpablq1uct7muvso70.apps.googleusercontent.com",
                                "project_id":"bankpasswordwinc-1606500460382",
                                "auth_uri":"https://accounts.google.com/o/oauth2/auth",
                                "token_uri":"https://oauth2.googleapis.com/token",
                                "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
                                "client_secret":"IizCk507q_N4YZLZQFNIizxx",
                                "redirect_uris":["urn:ietf:wg:oauth:2.0:oob",
                                "http://localhost"]
                              }
            }
         */
            try
            {
                if (string.IsNullOrEmpty(userName))
                    throw new ArgumentNullException("userName");
                if (string.IsNullOrEmpty(cliSecretJsonFilePath))
                    throw new ArgumentNullException("clientSecretJson");
                if (!File.Exists(cliSecretJsonFilePath))
                    throw new Exception("clientSecretJson file does not exist.");
 
                // Si legge il file json delle credenziali del client (è generato dalla Google Developers console
                // a questo URL:        https://console.developers.google.com  )
                // NOTA Dopo aver aggiunto nella root del progetto il file "credentials.json" IMPOSTARE
                //      la property del file a "Copy always" !!!
 
                string credPath = Path.GetDirectoryName(cliSecretJsonFilePath);
 
                using (var stream = new FileStream(cliSecretJsonFilePath, FileMode.Open, FileAccess.Read))
                {
                    //string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    //credPath = Path.Combine(credPath
                    //                    , ".credentials/"
                    //                    , System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
 
                    // The file token in credFileTokenFullPath (token.json) stores the user's access and refresh tokens, 
                    // and is created automatically when the authorization flow completes for the first time.
                    string credFileTokenFullPath = Path.Combine(credPath, c_CredTokenFileName);
                    // Requesting Authentication or loading previously stored authentication for userName
                    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                             scopes,
                                                                             userName, //Es. user
                                                                             CancellationToken.None,
                                                                             new FileDataStore(credFileTokenFullPath, true)).Result;
 
                    credential.GetAccessTokenForRequestAsync();
                    return credential;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Get user credentials failed.", ex);
            }
        }
 
        /// <summary>
        /// This method get a valid Calendar service
        /// </summary>
        /// <param name="credential">Authecated user credentail</param>
        /// <returns>CalendarService used to make requests against the Calendar API</returns>
        private CalendarService GetService(UserCredential credential, string applicationName)
        {
            try
            {
                if (credential == null)
                    throw new ArgumentNullException("credential");
 
                // Create Calendar API service.
                CalendarService gCalendarService = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = applicationName
                });
 
                //gCalendarService.HttpClient.Timeout = TimeSpan.FromMinutes(10);
                return gCalendarService;
            }
            catch (Exception ex)
            {
                throw new Exception("Get Calendar service failed.", ex);
            }
        }
        #endregion
    }
}

Calendar

using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace WebLib.GoogleHlp
{
    public class Calendar_Helper
    {
        #region Properties
        public CalendarService GCService { get; private set; }
 
        public string CalendarID { get; private set; }
        #endregion
 
        #region Constructors
        public Calendar_Helper(CalendarService calenadrService, string calendarID = "primary")
        {
            if (calenadrService == null)
                throw new ArgumentNullException(nameof(calenadrService), "CalendarService cannot be null.");
 
            GCService = calenadrService;
            CalendarID = calendarID;
        }
        #endregion
 
        #region Public Methods
        /// <summary>
        /// Cerca tra gli eventi del calendario Google l'ID dell'evento che contiene il testo freeTextToSearch.
        /// </summary>
        /// <param name="freeTextToSearch"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        public string GetCalendarEventID(string freeTextToSearch, out string errorMessage)
        {
            string eventID = null;
            errorMessage = string.Empty;
 
            try
            {
                EventsResource.ListRequest request = GCService.Events.List(CalendarID);
                request.Q = freeTextToSearch;   //Cerca in: Summary, Description, Location + etc
                request.MaxResults = 1;         //Limita a un solo risultato
                Events events = request.Execute();
                if (events.Items != null && events.Items.Count > 0)
                {
                    eventID = events.Items[0].Id;
                }
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
                // Log the exception if needed
            }
            return eventID;
        }
 
        public bool DeleteCalendarEvent(string freeTextToSearch, out string errorMessage)
        {
            errorMessage = string.Empty;
            bool outcome = false;
            try
            {
                //Cerca l'evento
                string eventID = GetCalendarEventID(freeTextToSearch, out errorMessage);
                if (!string.IsNullOrEmpty(errorMessage))
                {
                    errorMessage = string.Format("Error getting Google Calendar Event ID for '{0}': {1}"
                                                , freeTextToSearch, errorMessage);
                    return outcome;
                }
                if (eventID == null)
                {
                    errorMessage = string.Format("No Google Calendar Event found for '{0}'", freeTextToSearch);
                    return outcome;
                }
                // Cancella l'evento appena trovato
                EventsResource.DeleteRequest request = GCService.Events.Delete(CalendarID, eventID);
                string strOut = request.Execute();
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }
            return outcome;
        }
 
        /// <summary>
        /// Cancella un evento dal calendario Google.
        /// </summary>
        /// <param name="eventID"></param>
        /// <param name="freeTextToSearch">Se si fornisce eventID, sarà ignorato</param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        public bool DeleteCalendarEvent(string eventID, string freeTextToSearch, out string errorMessage)
        {
            errorMessage = string.Empty;
            bool outcome = false;
            try
            {
                if (string.IsNullOrEmpty(eventID))
                {
                    eventID = GetCalendarEventID(freeTextToSearch, out errorMessage);
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        errorMessage = string.Format("Error getting Google Calendar Event ID for offer '{0}': {1}"
                                                    , freeTextToSearch, errorMessage);
                        return outcome; //Non si può cancellare un evento che non esiste
                    }
                    if (string.IsNullOrEmpty(eventID))
                    {
                        errorMessage = string.Format("No Google Calendar Event found for offer '{0}'", freeTextToSearch);
                        return outcome; //Non si può cancellare un evento che non esiste
                    }
                }
                //Se l'offerta è stata eliminata o rifiutata, allora si cancella l'evento dal Google Calendar
                if (!string.IsNullOrEmpty(eventID))
                {
                    EventsResource.DeleteRequest request = GCService.Events.Delete(CalendarID, eventID);
                    request.Execute();
                }
                outcome = true; //Se si arriva qui, l'evento è stato cancellato con successo
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }
            return outcome;
        }
 
        public bool UpdateCalendarEvent(string eventID, Event updatedEvent, out string errorMessage)
        {
            errorMessage = string.Empty;
            bool outcome = false;
            try
            {
                if (string.IsNullOrEmpty(eventID))
                {
                    errorMessage = "Event ID cannot be null or empty.";
                    return outcome;
                }
                // Update the event
                EventsResource.UpdateRequest request = GCService.Events.Update(updatedEvent, CalendarID, eventID);
                request.Execute();
                outcome = true; // If we reach here, the event was updated successfully
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }
            return outcome;
        }
        #endregion
    }
}

Materiale

Mappa e Link


C# | Mondo Google | Integrazioni e librerie


Visual Studio | MS SQL | Dizionario


Parole chiave:

Author