Connect to the Outlook Calendar with the Microsoft Graph
Objective
Scenario
Virtual Machines
- QSC 1511 Master
Exercise 1 : Create a new project using Azure Active Directory v2 authentication
In this first step, you will create a new ASP.NET MVC project using the Graph AAD Auth v2 Start Project template, register a new application in the developer portal, and log in to your app and generate access tokens for calling the Graph API.
- Sign In to virtual machineActivate Windows logon and sign in as Developer with the following password: P@ssw0rd! and press Enter.Note: You may also use the Commands menu to automatically paste the virtual machine default Password (P@ssw0rd!).
- Launch Visual Studio 2015 as administratorShift + Right click Visual Studio 2015 on the task bar and select Run as Administrator.
- Create a new projectFrom the File menu select the New Project command. Search the installed templates for Graph and select the Graph AAD Auth v2 Starter Project template.
- Name the project QuickStartCalendarWebAppName the new project QuickStartCalendarWebApp and click OK.
- Open the Web.config fileOpen the Web.config file and find the appSettings element. This is where you will need to add your appId and app secret you will generate in the next steps.
- Open apps.dev.microsoft.comLaunch the Application Registration Portal by navigating your web browser and going to apps.dev.microsoft.com. to register a new application.
- Sign in using the supplied Office 365 credentialsSign into the portal using your Office 365 username and password.
- Add the GraphCalendarQuickStart appClick Add an App and type GraphCalendarQuickStart for the application name.
- Copy the Application ID to web.configCopy the Application Id and paste it into the value for ida:AppId in your project web.config file.
- Generate a new passwordUnder Application Secrets click Generate New Password to create a new client secret for your app.
- Copy the app password to web.configCopy the displayed app password and paste it into the value for ida:AppSecret in your project web.config file.
- Modify the ida:AppScopes valuesModify the ida:AppScopes value to include the required https://graph.microsoft.com/calendars.readwrite and https://graph.microsoft.com/calendars.read scopes as shown below:
- Open the webapp project propertiesRight-click QuickStartCalendarWebApp and click Properties to open the project properties.
- Select WebClick Web in the left navigation.
- Copy the Project URLCopy the Project Url value.
- Add a platform to the portalBack on the Application Registration Portal page, click Add Platform>Web.
- Add the Project URLPaste the value of Project Url into the Redirect URIs field
- Save the changesScroll to the bottom of the page and click Save.
- Open the WebApp propertiesRight-click QuickStartCalendarWebApp and click Properties to open the project properties
- Select WebClick Web in the left navigation.
- Add a Start Action valueUnder Start Action Choose Specific Page option and Type its value as Account/SignOut
- Compile and launch the applicationPress F5 to compile and launch your new application in the default browser.
- Sign in with the supplied Office 365 credentialsOnce the Graph and AAD v2 Auth Endpoint Starter page appears, click Sign in and login to your Office 365 account.
- Review and accept the permissionsReview the permissions the application is requesting, and click Accept.
- Stop the debuggerBefore proceeding stop the debugger
Exercise 2 : Access Calendar through Microsoft Graph SDK
In this exercise, you will build on exercise 1 to connect to the Microsoft Graph SDK and work with Office 365 and Outlook Calendar.
- Select Manage NuGet PackagesIn the Solution Explorer right-click the QuickStartCalendarWebApp project and select Manage NuGet Packages....
- Change the source to localChange Package Source (on the upper right corner) to Microsoft Graph local.
- Search for Microsoft.GraphClick Browse and search for Microsoft.Graph.
- Install the Graph SDKSelect the Microsoft Graph SDK and click Install.
- Select Manage NuGet PackagesIn the Solution Explorer right-click the QuickStartCalendarWebApp project and select Manage NuGet Packages....
- Change the source to nuget.orgChange Package Source (on the upper right corner) to nuget.org.
- Browse for the bootstrapClick Browse and search for Bootstrap.v3.Datetimepicker.CSS.
- Install the bootstrapSelect Bootstrap.v3.Datetimepicker.CSS and click Install.
- Replace code in the cs fileOpen the App_Start/BundleConfig.cs file and update the bootstrap script and CSS bundles. Replace these lines:
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
with: (copy the lines from below and paste them into the VM)
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js",
"~/Scripts/moment.js",
"~/Scripts/bootstrap-datetimepicker.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/bootstrap-datetimepicker.css",
"~/Content/site.css")); - Add a controllerFind the Controllers folder under QuickStartCalendarWebApp, right-click it and select Add>Controller.
- Select the MVC 5 ControllerSelect MVC 5 Controller - Empty and click Add.
- Change the name of the controllerChange the name of the controller to CalendarController and click Add.
- Replace the reference in the classReplace the following reference to the top of the CalendarController class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
with the following references (copy the below and then paste it into the VM)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.Graph;
using QuickStartCalendarWebApp.Auth;
using QuickStartCalendarWebApp.TokenStorage;
using Newtonsoft.Json;
using System.IO; - Add code to the classAdd the following code to the CalendarController class to initialize a new GraphServiceClient and generate an access token for the Graph API: (copy from below and then paste into the VM)
private GraphServiceClient GetGraphServiceClient()
{
string userObjId = AuthHelper.GetUserId(System.Security.Claims.ClaimsPrincipal.Current);
SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);
string authority = string.Format(ConfigurationManager.AppSettings["ida:AADInstance"], "common", "");
AuthHelper authHelper = new AuthHelper(
authority,
ConfigurationManager.AppSettings["ida:AppId"],
ConfigurationManager.AppSettings["ida:AppSecret"],
tokenCache);
// Request an accessToken and provide the original redirect URL from sign-in
GraphServiceClient client = new GraphServiceClient(new DelegateAuthenticationProvider(async (request) =>
{
string accessToken = await authHelper.GetUserAccessToken(Url.Action("Index", "Home", null, Request.Url.Scheme));
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + accessToken);
}));
return client;
} - Replace code in the classReplace the following code in the CalenderController class
// GET: Calendar
public ActionResult Index()
{
return View();
}
with the following code to get all events for the next 7 days in your mailbox. (Copy the below and paste it into the virtual machine)
// GET: Me/Calendar
[Authorize]
public async TaskIndex(int? pageSize, string nextLink)
{
if (!string.IsNullOrEmpty((string)TempData["error"]))
{
ViewBag.ErrorMessage = (string)TempData["error"];
}
pageSize = pageSize ?? 10;
var client = GetGraphServiceClient();
// In order to use a calendar view, you must specify
// a start and end time for the view. Here we'll specify
// the next 7 days.
DateTime start = DateTime.Today;
DateTime end = start.AddDays(6);
// These values go into query parameters in the request URL,
// so add them as QueryOptions to the options passed ot the
// request builder.
List - Add code to the classAdd the following code to the CalenderController class to display details of an event. (Copy the below and paste it into the virtual machine)
[Authorize]
public async TaskDetail(string eventId)
{
var client = GetGraphServiceClient();
var request = client.Me.Events[eventId].Request();
try
{
var result = await request.GetAsync();
TempData[eventId] = result.Body.Content;
return View(result);
}
catch (ServiceException ex)
{
return RedirectToAction("Index", "Error", new { message = ex.Error.Message });
}
}
public async TaskGetEventBody(string eventId)
{
return Content(TempData[eventId] as string);
} - Add code to the classIn a web browser, open https://raw.githubusercontent.com/robertlisiecki/LODSLabCode/5329ce05d67d0148675550b09dc649bdb2618ab1/Ignite/IDL2001/Code.txt. Copy and paste the contents into the CalendarController class to add a new event in the calendar.
- Add code to the classAdd the following code to the CalendarController class to Accept an event. (copy the below and paste it into the virtual machine)
// Accept Calendar event
[Authorize]
[HttpPost]
public async TaskAccept(string eventId)
{
var client = GetGraphServiceClient();
var request = client.Me.Events[eventId].Accept().Request();
try
{
await request.PostAsync();
}
catch (ServiceException ex)
{
TempData["error"] = ex.Error.Message;
return RedirectToAction("Index", "Error", new { message = ex.Error.Message });
}
return RedirectToAction("Detail", new { eventId = eventId });
} - Add code to the classAdd the following code to the CalendarController class to TentativelyAccept an event. (copy the below and paste it into the virtual machine)
[Authorize]
[HttpPost]
public async TaskTentative(string eventId)
{
var client = GetGraphServiceClient();
var request = client.Me.Events[eventId].TentativelyAccept().Request();
try
{
await request.PostAsync();
}
catch (ServiceException ex)
{
TempData["error"] = ex.Error.Message;
return RedirectToAction("Index", "Error", new { message = ex.Error.Message });
}
return RedirectToAction("Detail", new { eventId = eventId });
} - Add code to the classAdd the following code to the CalendarController class to Decline an event. (copy the below and paste it into the virtual machine)
[Authorize]
[HttpPost]
public async TaskDecline(string eventId)
{
var client = GetGraphServiceClient();
var request = client.Me.Events[eventId].Decline().Request();
try
{
await request.PostAsync();
}
catch (ServiceException ex)
{
TempData["error"] = ex.Error.Message;
return RedirectToAction("Index", "Error", new { message = ex.Error.Message });
}
return RedirectToAction("Index");
} - Open the Layout.cshmtlLocate the Views/Shared folder in the project and then open the _Layout.cshtml file found in the Views/Shared folder.
- Find and update the section with link near the topLocate the part of the file that includes a few links at the top of the page. It should look similar to the following code:
Update that navigation to add the "Outlook Calendar API" link with "Calendar" and connect this to the controller you just created. (copy the below and paste it into the virtual machine)
- Select the calendar folderExpand Views folder in QuickStartCalendarWebApp and select the folder Calendar.
- Add a new itemRight-click Calendar and select Add then New Item.
- Modify the MVC 5 view page nameSelect MVC 5 View Page (Razor) and change the filename Index.cshtml and click Add.
- Replace the code in the cshtmlIn a web browser, open https://raw.githubusercontent.com/robertlisiecki/LODSLabCode/b5fbe55b7c9c21a2a2a137870229f00a08c8487f/Ignite/IDL2001/Code2.txt. Copy and paste the contents to replace all of the code in the Calendar/Index.cshtml.
- Add a new viewExpand the Views folder in QuickStartCalendarWebApp. Right-click Calendar and select Add then New Item.
- Rename the MVC 5 pageSelect MVC 5 View Page (Razor) and change the filename Detail.cshtml and click Add.
- Replace the code in the cshtmlIn a web browser, open https://raw.githubusercontent.com/robertlisiecki/LODSLabCode/9b0f3afe5682daee0f9f4c61caa970b55a2db6ed/Ignite/IDL2001/Code3.txt. Copy and paste the contents to replace all of the code in the Calendar/Detail.cshtml.
- Debug the applicationPress F5 to begin debugging.
- Login with the supplied credentialsWhen prompted, login with your Office 365 administrator account.
- Select the API linkClick the Outlook Calendar API link in the navigation bar at the top of the page.
- Test the new appTry the app!
No comments:
Post a Comment