How to create an event in Google Calendar using c# and Google API?
Asked Answered
U

2

5

UPDATE: I solved this problem and posted the solution as an answer below! ;)

I need to create an event and add it to Google Calendar using Google API.

For now I only know how to get all the events I have from Google Calendar. This is what I've got so far:

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;


namespace CalendarQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/calendar-dotnet-quickstart.json
        static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
        static string ApplicationName = "Google Calendar API .NET Quickstart";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // 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();
            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.Read();
        }
    }
}

What I am trying to do must be looking something like this:

        var ev = new Event();
        EventDateTime start = new EventDateTime();
        start.DateTime = new DateTime(2019, 3, 11, 10, 0, 0);

        EventDateTime end = new EventDateTime();
        end.DateTime = new DateTime(2019, 3, 11, 10, 30, 0);


        ev.Start = start;
        ev.End = end;
        ev.Description = "Description...";

        events.Items.Insert(0, ev);

I've spent the entire day searching any .NET samples but got nothing. Any help appreciated! ;)

Ulane answered 11/3, 2019 at 13:34 Comment(2)
developers.google.com/resources/api-libraries/documentation/…Luciennelucier
@IanKemp thank you! I still get an error though: EventsResource.InsertRequest does not contain a definition for "InsertRequest" If you could show me an example of how to use it that would be just great! I've also tried this: service.Events.Insert(ev, "primary"); but I still don't see an event that I've just created in my calendar.Ulane
U
14

I've solved this problem! So before building the project change

static string[] Scopes = { CalendarService.Scope.CalendarReadonly };

to

static string[] Scopes = { CalendarService.Scope.Calendar };

If you already built the solution then delete credentials.json file and then reload it. The code for adding an event is here:

    var ev = new Event();
    EventDateTime start = new EventDateTime();
    start.DateTime = new DateTime(2019, 3, 11, 10, 0, 0);

    EventDateTime end = new EventDateTime();
    end.DateTime = new DateTime(2019, 3, 11, 10, 30, 0);


    ev.Start = start;
    ev.End = end;
    ev.Summary = "New Event";
    ev.Description = "Description...";

    var calendarId = "primary";
    Event recurringEvent = service.Events.Insert(ev, calendarId).Execute();
    Console.WriteLine("Event created: %s\n", e.HtmlLink);

This is my first try with Google API so don't judge me ;) Hope it helps somebody one day!

Note : You also need to remove the 'token.json' folder from \bin\debug folder

Ulane answered 11/3, 2019 at 15:42 Comment(2)
i tried installing the package in .net core 2.0 but i guess it is not working it says can not find google namespaceSelemas
Adding a conference link: #66278496Pilar
W
0

This is further useful information on understanding the Google Calendar API and how to add events.

Here is a link to c# calendar examples on GitHub

Here is an example:

using Google;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util;

Console.WriteLine("Hello, World!");

string clientId = "<your client id>";
string clientSecret = "<your client secret>";

string[] scopes = { "https://www.googleapis.com/auth/calendar" };

var credentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
    new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret },
    scopes, "user", CancellationToken.None).Result;

if(credentials.Token.IsExpired(SystemClock.Default))
{
   await  credentials.RefreshTokenAsync(CancellationToken.None);
}

var service = new CalendarService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credentials
}
);

var googleCalendarEvent = new Event();

googleCalendarEvent.Start = new EventDateTime()
    { DateTimeDateTimeOffset = new DateTime(2023, 12, 29, 10, 0, 0) };

googleCalendarEvent.End = new EventDateTime()
    { DateTimeDateTimeOffset = new DateTime(2023, 12, 29, 11, 0, 0) };

googleCalendarEvent.Summary = "New Event from api";
googleCalendarEvent.Description = "Description of my event";

var calendarId = "primary"; //Always primary.
try
{
    Event result = await service.Events.Insert(googleCalendarEvent, calendarId).ExecuteAsync();

    Console.WriteLine("Event created: %s\n", result.HtmlLink);
}
catch (GoogleApiException ex)
{
    Console.WriteLine(ex.ToString());
}
Wrecker answered 28/12, 2023 at 20:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.