Saturday, January 18, 2025

How to Create Events Using Microsoft Graph API with Delegated Permissions and MSAL.js

Microsoft Graph API provides powerful capabilities to interact with Microsoft 365 services. In this guide, we’ll explore how to create calendar events using Microsoft Graph API with delegated permissions, leveraging the MSAL.js library for authentication and token acquisition.

Prerequisites

  1. Azure App Registration:

    • Go to the Azure portal and register your app.

    • Note down the Application (Client) ID, Directory (Tenant) ID, and create a Client Secret.

    • Under "API permissions," add Calendar.ReadWrite delegated permission.

  2. MSAL.js Library: Install MSAL.js in your project:

    npm install @azure/msal-browser
  3. Redirect URI: Configure the redirect URI in your Azure app registration and in your application.

Setting Up MSAL.js

First, initialize MSAL.js in your application:

import { PublicClientApplication } from "@azure/msal-browser";

const msalConfig = {
  auth: {
    clientId: "YOUR_CLIENT_ID", // Replace with your Application ID
    authority: "https://login.microsoftonline.com/YOUR_TENANT_ID", // Replace with your Tenant ID
    redirectUri: "http://localhost:3000", // Replace with your redirect URI
  },
};

const msalInstance = new PublicClientApplication(msalConfig);

Logging In and Acquiring a Token

Use the MSAL.js library to log in and obtain an access token:

async function loginAndGetToken() {
  try {
    const loginResponse = await msalInstance.loginPopup({
      scopes: ["Calendars.ReadWrite"] // Scope for creating calendar events
    });

    const account = loginResponse.account;
    msalInstance.setActiveAccount(account);

    const tokenResponse = await msalInstance.acquireTokenSilent({
      account: account,
      scopes: ["Calendars.ReadWrite"]
    });

    return tokenResponse.accessToken;
  } catch (error) {
    if (error instanceof InteractionRequiredAuthError) {
      // Fallback to interactive login
      const tokenResponse = await msalInstance.acquireTokenPopup({
        scopes: ["Calendars.ReadWrite"]
      });
      return tokenResponse.accessToken;
    } else {
      console.error("Error acquiring token", error);
      throw error;
    }
  }
}

Creating a Calendar Event

Once you have the access token, use it to call the Microsoft Graph API and create an event:

async function createEvent(accessToken) {
  const endpoint = "https://graph.microsoft.com/v1.0/me/events";

  const event = {
    subject: "Team Meeting",
    body: {
      contentType: "HTML",
      content: "Let's discuss the project updates."
    },
    start: {
      dateTime: "2025-01-20T09:00:00",
      timeZone: "Pacific Standard Time"
    },
    end: {
      dateTime: "2025-01-20T10:00:00",
      timeZone: "Pacific Standard Time"
    },
    attendees: [
      {
        emailAddress: {
          address: "attendee@example.com",
          name: "John Doe"
        },
        type: "required"
      }
    ]
  };

  const options = {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${accessToken}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify(event)
  };

  try {
    const response = await fetch(endpoint, options);
    if (response.ok) {
      const eventData = await response.json();
      console.log("Event created successfully:", eventData);
    } else {
      console.error("Failed to create event:", response.status, await response.text());
    }
  } catch (error) {
    console.error("Error creating event:", error);
  }
}

Bringing It All Together

Combine the functions to authenticate the user, acquire a token, and create an event:

(async function main() {
  try {
    const token = await loginAndGetToken();
    await createEvent(token);
  } catch (error) {
    console.error("An error occurred:", error);
  }
})();

Testing

  1. Start your application and ensure the redirect URI matches the one configured in Azure.

  2. Click the login button to authenticate the user.

  3. Call the createEvent function and verify the event appears in the user's calendar.

Conclusion

Using Microsoft Graph API with MSAL.js simplifies integrating calendar functionalities into your application. With delegated permissions, you can access user-specific data securely. Follow this guide to enhance your applications with event creation capabilities!

If you need any assistance integrating Microsoft Graph API with an ASP.NET web application, feel free to reach out to me at lasantha26@gmail.com

Wednesday, November 8, 2023

TinyMCE Insert/Edit link not editable

 To fix this add e.stopImmediatePropagation() as below.

$(document).on('focusin', function (e) {

            if ($(e.target).closest(".tox-tinymce, .tox-tinymce-aux, .moxman-window, .tam-assetmanager-root").length) {

                e.stopImmediatePropagation();

            }

        });

Friday, November 3, 2023

How to export Android Signing Keys

A signing key is a digital key used to sign Android apps, confirming their authenticity and ensuring they haven't been tampered with. It's an essential part of app development and distribution.

The default location for Android signing keys on a Windows computer is:

`C:\Users\username\AppData\Local\Xamarin\Mono for Android\Keystore\AppName`

Here, replace "username" with your Windows username, and "AppName" with the name of your Android app. This directory stores your Android signing keys.

Thursday, October 19, 2023

How to Open an App in the Google Play Store When a Button is Clicked in a MonoGame Android Project

Introduction:

In my MonoGame Android project, I wanted to provide users with the option to rate my app when they clicked a button within the game. To achieve this, I inserted the following code inside the button's click event:

// Define your app's URL

Android.Net.Uri uri = Android.Net.Uri.Parse("market://details?id=cool.math.kids.games");


// Create an intent

Intent intent = new Intent(Intent.ActionView, uri);


// Get the current Android activity

Android.App.Activity activity = Game1.Activity;


// Start the intent to open the Google Play Store

activity.StartActivity(intent);

This code snippet allows users to seamlessly open the Google Play Store and navigate to your app's page for rating and reviews.

Thursday, October 12, 2023

How to disable grammarly in tinymce editor

I have tried data-gramm="false" and hiding it through CSS, but neither of these solutions has worked. If anyone can resolve this issue, please leave a comment.

Wednesday, October 11, 2023

How to disable related videos at the end of the embedded videos

Set rel parameter to 0 

https://www.youtube.com/embed/qU_djsolPkE?rel=0

In this case, rel=0 means that YouTube will not show related videos at the end of the embedded video. Setting rel=0 disables the display of related videos from other channels after the video playback is completed. If you were to set rel=1 instead, it would allow related videos to be shown.

This parameter is often used by website or content creators who want to prevent viewers from being distracted by other videos after watching the embedded video.

This parameter not working since 2018. See Notes below

YouTube Embedded Players and Player Parameters  |  YouTube IFrame Player API  |  Google for Developers



Tuesday, October 10, 2023

How to Create a Calendar Event Using Microsoft Graph API and C#

Microsoft Graph API is a powerful tool that allows developers to access a wide range of Microsoft 365 services, including Outlook and Calendar. In this blog post, we will walk you through the steps to create a calendar event using the Microsoft Graph API and C#. This integration can be incredibly useful for automating event scheduling and managing calendars within your applications.

Prerequisites

Before we dive into the code, you'll need the following:

  • Microsoft 365 Account: Ensure you have access to a Microsoft 365 account and have the necessary permissions to create calendar events.
  • Azure App Registration: Create an Azure App Registration to obtain the required client ID and client secret for authentication.
  • Visual Studio or Visual Studio Code: Use an IDE such as Visual Studio or Visual Studio Code with the necessary C# development tools installed.
  • Microsoft.Graph NuGet Package: Install the Microsoft.Graph NuGet package in your project to interact with Microsoft Graph API.

Step 1: Set Up Your Azure App Registratio

Navigate to the Azure portal and create a new App Registration and Note down the Application (client) ID, Tenant ID and generate a client secret. This information will be needed for authentication.

Step 2: Install Microsoft.Graph NuGet Package

In your C# project, install the Microsoft.Graph NuGet package using the package manager console or NuGet package manager in Visual Studio:

Step 3: Create GraphServiceClient

var clientSecretCredential = new ClientSecretCredential(tenantid, clientid, secret);

var _graphServiceClient = new GraphServiceClient(clientSecretCredential);

Step 4: Create a Calendar Event

Now that we have obtained the graphServiceClient, we can use it to create a calendar event using the Microsoft Graph API.

var newEvent = new Event

            {

                Subject = actionPlan.EventTitle,

                Start = new DateTimeTimeZone

                {

                    DateTime = actionPlan.EventStartTime.Value.ToString("o"),

                    TimeZone = TimeZoneInfo.Utc.Id

                },

                End = new DateTimeTimeZone

                {

                    DateTime = actionPlan.EventEndTime.Value.ToString("o"),

                    TimeZone = TimeZoneInfo.Utc.Id

                },

                Location = new Location

                {

                    DisplayName = actionPlan.EventLocation

                },


                Body = new ItemBody

                {

                    Content = notificationBody,

                    ContentType = BodyType.Html

                },


                Attendees = attendeeList,


                ResponseRequested = true


            };

var createdEvent = await graphServiceClient.Users[currentUser].Events.Request().AddAsync(newEvent);

Adjust the event details and date/time as needed for your specific use case.

Conclusion

You have now learned how to create a calendar event using the Microsoft Graph API and C#. Integrating Microsoft Graph API into your applications opens up a world of possibilities for automating and enhancing calendar management within your organization. Happy coding!

How to Create Events Using Microsoft Graph API with Delegated Permissions and MSAL.js

Microsoft Graph API provides powerful capabilities to interact with Microsoft 365 services. In this guide, we’ll explore how to create calen...