Friday, March 17, 2017

Connect to the Outlook Calendar with the Microsoft Graph

Connect to the Outlook Calendar with the Microsoft Graph

Objective

Scenario

Virtual Machines

  1. 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.
  1. Sign In to virtual machine
    Activate 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!).
  2. Launch Visual Studio 2015 as administrator
    Shift + Right click Visual Studio 2015 on the task bar and select Run as Administrator.
  3. Create a new project
    From the File menu select the New Project command. Search the installed templates for Graph and select the Graph AAD Auth v2 Starter Project template. 
  4. Name the project QuickStartCalendarWebApp
    Name the new project QuickStartCalendarWebApp and click OK.
  5. Open the Web.config file
    Open 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.
  6. Open apps.dev.microsoft.com
    Launch the Application Registration Portal by navigating your web browser and going to apps.dev.microsoft.com. to register a new application.
  7. Sign in using the supplied Office 365 credentials
    Sign into the portal using your Office 365 username and password.
  8. Add the GraphCalendarQuickStart app
    Click Add an App and type GraphCalendarQuickStart for the application name.
  9. Copy the Application ID to web.config
    Copy the Application Id and paste it into the value for ida:AppId in your project web.config file.
  10. Generate a new password
    Under Application Secrets click Generate New Password to create a new client secret for your app.
  11. Copy the app password to web.config
    Copy the displayed app password and paste it into the value for ida:AppSecret in your project web.config file.
  12. Modify the ida:AppScopes values
    Modify 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:








  13. Open the webapp project properties
    Right-click QuickStartCalendarWebApp and click Properties to open the project properties.
  14. Select Web
    Click Web in the left navigation.
  15. Copy the Project URL
    Copy the Project Url value.
  16. Add a platform to the portal
    Back on the Application Registration Portal page, click Add Platform>Web.
  17. Add the Project URL
    Paste the value of Project Url into the Redirect URIs field
  18. Save the changes
    Scroll to the bottom of the page and click Save.
  19. Open the WebApp properties
    Right-click QuickStartCalendarWebApp and click Properties to open the project properties
  20. Select Web
    Click Web in the left navigation.
  21. Add a Start Action value
    Under Start Action Choose Specific Page option and Type its value as Account/SignOut
  22. Compile and launch the application
    Press F5 to compile and launch your new application in the default browser.
  23. Sign in with the supplied Office 365 credentials
    Once the Graph and AAD v2 Auth Endpoint Starter page appears, click Sign in and login to your Office 365 account.
  24. Review and accept the permissions
    Review the permissions the application is requesting, and click Accept.
  25. Stop the debugger
    Before 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.
  1. Select Manage NuGet Packages
    In the Solution Explorer right-click the QuickStartCalendarWebApp project and select Manage NuGet Packages....
  2. Change the source to local
    Change Package Source (on the upper right corner) to Microsoft Graph local.
  3. Search for Microsoft.Graph
    Click Browse and search for Microsoft.Graph.
  4. Install the Graph SDK
    Select the Microsoft Graph SDK and click Install.
  5. Select Manage NuGet Packages
    In the Solution Explorer right-click the QuickStartCalendarWebApp project and select Manage NuGet Packages....
  6. Change the source to nuget.org
    Change Package Source (on the upper right corner) to nuget.org.
  7. Browse for the bootstrap
    Click Browse and search for Bootstrap.v3.Datetimepicker.CSS.
  8. Install the bootstrap
    Select Bootstrap.v3.Datetimepicker.CSS and click Install.
  9. Replace code in the cs file
    Open 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"));
  10. Add a controller
    Find the Controllers folder under QuickStartCalendarWebApp, right-click it and select Add>Controller.
  11. Select the MVC 5 Controller
    Select MVC 5 Controller - Empty and click Add.
  12. Change the name of the controller
    Change the name of the controller to CalendarController and click Add.
  13. Replace the reference in the class
    Replace 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;
  14. Add code to the class
    Add 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;
    }
  15. Replace code in the class
    Replace 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 Task Index(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
  16. Add code to the class
    Add 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 Task Detail(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 Task GetEventBody(string eventId)
    {
    return Content(TempData[eventId] as string);
    }
  17. Add code to the class
    In 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.
  18. Add code to the class
    Add 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 Task Accept(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 });
    }
  19. Add code to the class
    Add 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 Task Tentative(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 });
    }
  20. Add code to the class
    Add 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 Task Decline(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");
    }
  21. Open the Layout.cshmtl
    Locate the Views/Shared folder in the project and then open the _Layout.cshtml file found in the Views/Shared folder.
  22. Find and update the section with link near the top
    Locate 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)
  23. Select the calendar folder
    Expand Views folder in QuickStartCalendarWebApp and select the folder Calendar.
  24. Add a new item
    Right-click Calendar and select Add then New Item.
  25. Modify the MVC 5 view page name
    Select MVC 5 View Page (Razor) and change the filename Index.cshtml and click Add.
  26. Replace the code in the cshtml
    In 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.
  27. Add a new view
    Expand the Views folder in QuickStartCalendarWebApp. Right-click Calendar and select Add then New Item.
  28. Rename the MVC 5 page
    Select MVC 5 View Page (Razor) and change the filename Detail.cshtml and click Add.
  29. Replace the code in the cshtml
    In 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.
  30. Debug the application
    Press F5 to begin debugging.
  31. Login with the supplied credentials
    When prompted, login with your Office 365 administrator account.
  32. Select the API link
    Click the Outlook Calendar API link in the navigation bar at the top of the page.
  33. Test the new app
    Try the app!

No comments: