Skip to content

Instantly share code, notes, and snippets.

@jasonjoh
Created February 12, 2016 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonjoh/40d9e44fa488dc79d82e to your computer and use it in GitHub Desktop.
Save jasonjoh/40d9e44fa488dc79d82e to your computer and use it in GitHub Desktop.
BuildingRequest event handler for OutlookServicesClient to insert user's email address into the Users segment
// When using the v2 or beta endpoints of the Outlook API, the OutlookServicesClient class sends PATCH requests
// to a URL that contains the user's unique identifier in <guid>@<guid> format. This fails when authenticating
// with an app-only token.
// To work around this, you can implement an event handler for the BuildingRequest event on the client's .Context
// property, and replace the old user spec with the user's email.
// Sample function that calls an update on an event
public async Task<ActionResult> UpdateEvent(AppState passedAppState)
{
OutlookServicesClient client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"), async () =>
{
// Since we have it locally from the app state, just return it here.
return passedAppState.AccessToken;
});
client.Context.BuildingRequest += new EventHandler<Microsoft.OData.Client.BuildingRequestEventArgs>(
(sender, e) => FixAppOnlyUrl(sender, e, passedAppState.MailboxSmtpAddress));
try
{
var updateEvent = await client.Users[passedAppState.MailboxSmtpAddress].Events.GetById(passedAppState.EventId).ExecuteAsync();
updateEvent.Subject = "modified: " + updateEvent.Subject;
await updateEvent.UpdateAsync();
}
catch (Exception ex)
{
...
}
}
// BuildingRequest event handler
private void FixAppOnlyUrl(object sender, BuildingRequestEventArgs e, string email)
{
string escapedEmail = email.Replace("@", "%40");
string oldUrl = e.RequestUri.ToString();
// Only muck with the URL if it has the /Users() segment and
// it doesn't already contain the user's email address
if (oldUrl.ToLower().Contains("/users(") && !oldUrl.ToLower().Contains(escapedEmail.ToLower()))
{
string newUrl = Regex.Replace(oldUrl, "[Uu]sers\\('.+?'\\)", "Users('" + escapedEmail + "')");
e.RequestUri = new Uri(newUrl);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment