public async Task<ActionResult> Create() { string token = (string)Session["access_token"]; string email = (string)Session["user_email"]; if (string.IsNullOrEmpty(token)) { // If there's no token in the session, redirect to Home return Redirect("/"); } try { OutlookServicesClient client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"), async () => { // Since we have it locally from the Session, just return it here. return token; }); Location location = new Location { DisplayName = "Water cooler" }; // Create a description for the event ItemBody body = new ItemBody { Content = "Status updates, blocking issues, and next steps", ContentType = BodyType.Text }; // Create the event object DateTimeTimeZone start=new DateTimeTimeZone() ; string dateTimeFormat = "yyyy-MM-ddThh:mm:ss"; string timeZone = "Pacific Standard Time";//"Eastern Standard Time"; start.DateTime = new DateTime(2016, 1, 22, 14, 30, 0).ToString(dateTimeFormat); start.TimeZone = timeZone; DateTimeTimeZone end = new DateTimeTimeZone(); end.DateTime = new DateTime(2016, 1, 22, 15, 30, 0).ToString(dateTimeFormat); end.TimeZone = timeZone; Event newEvent = new Event { Subject = "Sync up", Location = location, Start = start, End = end, Body = body }; newEvent.Recurrence = new PatternedRecurrence(); newEvent.Recurrence.Range = new RecurrenceRange(); string dateFormat = "yyyy-MM-dd"; newEvent.Recurrence.Range.EndDate = DateTime.Now.AddYears(1).ToString(dateFormat); newEvent.Recurrence.Range.StartDate = DateTime.Now.ToString(dateFormat); newEvent.Recurrence.Range.NumberOfOccurrences = 11; newEvent.Recurrence.Pattern = new RecurrencePattern(); newEvent.Recurrence.Pattern.Type = RecurrencePatternType.Weekly; newEvent.Recurrence.Pattern.Interval = 1; newEvent.Recurrence.Pattern.DaysOfWeek= new List<Microsoft.Office365.OutlookServices.DayOfWeek>() { Microsoft.Office365.OutlookServices.DayOfWeek.Friday }; // Add the event to the default calendar await client.Me.Events.AddEventAsync(newEvent); //client.Me.Calendars.AddCalendarAsync() //client.Me.Calendars.AddCalendarAsync(new ICalendar) var eventResults = await client.Me.Events .OrderByDescending(e => e.Start.DateTime) .Take(10) .Select(e => new Models.DisplayEvent(e.Subject, e.Start.DateTime, e.End.DateTime)) .ExecuteAsync(); return View("Calendar",eventResults.CurrentPage); } catch (AdalException ex) { return Content(string.Format("ERROR retrieving events: {0}", ex.Message)); } }
public MailStoreProviderSDK(string userName, string password) : base(userName, password) { _outlookClient = GetOutlookClient("Mail"); _user = _outlookClient.Me.ExecuteAsync().Result; DisplayName = _user.Id; RootFolder = new MailFolderProviderSDK(_outlookClient, _user.Id); }
// GET: Contacts public async Task<ActionResult> Index() { List<MyContact> myContacts = new List<MyContact>(); var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; AuthenticationContext authContext = new AuthenticationContext(string.Format(AADAppSettings.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId)); try { DiscoveryClient discClient = new DiscoveryClient(AADAppSettings.DiscoveryServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(AADAppSettings.DiscoveryServiceResourceId, new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); var dcr = await discClient.DiscoverCapabilityAsync("Contacts"); ViewBag.ResourceId = dcr.ServiceResourceId; OutlookServicesClient exClient = new OutlookServicesClient(dcr.ServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); var contactsResult = await exClient.Me.Contacts.ExecuteAsync(); do { var contacts = contactsResult.CurrentPage; foreach (var contact in contacts) { myContacts.Add(new MyContact { Name = contact.DisplayName }); } contactsResult = await contactsResult.GetNextPageAsync(); } while (contactsResult != null); } catch (AdalException exception) { //handle token acquisition failure if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently) { authContext.TokenCache.Clear(); ViewBag.ErrorMessage = "AuthorizationRequired"; } } return View(myContacts); }
private Office365Api() { // use file cache to persist token _authContext = new AuthenticationContext(_authority, new FileCache()); if (_authContext.TokenCache.ReadItems().Count() > 0) { // re-bind the AuthenticationContext to the authority that sourced the token in the cache // this is needed for the cache to work when asking a token from that authority // (the common endpoint never triggers cache hits) var cachedAuthority = _authContext.TokenCache.ReadItems().First().Authority; _authContext = new AuthenticationContext(cachedAuthority, new FileCache()); } else { // no previous tokens -> do nothing for now } // initialize outlook services client _client = new OutlookServicesClient(new Uri(_apiUrl), async () => { // Since we have it locally from the Session, just return it here. return _authResult.Token; }); }
/// <summary> /// Schedules meeting /// </summary> /// <param name="accessToken">Access Token for API</param> /// <param name="meeting">Meeting object containing all required data for scheduling meeting</param> /// <returns>Task of <see cref="Event"/></returns> public async Task <Office.Event> ScheduleMeeting(string accessToken, Office.Event meeting) { try { Office.Recipient organizer = new Office.Recipient(); Office.EmailAddress organizerEmail = new Office.EmailAddress(); organizerEmail.Address = "*****@*****.**"; // organizer email address organizerEmail.Name = "Display Name"; // organizer display name organizer.EmailAddress = organizerEmail; meeting.IsOrganizer = false; meeting.Organizer = organizer; Office.OutlookServicesClient sc = new Office.OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0/me/events"), () => GetAccessToken("office")); await sc.Me.Events.AddEventAsync(meeting); //var httpResponseMessage = await _httpService.AuthenticatedPost(ScheduleMeetingEndpoint, accessToken, meeting, "UTC"); //var scheduledMeeting = JsonConvert.DeserializeObject<Office.Event>(await httpResponseMessage.Content.ReadAsStringAsync()); return(null);// scheduledMeeting; } catch (Exception ex) { _loggingService.Error(ex); throw; } }
/// <summary> /// Checks that an OutlookServicesClient object is available. /// </summary> /// <returns>The OutlookServicesClient object. </returns> public static async Task<OutlookServicesClient> EnsureClientCreated() { AuthenticationContext = new AuthenticationContext(CommonAuthority); if (AuthenticationContext.TokenCache.ReadItems().Count() > 0) { // Bind the AuthenticationContext to the authority that sourced the token in the cache // this is needed for the cache to work when asking for a token from that authority // (the common endpoint never triggers cache hits) string cachedAuthority = AuthenticationContext.TokenCache.ReadItems().First().Authority; AuthenticationContext = new AuthenticationContext(cachedAuthority); } // Create a DiscoveryClient using the discovery endpoint Uri. DiscoveryClient discovery = new DiscoveryClient(DiscoveryServiceEndpointUri, async () => await AcquireTokenAsync(AuthenticationContext, DiscoveryResourceId)); // Now get the capability that you are interested in. var result = await discovery.DiscoverCapabilityAsync("Mail"); var client = new OutlookServicesClient( result.ServiceEndpointUri, async () => await AcquireTokenAsync(AuthenticationContext, result.ServiceResourceId)); return client; }
public MailStoreProviderSDK(string userName, string password) { _adClient = AuthenticationHelperSDK.GetGraphClientAsync(userName, password).GetResult(); _outlookClient = GetOutlookClient("Mail"); _user = _outlookClient.Me.ExecuteAsync().GetResult(); DisplayName = _user.Id; RootFolder = new MailFolderProviderSDK(_outlookClient, _user.Id); }
public void Init() { var settings = Settings.ExchangePrd; Its.Configuration.Settings.SettingsDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config"); var authSettings = Its.Configuration.Settings.Get<AuthSettings>(); if(String.IsNullOrWhiteSpace(authSettings.ClientId)) throw new Exception(String.Format("Create a file called AuthSettings.json in {0} and provide your O365 credentials via this JSON object:\r\n {1}", Its.Configuration.Settings.SettingsDirectory, AuthSettings.GetJsonTemplate())); var xauth = new XAuth.Auth(authSettings); client = new OutlookServicesClient(settings.Environment.EndpointUri, () => xauth.GetAccessToken(settings.Environment.ResourceId)); }
// GET: Calendar public async Task<ActionResult> Index() { // fetch from stuff user claims var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value; // discover contact endpoint var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret); var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId); // create auth context AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId)); // create O365 discovery client DiscoveryClient discovery = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint), async () => { var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, clientCredential, userIdentifier); return authResult.AccessToken; }); // query discovery service for endpoint for 'calendar' endpoint var dcr = await discovery.DiscoverCapabilityAsync("Calendar"); // create Outlook client using the calendar api endpoint OutlookServicesClient client = new OutlookServicesClient(dcr.ServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, clientCredential, userIdentifier); return authResult.AccessToken; }); // get contacts var results = await client.Me.Events.Take(20).ExecuteAsync(); ViewBag.Events = results.CurrentPage.OrderBy(c => c.Start); return View(); }
private async void btnDiscoverContacts_Click(object sender, RoutedEventArgs e) { String discoveryResultText = "Capability: {0} \nEndpoint Uri: {1} \nResource Id: {2}\n\n"; var capabilityContacts = ServiceCapabilities.Contacts.ToString(); CapabilityDiscoveryResult discoveryCapabilityResult = await Office365ServiceHelper.GetDiscoveryCapabilityResultAsync(capabilityContacts); txtBoxStatus.Text = String.Format(discoveryResultText, capabilityContacts, discoveryCapabilityResult.ServiceEndpointUri.ToString(), discoveryCapabilityResult.ServiceResourceId).Replace("\n", Environment.NewLine); OutlookServicesClient outlookContactsClient = new OutlookServicesClient(discoveryCapabilityResult.ServiceEndpointUri, async () => { return await Office365ServiceHelper.GetAccessTokenForResourceAsync(discoveryCapabilityResult); }); var contactsResults = await outlookContactsClient.Me.Contacts.ExecuteAsync(); do { var contacts = contactsResults.CurrentPage; foreach (var contact in contacts) { txtBoxStatus.Text += String.Format(discoveryResultText, capabilityContacts, contact.DisplayName, contact.JobTitle).Replace("\n", Environment.NewLine); } contactsResults = await contactsResults.GetNextPageAsync(); } while (contactsResults != null); }
public void Init() { var settings = Settings.ExchangePrd; Its.Configuration.Settings.SettingsDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config"); var authSettings = Its.Configuration.Settings.Get<AuthSettings>(); if (String.IsNullOrWhiteSpace(authSettings.ClientId)) throw new Exception(String.Format("Create a file called AuthSettings.json in {0} and provide your O365 credentials via this JSON object:\r\n {1}", Its.Configuration.Settings.SettingsDirectory, AuthSettings.GetJsonTemplate())); var xauth = new XAuth.Auth(authSettings); _client = new OutlookServicesClient(settings.Environment.EndpointUri, () => xauth.GetAccessToken(settings.Environment.ResourceId)); _tempContact = new Contact { DisplayName = "Test User" + new Random().NextDouble(), GivenName = "GivenName", Surname = "Surname" }; _client.Me.Contacts.AddContactAsync(_tempContact).Wait(); }
// GET: Mail public async Task<ActionResult> Index() { string clientID = ConfigurationManager.AppSettings["ida:ClientID"]; string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; string tenant = ConfigurationManager.AppSettings["ida:Tenant"]; string clientSecret = ConfigurationManager.AppSettings["ida:AppKey"]; string graphResourceID = ConfigurationManager.AppSettings["ida:GraphResourceID"]; string discoveryResourceID = "https://api.office.com/discovery/"; string discoveryServiceEndpointUri = "https://api.office.com/discovery/v1.0/me/"; string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant); List<MyMessage> myMessages = new List<MyMessage>(); var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; //Create an authentication context from cache AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCache(signInUserId)); try { DiscoveryClient discClient = new DiscoveryClient(new Uri(discoveryServiceEndpointUri), async () => { //Get an access token to the discovery service var authResult = await authContext.AcquireTokenSilentAsync(discoveryResourceID, new ClientCredential(clientID, clientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); var dcr = await discClient.DiscoverCapabilityAsync("Mail"); OutlookServicesClient exClient = new OutlookServicesClient(dcr.ServiceEndpointUri, async () => { //Get an access token to the Messages var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(clientID, clientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); var messagesResult = await exClient.Me.Messages.ExecuteAsync(); do { var messages = messagesResult.CurrentPage; foreach (var message in messages) { myMessages.Add(new MyMessage { Subject = message.Subject, From = message.Sender.EmailAddress.Address }); } messagesResult = await messagesResult.GetNextPageAsync(); } while (messagesResult != null); } catch (AdalException exception) { //handle token acquisition failure if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently) { authContext.TokenCache.Clear(); //handle token acquisition failure } } return View(myMessages); }
public async Task<ActionResult> Calendar() { string token = Context.Session.GetString("access_token"); string email = Context.Session.GetString("user_email"); ; if (string.IsNullOrEmpty(token)) { // If there's no token in the session, redirect to Home return Redirect("/"); } try { OutlookServicesClient client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v1.0"), async () => { // Since we have it locally from the Session, just return it here. return token; }); client.Context.SendingRequest2 += (sender, e) => InsertXAnchorMailboxHeader(sender, e, email); var eventResults = await client.Me.Events .OrderBy(e => e.Start) .Take(20) .Select(e => new CalendarEvent { Id = e.iCalUId, Body = e.Body.Content, Location = e.Location.DisplayName, Subject = e.Subject, Start = e.Start.Value.LocalDateTime, End = e.End.Value.LocalDateTime, }) .ExecuteAsync(); foreach (var eventResult in eventResults.CurrentPage) { var existingEvent = _dbContext.CalendarEvents .SingleOrDefault(c => c.Id == eventResult.Id); if (existingEvent == null) { var activity = new Activity { Date = eventResult.Start, MessageSource = "Calendar", Message = $"{eventResult.Subject} between {eventResult.Start} to {eventResult.End} at {eventResult.Location}.", }; _dbContext.CalendarEvents.Add(eventResult); _dbContext.Activities.Add(activity); } } _dbContext.SaveChanges(); return Ok(); } catch (AdalException ex) { return Content(string.Format("ERROR retrieving events: {0}", ex.Message)); } }
private OutlookServicesClient GetOutlookClient(string capability) { if (_outlookClient != null) { return _outlookClient; } try { Uri serviceEndpointUri; string serviceResourceId; GetService(capability, out serviceEndpointUri, out serviceResourceId); _outlookClient = new OutlookServicesClient( serviceEndpointUri, async () => await AuthenticationHelperSDK.GetTokenAsync(serviceResourceId)); } catch (Exception ex) { Log.Out(Log.Severity.Warning, string.Empty, ex.ToString()); } return _outlookClient; }
public async Task<ActionResult> Inbox(RallyNowDbContext dbContext) { string token = Context.Session.GetString("access_token"); string email = Context.Session.GetString("user_email"); if (string.IsNullOrEmpty(token)) { // If there's no token in the session, redirect to Home return Redirect("/"); } try { OutlookServicesClient client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v1.0"), async () => { return token; }); client.Context.SendingRequest2 += (sender, e) => InsertXAnchorMailboxHeader(sender, e, email); var mailResults = await client.Me.Messages .OrderByDescending(m => m.DateTimeReceived) .Take(20) .Select(m => new Emails { Id = m.Id, Subject = m.Subject, DateTimeSent = m.DateTimeReceived.Value.LocalDateTime, From = m.From.EmailAddress.Name, Body = m.BodyPreview, }) .ExecuteAsync(); foreach (var mailResult in mailResults.CurrentPage) { var existingEmail = _dbContext.Emails .SingleOrDefault(c => c.Id == mailResult.Id); if (existingEmail == null) { var activity = new Activity { Date = mailResult.DateTimeSent, MessageSource = "Email", Message = $"Subject: {mailResult.Subject} \r\n Body: {mailResult.Body}", }; WebClient webClient = new WebClient(); var response = webClient.DownloadString( "https://api.projectoxford.ai/luis/v1/application?id=f375bec7-02a2-4119-ab65-ca89ea673b22&subscription-key=11ea75021c944b31bf1a7d7c465175c5&q=" + HttpUtility.UrlEncode(mailResult.Body)); JObject jResults = JObject.Parse(response); try { var intent = jResults["intents"][0]["intent"].Value<string>(); if (intent != "builtin.intent.none") { var entities = jResults["entities"]; foreach (var entity in entities) { var type = entity["type"].Value<string>(); var resolution = entity["resolution"].Value<string>(); } } activity.Action = intent; } catch { } _dbContext.Emails.Add(mailResult); _dbContext.Activities.Add(activity); } } _dbContext.SaveChanges(); return Ok(); } catch (AdalException ex) { return Content(string.Format("ERROR retrieving messages: {0}", ex.Message)); } }
/// <summary> /// Checks that an OutlookServicesClient object is available. /// </summary> /// <returns>The OutlookServicesClient object. </returns> public static async Task<OutlookServicesClient> EnsureOutlookClientCreatedAsync() { try { AuthenticationContext = new AuthenticationContext(CommonAuthority); if (AuthenticationContext.TokenCache.ReadItems().Count() > 0) { // Bind the AuthenticationContext to the authority that sourced the token in the cache // this is needed for the cache to work when asking for a token from that authority // (the common endpoint never triggers cache hits) string cachedAuthority = AuthenticationContext.TokenCache.ReadItems().First().Authority; AuthenticationContext = new AuthenticationContext(cachedAuthority); } // Create a DiscoveryClient using the discovery endpoint Uri. DiscoveryClient discovery = new DiscoveryClient(DiscoveryServiceEndpointUri, async () => await AcquireTokenAsync(AuthenticationContext, DiscoveryResourceId)); // Now get the capability that you are interested in. CapabilityDiscoveryResult result = await discovery.DiscoverCapabilityAsync("Mail"); var client = new OutlookServicesClient( result.ServiceEndpointUri, async () => await AcquireTokenAsync(AuthenticationContext, result.ServiceResourceId)); return client; } // The following is a list of all exceptions you should consider handling in your app. // In the case of this sample, the exceptions are handled by returning null upstream. catch (DiscoveryFailedException dfe) { MessageDialogHelper.DisplayException(dfe as Exception); // Discovery failed. AuthenticationContext.TokenCache.Clear(); return null; } catch (MissingConfigurationValueException mcve) { MessageDialogHelper.DisplayException(mcve); // Connected services not added correctly, or permissions not set correctly. AuthenticationContext.TokenCache.Clear(); return null; } catch (AuthenticationFailedException afe) { MessageDialogHelper.DisplayException(afe); // Failed to authenticate the user AuthenticationContext.TokenCache.Clear(); return null; } catch (ArgumentException ae) { MessageDialogHelper.DisplayException(ae as Exception); // Argument exception AuthenticationContext.TokenCache.Clear(); return null; } }
/// <summary> /// Checks that an OutlookServicesClient object is available. /// </summary> /// <returns>The OutlookServicesClient object. </returns> public static async Task<OutlookServicesClient> GetOutlookClientAsync(string capability) { if (_outlookClient != null) { return _outlookClient; } else { try { // See the Discovery Service Sample (https://github.com/OfficeDev/Office365-Discovery-Service-Sample) // for an approach that improves performance by storing the discovery service information in a cache. DiscoveryClient discoveryClient = new DiscoveryClient( async () => await GetTokenHelperAsync(AuthenticationContext, DiscoveryResourceId)); // Get the specified capability ("Mail"). CapabilityDiscoveryResult result = await discoveryClient.DiscoverCapabilityAsync(capability); _outlookClient = new OutlookServicesClient( result.ServiceEndpointUri, async () => await GetTokenHelperAsync(AuthenticationContext, result.ServiceResourceId)); return _outlookClient; } // The following is a list of all exceptions you should consider handling in your app. // In the case of this sample, the exceptions are handled by returning null upstream. catch (DiscoveryFailedException dfe) { // Discovery failed. Debug.WriteLine("Exception: " + dfe.Message); AuthenticationContext.TokenCache.Clear(); return null; } catch (ArgumentException ae) { // Argument exception Debug.WriteLine("Exception: " + ae.Message); AuthenticationContext.TokenCache.Clear(); return null; } } }
private static async Task<OutlookServicesClient> EnsureClient() { var uri = new Uri("https://outlook.office.com/api/v2.0/"); var client = new OutlookServicesClient(uri, async () => await GetAccessToken()); return client; }
/// <summary> /// Checks that an OutlookServicesClient object is available. /// </summary> /// <returns>The OutlookServicesClient object. </returns> public static async Task<OutlookServicesClient> GetOutlookClientAsync(string capability) { //Check to see if this client has already been created. If so, return it. Otherwise, create a new one. if (_outlookClient != null) { return _outlookClient; } else { try { // Now get the capability that you are interested in. CapabilityDiscoveryResult result = await GetDiscoveryCapabilityResultAsync(capability); _outlookClient = new OutlookServicesClient( result.ServiceEndpointUri, async () => await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId)); return _outlookClient; } // The following is a list of all exceptions you should consider handling in your app. // In the case of this sample, the exceptions are handled by returning null upstream. catch (DiscoveryFailedException dfe) { MessageDialogHelper.DisplayException(dfe as Exception); // Discovery failed. _authenticationContext.TokenCache.Clear(); return null; } catch (MissingConfigurationValueException mcve) { MessageDialogHelper.DisplayException(mcve); // Connected services not added correctly, or permissions not set correctly. _authenticationContext.TokenCache.Clear(); return null; } catch (AuthenticationFailedException afe) { MessageDialogHelper.DisplayException(afe); // Failed to authenticate the user _authenticationContext.TokenCache.Clear(); return null; } catch (ArgumentException ae) { MessageDialogHelper.DisplayException(ae as Exception); // Argument exception _authenticationContext.TokenCache.Clear(); return null; } } }
/// <summary> /// Signs the user out of the service. /// </summary> public static void SignOut() { AuthenticationContext.TokenCache.Clear(); // Clean up all existing clients. _outlookClient = null; // Clear stored values from last authentication. App._settings.TenantId = null; App._settings.LastAuthority = null; }
public async Task<ActionResult> Index(string code) { List<MyEvent> eventList = new List<MyEvent>(); AuthenticationContext authContext = new AuthenticationContext( ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common", true); ClientCredential creds = new ClientCredential( ConfigurationManager.AppSettings["ida:ClientID"], ConfigurationManager.AppSettings["ida:Password"]); DiscoveryClient disco = GetFromCache("DiscoveryClient") as DiscoveryClient; CapabilityDiscoveryResult eventsDisco =GetFromCache("EventsDiscovery") as CapabilityDiscoveryResult; //Redirect to login page if we do not have an //authorization code for the Discovery service if (disco == null && code == null) { Uri redirectUri = authContext.GetAuthorizationRequestURL( discoResource, creds.ClientId, new Uri(Request.Url.AbsoluteUri.Split('?')[0]), UserIdentifier.AnyUser, string.Empty); return Redirect(redirectUri.ToString()); } //Create a DiscoveryClient using the authorization code if (disco == null && code != null) { disco = new DiscoveryClient(new Uri(discoEndpoint), async () => { var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync( code, new Uri(Request.Url.AbsoluteUri.Split('?')[0]), creds); return authResult.AccessToken; }); } if (disco != null && code != null & eventsDisco == null) { //Discover required capabilities eventsDisco = await disco.DiscoverCapabilityAsync("Calendar"); SaveInCache("EventsDiscovery", eventsDisco); code = null; //Get authorization code for the calendar Uri redirectUri = authContext.GetAuthorizationRequestURL( eventsDisco.ServiceResourceId, creds.ClientId, new Uri(Request.Url.AbsoluteUri.Split('?')[0]), UserIdentifier.AnyUser, string.Empty); return Redirect(redirectUri.ToString()); } //Get the calendar events if (disco != null && code != null & eventsDisco != null) { OutlookServicesClient outlookClient = new OutlookServicesClient(eventsDisco.ServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync( code, new Uri(Request.Url.AbsoluteUri.Split('?')[0]), creds); return authResult.AccessToken; }); //Get the events for the next 8 hours var eventResults = await (from i in outlookClient.Me.Events where i.End >= DateTimeOffset.UtcNow && i.End <= DateTimeOffset.UtcNow.AddHours(8) select i).Take(5).ExecuteAsync(); var events = eventResults.CurrentPage.OrderBy(e => e.Start); foreach (var e in events) { eventList.Add(new MyEvent { Id = e.Id, Body = e.Body == null ? string.Empty : e.Body.Content, End = e.End, Location = e.Location == null ? string.Empty : e.Location.DisplayName, Start = e.Start, Subject = e.Subject == null ? string.Empty : e.Subject }); } //cache the events SaveInCache("Events", eventList); } return View(); }
public async Task<ActionResult> Index() { List<EmailMessage> myMessages = new List<EmailMessage>(); if (User.Identity.IsAuthenticated) { var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(signInUserId)); try { DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); var dcr = await discClient.DiscoverCapabilityAsync("Mail"); OutlookServicesClient exClient = new OutlookServicesClient(dcr.ServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); var messagesResult = await exClient.Me.Folders.GetById("Inbox").Messages.Take(20).ExecuteAsync(); //do //{ var msgs = messagesResult.CurrentPage; foreach (var m in msgs) { myMessages.Add(new EmailMessage { Subject = m.Subject, Received = m.DateTimeReceived.Value.DateTime, FromName = m.From.EmailAddress.Name, FromEmail = m.From.EmailAddress.Address, HasAttachments = m.HasAttachments.GetValueOrDefault(false), Importance = m.Importance.ToString(), Preview = m.BodyPreview, IsRead = m.IsRead.GetValueOrDefault(false) }); } //messagesResult = await messagesResult.GetNextPageAsync(); //messagesResult = null; //} while (messagesResult != null); } catch (AdalException exception) { //handle token acquisition failure if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently) { authContext.TokenCache.Clear(); //handle token acquisition failure } } } return View(myMessages); }
/// <summary> /// Signs the user out of the service. /// </summary> public static async Task SignOutAsync() { if (string.IsNullOrEmpty(LoggedInUser)) { return; } _authenticationContext.TokenCache.Clear(); //Clean up all existing clients _graphClient = null; _outlookClient = null; _sharePointClient = null; //Clear stored values from last authentication. Leave value for LoggedInUser so that we can try again if logout fails. _settings.Values["TenantId"] = null; _settings.Values["LastAuthority"] = null; }
/// <summary> /// Checks that an OutlookServicesClient object is available. /// </summary> /// <returns>The OutlookServicesClient object. </returns> public static async Task<OutlookServicesClient> GetOutlookClientAsync(string capability) { if (_outlookClient != null) { return _outlookClient; } else { try { //First, look for the authority used during the last authentication. //If that value is not populated, use CommonAuthority. string authority = null; if (String.IsNullOrEmpty(LastAuthority)) { authority = CommonAuthority; } else { authority = LastAuthority; } // Create an AuthenticationContext using this authority. _authenticationContext = new AuthenticationContext(authority); // Set the value of _authenticationContext.UseCorporateNetwork to true so that you // can use this app inside a corporate intranet. If the value of UseCorporateNetwork // is true, you also need to add the Enterprise Authentication, Private Networks, and // Shared User Certificates capabilities in the Package.appxmanifest file. _authenticationContext.UseCorporateNetwork = true; //See the Discovery Service Sample (https://github.com/OfficeDev/Office365-Discovery-Service-Sample) //for an approach that improves performance by storing the discovery service information in a cache. DiscoveryClient discoveryClient = new DiscoveryClient( async () => await GetTokenHelperAsync(_authenticationContext, DiscoveryResourceId)); // Get the specified capability ("Mail"). CapabilityDiscoveryResult result = await discoveryClient.DiscoverCapabilityAsync(capability); var token = await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId); // Check the token if (String.IsNullOrEmpty(token)) { // User cancelled sign-in return null; } else { _outlookClient = new OutlookServicesClient( result.ServiceEndpointUri, async () => await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId)); return _outlookClient; } } // The following is a list of all exceptions you should consider handling in your app. // In the case of this sample, the exceptions are handled by returning null upstream. catch (DiscoveryFailedException dfe) { // Discovery failed. Debug.WriteLine("Exception: " + dfe.Message); _authenticationContext.TokenCache.Clear(); return null; } catch (ArgumentException ae) { // Argument exception Debug.WriteLine("Exception: " + ae.Message); _authenticationContext.TokenCache.Clear(); return null; } } }
// GET: Contacts public async Task<ActionResult> Index() { // This code creates the authentication context, using the signed-in // Office 365 user Id and the authority for your Office 365 tenancy. List<MyContact> myContacts = new List<MyContact>(); var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(signInUserId)); try { // This code attempts to acquire an access token to the Discovery Service, // passing the application's client id and app password, as well the user's credentials. // Because the user authentication token has been cached, // the controller is able to acquire the necessary access token silently, // without having to prompt the user again for their credentials. // With the access token, the application can create a Discovery Service client object, // and use the discovery client object to determine the resource endpoint for the // Office 365 service Contacts APIs. DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); var dcr = await discClient.DiscoverCapabilityAsync("Contacts"); // This code contacts the resource endpoint for the Office 365 service Contacts APIs, // again silenlty passing the application and user credentials to acquire // an access token to the Outlook service. // Once the access token is recieved, the code can initialize an Outlook client object. OutlookServicesClient exClient = new OutlookServicesClient(dcr.ServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); // The code then uses the Me property of the Outlook client object to // retrieve contacts information for this user var contactsResult = await exClient.Me.Contacts.ExecuteAsync(); do { var contacts = contactsResult.CurrentPage; // read through the list of user contacts and add to the myContacts list foreach (var contact in contacts) { myContacts.Add(new MyContact { Name = contact.DisplayName }); } contactsResult = await contactsResult.GetNextPageAsync(); } while (contactsResult != null); } catch (AdalException exception) { //todo: handle token acquisition failure if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently) { authContext.TokenCache.Clear(); //todo: handle token acquisition failure } } // return a view using the myContacts list as a listing the contacts display names return View(myContacts); }
/// <summary> /// Signs the user out of the service. /// </summary> public static void SignOut() { _authenticationContext.TokenCache.Clear(); //Clean up all existing clients _outlookClient = null; //Clear stored values from last authentication. _settings.Values["TenantId"] = null; _settings.Values["LastAuthority"] = null; _settings.Values["LoggedInUser"] = null; _settings.Values["LoggedInUserEmail"] = null; }
public MailItemProviderSDK(OutlookServicesClient outlookClient, IMessage msg) { _outlookClient = outlookClient; _message = msg; }
public async Task<ActionResult> Inbox() { string token = (string)Session["access_token"]; string email = (string)Session["user_email"]; if (string.IsNullOrEmpty(token)) { // If there's no token in the session, redirect to Home return Redirect("/"); } try { OutlookServicesClient client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"), async () => { // Since we have it locally from the Session, just return it here. return token; }); client.Context.SendingRequest2 += new EventHandler<Microsoft.OData.Client.SendingRequest2EventArgs> ( (sender, e) => InsertXAnchorMailboxHeader(sender, e, email)); var mailResults = await client.Me.Messages .OrderByDescending(m => m.ReceivedDateTime) .Take(10) .Select(m => new Models.DisplayMessage(m.Subject, m.ReceivedDateTime, m.From)) .ExecuteAsync(); return View(mailResults.CurrentPage); } catch (AdalException ex) { return Content(string.Format("ERROR retrieving messages: {0}", ex.Message)); } }
/// <summary> /// Use the OutlookServicesClient to get Exchange contacts /// </summary> /// <param name="code">The authorization code to use when getting an access token</param> /// <returns></returns> public async Task<ActionResult> Contacts(string code) { AuthenticationContext authContext = new AuthenticationContext( ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common", true); ClientCredential creds = new ClientCredential( ConfigurationManager.AppSettings["ida:ClientID"], ConfigurationManager.AppSettings["ida:Password"]); //Get the discovery information that was saved earlier CapabilityDiscoveryResult cdr = Helpers.GetFromCache("ContactsDiscoveryResult") as CapabilityDiscoveryResult; //Get a client, if this page was already visited OutlookServicesClient outlookClient = Helpers.GetFromCache("OutlookClient") as OutlookServicesClient; //Get an authorization code if needed if (outlookClient == null && cdr != null && code == null) { Uri redirectUri = authContext.GetAuthorizationRequestURL( cdr.ServiceResourceId, creds.ClientId, new Uri(Request.Url.AbsoluteUri.Split('?')[0]), UserIdentifier.AnyUser, string.Empty); return Redirect(redirectUri.ToString()); } //Create the OutlookServicesClient if (outlookClient == null && cdr != null && code != null) { outlookClient = new OutlookServicesClient(cdr.ServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync( code, new Uri(Request.Url.AbsoluteUri.Split('?')[0]), creds); return authResult.AccessToken; }); Helpers.SaveInCache("OutlookClient", outlookClient); } //Get the contacts var contactsResults = await outlookClient.Me.Contacts.ExecuteAsync(); List<MyContact> contactList = new List<MyContact>(); foreach (var contact in contactsResults.CurrentPage.OrderBy(c => c.Surname)) { contactList.Add(new MyContact { Id = contact.Id, GivenName = contact.GivenName, Surname = contact.Surname, DisplayName = contact.Surname + ", " + contact.GivenName, CompanyName = contact.CompanyName, EmailAddress1 = contact.EmailAddresses.FirstOrDefault().Address, BusinessPhone1 = contact.BusinessPhones.FirstOrDefault(), HomePhone1 = contact.HomePhones.FirstOrDefault() }); } //Save the contacts Helpers.SaveInCache("ContactList", contactList); //Show the contacts return View(contactList); }
public async Task<ActionResult> Contacts() { List<Persona> myContacts = new List<Persona>(); if (User.Identity.IsAuthenticated) { var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(signInUserId)); try { DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); var dcr = await discClient.DiscoverCapabilityAsync("Contacts"); OutlookServicesClient exClient = new OutlookServicesClient(dcr.ServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); var contactsResult = await exClient.Me.Contacts.Take(20).ExecuteAsync(); //do //{ var contacts = contactsResult.CurrentPage; foreach (var c in contacts) { var firstEmail = c.EmailAddresses.FirstOrDefault(); string email = ""; if (firstEmail != null) email = firstEmail.Address; myContacts.Add(new Persona { DisplayName = c.DisplayName, Email = email, JobTitle = c.JobTitle, CompanyName = c.CompanyName, Im = c.ImAddresses.FirstOrDefault(), OfficeLocation = c.OfficeLocation, Phone = c.BusinessPhones.FirstOrDefault() }); } // contactsResult = await contactsResult.GetNextPageAsync(); //} while (contactsResult != null); } catch (AdalException exception) { //handle token acquisition failure if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently) { authContext.TokenCache.Clear(); //handle token acquisition failure } } } return View(myContacts); }
public async Task<ActionResult> Calendar() { string token = (string)Session["access_token"]; string email = (string)Session["user_email"]; if (string.IsNullOrEmpty(token)) { // If there's no token in the session, redirect to Home return Redirect("/"); } try { OutlookServicesClient client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"), async () => { // Since we have it locally from the Session, just return it here. return token; }); client.Context.SendingRequest2 += new EventHandler<Microsoft.OData.Client.SendingRequest2EventArgs>( (sender, e) => InsertXAnchorMailboxHeader(sender, e, email)); // Use calendar view to get meetings for the next N hours var startDateTime = new DateTimeOffset(DateTime.Now); var endDateTime = new DateTimeOffset(DateTime.Now.AddHours(+12)); var eventResults = await client.Me.GetCalendarView(startDateTime, endDateTime) .OrderByDescending(e => e.Start.DateTime) .Take(10) .Select(e => new Models.DisplayEvent(e.Subject, e.Start.DateTime, e.End.DateTime, e.Location, e.Organizer)) .ExecuteAsync(); return View(eventResults.CurrentPage); } catch (AdalException ex) { return Content(string.Format("ERROR retrieving events: {0}", ex.Message)); } }