Ejercicio: Incorporar Microsoft Graph en aplicaciones web ASP.NET MVC
En este ejercicio, incorporará Microsoft Graph a la aplicación. Para esta aplicación, usará la Biblioteca cliente de Microsoft Graph para .NET para realizar llamadas a Microsoft Graph.
Obtener eventos del calendario desde Outlook
Para empezar, amplíe la clase GraphHelper
que creó en el último módulo.
Agregue las siguientes instrucciones using
a la parte superior del archivo Helpers/GraphHelper.cs.
using graph_tutorial.TokenStorage;
using Microsoft.Identity.Client;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Claims;
using System.Web;
Agregue el código siguiente a la clase GraphHelper
.
// Load configuration settings from PrivateSettings.config
private static string appId = ConfigurationManager.AppSettings["ida:AppId"];
private static string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"];
private static string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
private static List<string> graphScopes =
new List<string>(ConfigurationManager.AppSettings["ida:AppScopes"].Split(' '));
public static async Task<IEnumerable<Event>> GetEventsAsync()
{
var graphClient = GetAuthenticatedClient();
var events = await graphClient.Me.Events.Request()
.Select("subject,organizer,start,end")
.OrderBy("createdDateTime DESC")
.GetAsync();
return events.CurrentPage;
}
private static GraphServiceClient GetAuthenticatedClient()
{
return new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
var idClient = ConfidentialClientApplicationBuilder.Create(appId)
.WithRedirectUri(redirectUri)
.WithClientSecret(appSecret)
.Build();
var tokenStore = new SessionTokenStore(idClient.UserTokenCache,
HttpContext.Current, ClaimsPrincipal.Current);
var userUniqueId = tokenStore.GetUsersUniqueId(ClaimsPrincipal.Current);
var account = await idClient.GetAccountAsync(userUniqueId);
// By calling this here, the token can be refreshed
// if it's expired right before the Graph call is made
var result = await idClient.AcquireTokenSilent(graphScopes, account)
.ExecuteAsync();
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", result.AccessToken);
}));
}
Nota:
Tenga en cuenta lo que está haciendo este código.
- La función
GetAuthenticatedClient
inicia unGraphServiceClient
con un proveedor de autenticación que llama aAcquireTokenSilent
. - En la función
GetEventsAsync
:- La dirección URL a la que se llamará es
/v1.0/me/events
. - La función
Select
limita los campos devueltos para cada evento a los que realmente usará la vista. - La función
OrderBy
ordena los resultados por fecha y hora en que se crearon, con el elemento más reciente en primer lugar.
- La dirección URL a la que se llamará es
Crear un controlador para las vistas de calendario. Haga clic con el botón derecho en la carpeta Controladores de Explorador de soluciones y seleccione Agregar > controlador.... Elija Controlador MVC 5 : vacío y seleccione Agregar. Asigne al controlador el nombre CalendarController y seleccione Agregar. Reemplace todo el contenido del archivo nuevo con el código siguiente.
using graph_tutorial.Helpers;
using System;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace graph_tutorial.Controllers
{
public class CalendarController : BaseController
{
// GET: Calendar
[Authorize]
public async Task<ActionResult> Index()
{
var events = await GraphHelper.GetEventsAsync();
// Change start and end dates from UTC to local time
foreach (var ev in events)
{
ev.Start.DateTime = DateTime.Parse(ev.Start.DateTime).ToLocalTime().ToString();
ev.Start.TimeZone = TimeZoneInfo.Local.Id;
ev.End.DateTime = DateTime.Parse(ev.End.DateTime).ToLocalTime().ToString();
ev.End.TimeZone = TimeZoneInfo.Local.Id;
}
return Json(events, JsonRequestBehavior.AllowGet);
}
}
}
Inicie la aplicación, inicie sesión y seleccione el vínculo Calendario en la barra de navegación. Si funciona todo, debería ver un volcado JSON de eventos en el calendario del usuario.
Mostrar los resultados
Ahora puede agregar una vista para mostrar los resultados de una manera más fácil de usar.
En Explorador de soluciones, haga clic con el botón derecho en la carpeta Vistas/Calendario y seleccione Agregar > vista.... Elija VISTA DE MVC 5 y seleccione Agregar. Asigne a la vista el nombre Índice y seleccione Agregar. Reemplace todo el contenido del archivo nuevo con el código siguiente.
@model IEnumerable<Microsoft.Graph.Event>
@{
ViewBag.Current = "Calendar";
}
<h1>Calendar</h1>
<table class="table">
<thead>
<tr>
<th scope="col">Organizer</th>
<th scope="col">Subject</th>
<th scope="col">Start</th>
<th scope="col">End</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.Organizer.EmailAddress.Name</td>
<td>@item.Subject</td>
<td>@Convert.ToDateTime(item.Start.DateTime).ToString("M/d/yy h:mm tt")</td>
<td>@Convert.ToDateTime(item.End.DateTime).ToString("M/d/yy h:mm tt")</td>
</tr>
}
</tbody>
</table>
Esto recorrerá una colección de eventos y agregará una fila de tabla para cada uno.
Quite la línea return Json(events, JsonRequestBehavior.AllowGet);
de la función Index
en Controllers/CalendarController.cs y sustitúyala por el siguiente código.
return View(events);
Inicie la aplicación, inicie sesión y seleccione el vínculo Calendario. La aplicación ahora debería presentar una tabla de eventos.
Resumen
En este ejercicio, ha incorporado Microsoft Graph a la aplicación. Para esta aplicación, ha usado la Biblioteca cliente de Microsoft Graph para .NET para realizar llamadas a Microsoft Graph.