public async Task <ActionResult> Contacts() { string token = await GetAccessToken(); if (string.IsNullOrEmpty(token)) { // If there's no token in the session, redirect to Home return(Redirect("/")); } string userEmail = await GetUserEmail(); OutlookServicesClient client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"), GetAccessToken); client.Context.SendingRequest2 += new EventHandler <Microsoft.OData.Client.SendingRequest2EventArgs>( (sender, e) => InsertXAnchorMailboxHeader(sender, e, userEmail)); try { var contactResults = await client.Me.Contacts .OrderBy(c => c.DisplayName) .Take(10) .Select(c => new Models.DisplayContact(c.DisplayName, c.EmailAddresses, c.MobilePhone1)) .ExecuteAsync(); return(View(contactResults.CurrentPage)); } catch (MsalException ex) { return(RedirectToAction("Error", "Home", new { message = "ERROR retrieving contacts", debug = ex.Message })); } }
public async Task <ActionResult> Inbox() { string token = await GetAccessToken(); if (string.IsNullOrEmpty(token)) { // If there's no token in the session, redirect to Home return(Redirect("/")); } string userEmail = await GetUserEmail(); OutlookServicesClient client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"), GetAccessToken); client.Context.SendingRequest2 += new EventHandler <Microsoft.OData.Client.SendingRequest2EventArgs>( (sender, e) => InsertXAnchorMailboxHeader(sender, e, userEmail)); try { 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 (MsalException ex) { return(RedirectToAction("Error", "Home", new { message = "ERROR retrieving messages", debug = ex.Message })); } }
/// <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); }
private async void GetMessages() { // use the Microsoft.Experimental.IdentityModel.Clients.ActiveDirectory nuget package for auth var authContext = new AuthenticationContext(authority, _cache); var result = await authContext.AcquireTokenAsync( new[] { "https://outlook.office.com/mail.read" }, null, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Always, this)); // use the Microsoft.Office365.OutlookServices-V2.0 nuget package from now on var client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"), () => Task.FromResult(result.Token)); var messages = await client.Me.Messages .Take(10) // get only 10 messages .ExecuteAsync(); // fill some list box // (beware, some messages have a null subject) foreach (var msg in messages.CurrentPage) { listBox1.Items.Add(msg.Subject); } }
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(); }
private void CloseCurrentSession() { client = null; dataGridView_FolderProps.Rows.Clear(); dataGridView_FolderProps.Columns.Clear(); treeView_Mailbox.Nodes.Clear(); }
internal MailFolderProviderSDK(OutlookServicesClient outlookClient, string rootName) { _isRoot = true; _outlookClient = outlookClient; Name = rootName; }
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 static async Task <bool> UpdateMessageAsync(string MessageId, string UpdatedContent) { try { // Make sure we have a reference to the Outlook Services client OutlookServicesClient outlookClient = await GetOutlookClientAsync(); // Get the message to update and set changed properties IMessage message = await outlookClient.Me.Messages.GetById(MessageId).ExecuteAsync(); message.Body = new ItemBody { Content = UpdatedContent, ContentType = BodyType.HTML }; await message.UpdateAsync(); Debug.WriteLine("Updated message: " + message.Id); return(true); } catch (ODataErrorException ex) { // GetById will throw an ODataErrorException when the // item with the specified Id can't be found in the contact store on the server. Debug.WriteLine(ex.Message); return(false); } }
public static async Task sendMail(OutlookServicesClient mailClient, List <Message> newMails) { foreach (var newMail in newMails) { await mailClient.Me.SendMailAsync(newMail, true); } }
public static async Task <bool> GetFileAttachmentsAsync(string MessageId) { try { // Make sure we have a reference to the Outlook Services client OutlookServicesClient outlookClient = await GetOutlookClientAsync(); var message = outlookClient.Me.Messages.GetById(MessageId); var attachmentsResult = await message.Attachments.ExecuteAsync(); var attachments = attachmentsResult.CurrentPage.ToList(); foreach (IFileAttachment attachment in attachments) { Debug.WriteLine("Attachment: " + attachment.Name); } return(true); } catch (ODataErrorException ex) { // GetById will throw an ODataErrorException when the // item with the specified Id can't be found in the contact store on the server. Debug.WriteLine(ex.Message); return(false); } }
public static async Task <string> CreateMailFolderAsync(string ParentFolder, string NewFolderName) { try { OutlookServicesClient outlookClient = await GetOutlookClientAsync(); Folder newFolder = new Folder { DisplayName = NewFolderName }; await outlookClient.Me.Folders.GetById(ParentFolder).ChildFolders.AddFolderAsync(newFolder); Debug.WriteLine("Created folder: " + newFolder.Id); // Get the ID of the new folder. return(newFolder.Id); } catch (ODataErrorException ex) { // GetById will throw an ODataErrorException when the // item with the specified Id can't be found in the contact store on the server. Debug.WriteLine(ex.Message); return(null); } }
public static async Task <bool> ForwardMessageAsync( string MessageId, string ForwardMessage, string RecipientAddress) { try { // Make sure we have a reference to the Outlook Services client OutlookServicesClient outlookClient = await GetOutlookClientAsync(); List <Recipient> toRecipients = new List <Recipient>(); toRecipients.Add(new Recipient { EmailAddress = new EmailAddress { Address = RecipientAddress } }); await outlookClient.Me.Messages.GetById(MessageId).ForwardAsync(ForwardMessage, toRecipients); Debug.WriteLine("Forwarded message: " + MessageId); return(true); } catch (ODataErrorException ex) { // GetById will throw an ODataErrorException when the // item with the specified Id can't be found in the contact store on the server. Debug.WriteLine(ex.Message); return(false); } }
public async Task <List <MyContact> > GetContacts(int pageIndex, int pageSize) { // acquire a O365 client to retrieve contacts OutlookServicesClient client = await EnsureClientCreated(); // get contacts, sort by their last name and only one page of content var contactsResults = await client.Me.Contacts.ExecuteAsync(); var contacts = contactsResults.CurrentPage .OrderBy(e => e.Surname) .Skip(pageIndex * pageSize) .Take(pageSize); // convert response from Office 365 API > internal class var myContactsList = new List <MyContact>(); foreach (var contact in contacts) { myContactsList.Add(new MyContact { Id = contact.Id, GivenName = contact.GivenName, Surname = contact.Surname, CompanyName = contact.CompanyName, EmailAddress = contact.EmailAddresses[0] != null ? contact.EmailAddresses[0].Address : string.Empty, BusinessPhone = contact.BusinessPhones[0] ?? string.Empty, HomePhone = contact.HomePhones[0] ?? string.Empty }); } // return collection oc contacts return(myContactsList); }
// 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("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId), 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"); ViewBag.ResourceId = dcr.ServiceResourceId; 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.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); }); }
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 static async Task <bool> UpdateMailFolderAsync(string FolderId, string NewFolderName) { try { OutlookServicesClient outlookClient = await GetOutlookClientAsync(); IFolder folder = await outlookClient.Me.Folders.GetById(FolderId).ExecuteAsync(); folder.DisplayName = NewFolderName; await folder.UpdateAsync(); string updatedName = folder.DisplayName; Debug.WriteLine("Updated folder name: " + FolderId + " " + NewFolderName); return(true); } catch (ODataErrorException ex) { // GetById will throw an ODataErrorException when the // item with the specified Id can't be found in the contact store on the server. Debug.WriteLine(ex.Message); return(false); } }
public static async Task <bool> AddFileAttachmentAsync(string MessageId, MemoryStream fileContent) { // Make sure we have a reference to the Outlook Services client OutlookServicesClient outlookClient = await GetOutlookClientAsync(); var attachment = new FileAttachment(); attachment.ContentBytes = fileContent.ToArray(); attachment.Name = "fileAttachment"; attachment.Size = fileContent.ToArray().Length; try { var storedMessage = outlookClient.Me.Messages.GetById(MessageId); await storedMessage.Attachments.AddAttachmentAsync(attachment); await storedMessage.SendAsync(); Debug.WriteLine("Added attachment to message: " + MessageId); return(true); } catch (ODataErrorException ex) { // GetById will throw an ODataErrorException when the // item with the specified Id can't be found in the contact store on the server. Debug.WriteLine(ex.Message); return(false); } }
public static async Task <IContact> getContactByGivenNameAndSurname(OutlookServicesClient contactsClient, Contact myContact) { var contactsResult = await contactsClient.Me.Contacts .Where(c => c.GivenName == myContact.GivenName && c.Surname == myContact.Surname) .ExecuteSingleAsync(); return(contactsResult); }
internal MailFolderProviderSDK(OutlookServicesClient outlookClient, IFolder folder) { _outlookClient = outlookClient; Name = folder.DisplayName; _id = folder.Id; _folderFetcher = new Lazy <IFolderFetcher>(() => _outlookClient.Me.Folders.GetById(_id)); }
public void Init() { var settings = Settings.ExchangePrd; var xauth = new XAuth.Auth(settings.Auth); client = new OutlookServicesClient(settings.Environment.EndpointUri, () => xauth.GetAccessToken(settings.Environment.ResourceId)); }
public static async Task <OutlookServicesClient> GetContactsClient() { if (contactsClient != null) { return(contactsClient); } contactsClient = await GetOutlookClient("Contacts"); return(contactsClient); }
/// <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; }
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); }
/// <summary> /// Checks that an OutlookServicesClient object is available. /// </summary> /// <returns>The OutlookServicesClient object. </returns> public static async Task <OutlookServicesClient> EnsureOutlookClientCreatedAsync(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; }
/// <summary> /// Checks that an OutlookServicesClient object is available. /// </summary> /// <returns>The OutlookServicesClient object. </returns> public static async Task <OutlookServicesClient> EnsureOutlookClientCreatedAsync() { try { AuthenticationContext = new AuthenticationContext(AadAuthority); 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); } }
public async Task <OutlookServicesClient> GetOutlookClient(OutlookToken outlookToken) { var client = new OutlookServicesClient(new Uri(_outlookApiEndpoint), async() => { // Since we have it locally from the Session, just return it here. return(outlookToken.Token); }); client.Context.SendingRequest2 += (sender, e) => InsertXAnchorMailboxHeader(sender, e, outlookToken.Email); return(client); }
public static async Task addEvents(OutlookServicesClient calendarClient, List <Event> newEvents) { foreach (var newEvent in newEvents) { var refEvent = await getEventBySubject(calendarClient, newEvent); if (refEvent == null) { await calendarClient.Me.Events.AddEventAsync(newEvent); } } }