Search code examples
c#.netgoogle-apigoogle-calendar-api

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


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


Solution

  • 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