Google calendar API integration in .Net Core

Here, we are going to learn how can we integrate Google Calendar API with C# and .NET Core.

Prerequisite

  • Basic knowledge of C# and .NET Core
  • Basic Knowledge of API

What we are gonna do here?

Here, we going to Integrate Google Calendar With ourΒ  .NET Core 3.1 Web Applications. Here, I’m gonna listing Events from Google Calendar and

also, you can get a little bit idea about Google OAuth 2.0, without it you can’t access Google Calendar API.

Let’s Get Start the project setup.

First Create aΒ  .Net Core MVC Web Application.

Now Install these Two Packages that are Extremely Necessary.

  • Google.Apis.Calendar.v3
  • Google.Apis.Auth.AspNetCore3


Now, for the next step, we have to Visit Google Developer Console.

Create a project and Get Access Credentials.

Now, Add those credentials to your appsettings.json.

Now , for the next step do as below in Startup.cs file for Google OAuth.

using Google.Apis.Auth.AspNetCore3;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Google_Calnder_api
{
    public class Startup
    {


        private static AuthString applicationConfigurations;
        public Startup(IConfiguration configuration)
        {
            IConfigurationBuilder builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile($"appsettings.json", optional: false, reloadOnChange: true);
            IConfigurationRoot conf = builder.Build();

            applicationConfigurations = conf.GetSection("Google-Auth").Get<AuthString>();
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddRazorPages();
            services
       .AddAuthentication(o =>
       {
            // This forces challenge results to be handled by Google OpenID Handler, so there's no
            // need to add an AccountController that emits challenges for Login.
            o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
            // This forces forbid results to be handled by Google OpenID Handler, which checks if
            // extra scopes are required and does automatic incremental auth.
            o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
            // Default scheme that will handle everything else.
            // Once a user is authenticated, the OAuth2 token info is stored in cookies.
            o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
       })
       .AddCookie()
       .AddGoogleOpenIdConnect(options =>
       {
           options.ClientId = applicationConfigurations.client_id;
           options.ClientSecret = applicationConfigurations.client_secret;
       });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseHttpsRedirection();
            app.UseRouting();
            
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Now, For the next step in Home Controller create a method called Login and Its Correspond View, after this method gets data from Google Calendar API, we are gonna list that data in Login View For testing purposes.

Here, In Home Controller,

using System;
using Google_Calnder_api.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using Microsoft.Extensions.Configuration;
using System.IO;

using Google.Apis.Auth.AspNetCore3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using System.Threading.Tasks;
using System.Linq;
using Google.Apis.Calendar;
using Microsoft.AspNetCore.Authorization;
using Google.Apis.Calendar.v3;


namespace Google_Calnder_api.Controllers
{
    public class HomeController : Controller
    {
        private static AuthString applicationConfigurations;
        
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
                IConfigurationBuilder builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile($"appsettings.json", optional: false, reloadOnChange: true);
                IConfigurationRoot configuration = builder.Build();

                applicationConfigurations = configuration.GetSection("Google-Auth").Get<AuthString>();
            
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        [GoogleScopedAuthorize(CalendarService.ScopeConstants.Calendar)]        
        public async Task<IActionResult> Login([FromServices] IGoogleAuthProvider auth)
        {
                        
            GoogleCredential cred = await auth.GetCredentialAsync();
            var service = new CalendarService(new BaseClientService.Initializer
            {
                HttpClientInitializer = cred,
                ApplicationName = "Calendar API Integration",
            });
            var calendarList = await service.CalendarList.List().ExecuteAsync();            
            var CalendarEvents = await service.Events.List(calendarList.Items[0].Id).ExecuteAsync();
            return View(CalendarEvents);
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

In , Home View we have login button to login into Google Accounts, with we can generate Google Authorization and gets list of events from

Calendar API.

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    
    <form method="post" asp-controller="home" asp-action="login">
        <div class="col-md-12 my-3 text-center">
            <button class="btn btn-primary">Google Login</button>
        </div>
    </form>
    @foreach (var properties in ViewData.ModelMetadata.Properties)
    {
        <h4>@properties.PropertyName</h4>
    }
</div>

Here, the UI looks like this. Now click onΒ  Google Login button. It will display Google Sign In window.

Now, For listing the Calendar Events we are gonna use Login View. Here is the code and also a Screenshot UI.

@using System;
@model Google.Apis.Calendar.v3.Data.Events


<div class="container row">
    <div class="col-md-12">
        <h3 class="text-primary">Google Calendar Events</h3>
    </div>
    <div class="col-md-12">
        <h3 class="">Events List</h3>
        @foreach (var item in Model.Items)
        {
            <div class="alert alert-secondary" role="alert">

                <h4>
                    @item.Summary
                </h4>
                <div class="text-success">
                    Start : @Convert.ToDateTime(@item.Start.DateTime).ToString("dddd, dd MMMM yyyy") @Convert.ToDateTime(@item.Start.DateTime).ToString("h:mm tt")
                </div>
                <div class="text-danger">
                    End : @Convert.ToDateTime(@item.End.DateTime).ToString("dddd, dd MMMM yyyy") @Convert.ToDateTime(@item.End.DateTime).ToString("h:mm tt")             
                </div>


            </div>
        }
    </div>

</div>

And, that’s all of it. I came up with this straightforward way to do things. If you want to Create, Edit, and Delete With Google Calendar Events

You can visit Google Calendar API reference for that.

And, here in the end I prepared a demo as a video and you an idea of how it’s working.😁😁😁 , So I hope you guys will like my blog.

2 Comments

  1. Machhindra R Gaikwad

    Hi, Thanks for great article.
    For this example which return url you have used? please reply.

    because i am using angular and .net core and for testing locally it throws error saying “url_mismatch”

    Thanks in Advance

    1
    0
    Reply
  2. ilyas

    how can we implement it in .Net core Angular?

    0
    0
    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories