/// <summary>
        /// Fetches email from user's Inbox.
        internal async Task <List <model.MailItem> > GetEmailMessages(int pageNo, int pageSize)
        {
            // Make sure we have a reference to the Outlook Services client
            var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Mail");

            List <model.MailItem> returnResults = new List <model.MailItem>();

            var mailResults = await(from i in outlookServicesClient.Me.Folders.GetById("Inbox").Messages
                                    orderby i.DateTimeReceived descending
                                    select i).Skip((pageNo - 1) * pageSize).Take(pageSize).ExecuteAsync();

            var mailMessages = mailResults.CurrentPage;

            foreach (IMessage serverMailItem in mailMessages)
            {
                model.MailItem modelMailItem = new model.MailItem(serverMailItem);
                if ((!mailResults.MorePagesAvailable))
                {
                    if (modelMailItem.ID == mailMessages.Last <IMessage>().Id)
                    {
                        modelMailItem.IsLastItem = true;
                    }
                }
                if ((modelMailItem.ID == mailMessages.First <IMessage>().Id) && pageNo == 1)
                {
                    modelMailItem.IsFirstItem = true;
                }

                returnResults.Add(modelMailItem);
            }

            return(returnResults);
        }
Пример #2
0
        /// <summary>
        /// Updates an existing event in the user's default calendar
        /// </summary>
        /// <param name="selectedEventId">string. The unique Id of the event to update</param>
        /// <param name="LocationName">string. The name of the event location</param>
        /// <param name="BodyContent">string. The body of the event.</param>
        /// <param name="Attendees">string. semi-colon delimited list of invitee email addresses</param>
        /// <param name="EventName">string. The subject of the event</param>
        /// <param name="start">DateTimeOffset. The start date of the event</param>
        /// <param name="end">DateTimeOffset. The end date of the event</param>
        /// <returns>IEvent. The updated event</returns>
        internal async Task <IEvent> UpdateCalendarEventAsync(

            string selectedEventId,
            string LocationName,
            string BodyContent,
            string Attendees,
            string EventName,
            DateTimeOffset start,
            DateTimeOffset end
            )
        {
            // Make sure we have a reference to the Outlook Services client
            var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Calendar");

            var    thisEventFetcher = outlookServicesClient.Me.Calendar.Events.GetById(selectedEventId);
            IEvent eventToUpdate    = await thisEventFetcher.ExecuteAsync();

            eventToUpdate.Attendees.Clear();
            string[] splitter            = { ";" };
            var      splitAttendeeString = Attendees.Split(splitter, StringSplitOptions.RemoveEmptyEntries);

            Attendee[] attendees = new Attendee[splitAttendeeString.Length];
            for (int i = 0; i < splitAttendeeString.Length; i++)
            {
                Attendee newAttendee = new Attendee();
                newAttendee.EmailAddress = new EmailAddress()
                {
                    Address = splitAttendeeString[i]
                };
                newAttendee.Type = AttendeeType.Required;
                eventToUpdate.Attendees.Add(newAttendee);
            }

            eventToUpdate.Subject = EventName;
            Location location = new Location();

            location.DisplayName   = LocationName;
            eventToUpdate.Location = location;
            eventToUpdate.Start    = (DateTimeOffset?)CalcNewTime(eventToUpdate.Start, start);
            eventToUpdate.End      = (DateTimeOffset?)CalcNewTime(eventToUpdate.End, end);
            ItemBody body = new ItemBody();

            body.ContentType   = BodyType.Text;
            body.Content       = BodyContent;
            eventToUpdate.Body = body;
            try
            {
                // Writes data to API client model.
                await eventToUpdate.UpdateAsync(true);

                // Uupdates the event on the server. This results in a call to the service.
                await outlookServicesClient.Context.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw new Exception("Your calendar event was not updated on the Exchange service");
            }
            return(eventToUpdate);
        }
Пример #3
0
        /// <summary>
        /// Gets the details of an event.
        /// </summary>
        /// <param name="SelectedEventId">string. The unique identifier of an event selected in the UI.</param>
        /// <returns>A calendar event.</returns>
        internal async Task <model.CalendarEvent> GetEventDetailsAsync(string SelectedEventId)
        {
            // Make sure we have a reference to the Outlook Services client
            var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Calendar");

            // This results in a call to the service.
            var thisEventFetcher = outlookServicesClient.Me.Calendar.Events.GetById(SelectedEventId);
            var thisEvent        = await thisEventFetcher.ExecuteAsync();

            model.CalendarEvent modelEvent = new model.CalendarEvent(thisEvent);
            return(modelEvent);
        }
Пример #4
0
        internal async Task <model.ContactItem> GetContactByIDsAsync(string id)
        {
            // Make sure we have a reference to the Outlook Services client
            var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Contacts");

            // This results in a call to the service.
            var thisContactFetcher = outlookServicesClient.Me.Contacts.GetById(id);
            var thisContact        = await thisContactFetcher.ExecuteAsync();

            model.ContactItem modelContact = new model.ContactItem(thisContact);
            return(modelContact);
        }
Пример #5
0
        /// <summary>
        /// Updates an existing contact.
        /// </summary>
        internal async Task <IContact> UpdateContactItemAsync(

            string selectedContactId,
            string fileAs,
            string givenName,
            string surname,
            string jobTitle,
            string email,
            string workPhone,
            string mobilePhone
            )
        {
            try
            {
                // Make sure we have a reference to the Outlook Services client
                var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Contacts");

                var contactToUpdate = await outlookServicesClient.Me.Contacts[selectedContactId].ExecuteAsync();

                contactToUpdate.FileAs    = fileAs;
                contactToUpdate.GivenName = givenName;
                contactToUpdate.Surname   = surname;
                contactToUpdate.JobTitle  = jobTitle;

                contactToUpdate.MobilePhone1 = mobilePhone;

                // Note: Setting EmailAddress1 to a null or empty string will throw an exception that
                // states the email address is invalid and the contact cannot be added.
                // Setting EmailAddress1 to a string that does not resemble an email address will not
                // cause an exception to be thrown, but the value is not stored in EmailAddress1.

                //if (!string.IsNullOrEmpty(email))
                //    contactToUpdate.EmailAddress1 = email;

                // Update the contact in Exchange
                await contactToUpdate.UpdateAsync();

                return(contactToUpdate);

                // A note about Batch Updating
                // You can save multiple updates on the client and save them all at once (batch) by
                // implementing the following pattern:
                // 1. Call UpdateAsync(true) for each contact you want to update. Setting the parameter dontSave to true
                //    means that the updates are registered locally on the client, but won't be posted to the server.
                // 2. Call exchangeClient.Context.SaveChangesAsync() to post all contact updates you have saved locally
                //    using the preceding UpdateAsync(true) call to the server, i.e., the user's Office 365 contacts list.
            }
            catch { return(null); }
        }
Пример #6
0
        internal async Task <List <model.ContactItem> > GetContactsPageAsync(int pageNo, int pageSize)
        {
            try
            {
                // Get Outlook Services client
                var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Contacts");

                List <model.ContactItem> returnResults = new List <model.ContactItem>();

                // Get contacts
                var contactsResults = await(from i in outlookServicesClient.Me.Contacts
                                            orderby i.FileAs
                                            select i).Skip((pageNo - 1) * pageSize).Take(pageSize).ExecuteAsync();

                var contacts = contactsResults.CurrentPage;

                foreach (IContact serverContactItem in contacts)
                {
                    model.ContactItem modelContact = new model.ContactItem(serverContactItem);
                    if ((!contactsResults.MorePagesAvailable))
                    {
                        if (modelContact.ID == contacts.Last <IContact>().Id)
                        {
                            modelContact.IsLastItem = true;
                        }
                    }
                    if ((modelContact.ID == contacts.First <IContact>().Id) && pageNo == 1)
                    {
                        modelContact.IsFirstItem = true;
                    }

                    returnResults.Add(modelContact);
                }


                return(returnResults);
            }
            catch (Exception ex)
            {
                if (ex is AdalException)
                {
                    throw ex;
                }
                else
                {
                    return(null);
                }
            }
        }
Пример #7
0
        /// <summary>
        /// Deletes a contact.
        /// </summary>
        /// <param name="contactId">The contact to delete.</param>
        /// <returns>True if deleted;Otherwise, false.</returns>
        internal async Task <bool> DeleteContactAsync(string contactId)
        {
            try
            {
                // Make sure we have a reference to the Outlook Services client
                var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Contacts");

                var contactToDelete = await outlookServicesClient.Me.Contacts[contactId].ExecuteAsync();

                await contactToDelete.DeleteAsync();

                return(true);
            }
            catch { return(false); }
        }
        internal async Task <model.MailItem> GetMailItemByIDsAsync(string id)
        {
            // Make sure we have a reference to the Outlook Services client
            var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Mail");

            IMessage thisMailItem = null;

            // This results in a call to the service.
            var thisMailFetcher = outlookServicesClient.Me.Folders.GetById("Inbox").Messages.GetById(id);

            thisMailItem = await thisMailFetcher.ExecuteAsync();

            model.MailItem modelMailMessage = new model.MailItem(thisMailItem);
            return(modelMailMessage);
        }
Пример #9
0
        /// <summary>
        /// Adds a new contact.
        /// </summary>
        internal async Task <string> AddContactItemAsync(

            string fileAs,
            string givenName,
            string surname,
            string jobTitle,
            string email,
            string workPhone,
            string mobilePhone
            )
        {
            Contact newContact = new Contact
            {
                FileAs       = fileAs,
                GivenName    = givenName,
                Surname      = surname,
                JobTitle     = jobTitle,
                MobilePhone1 = mobilePhone
            };

            newContact.BusinessPhones.Add(workPhone);


            // Note: Setting EmailAddress1 to a null or empty string will throw an exception that
            // states the email address is invalid and the contact cannot be added.
            // Setting EmailAddress1 to a string that does not resemble an email address will not
            // cause an exception to be thrown, but the value is not stored in EmailAddress1.
            if (!string.IsNullOrEmpty(email))
            {
                newContact.EmailAddresses.Add(new EmailAddress()
                {
                    Address = email
                });
            }

            try
            {
                // Make sure we have a reference to the Outlook Services client
                var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Contacts");

                // This results in a call to the service.
                await outlookServicesClient.Me.Contacts.AddContactAsync(newContact);

                return(newContact.Id);
            }
            catch { return(null); }
        }
        /// <summary>
        /// Removes an event from the user's default calendar.
        /// </summary>
        /// <param name="selectedEventId">string. The unique Id of the event to delete.</param>
        /// <returns></returns>
        internal async Task <IMessage> DeleteMailItemAsync(string selectedEventId)
        {
            IMessage thisMailItem = null;

            try
            {
                // Make sure we have a reference to the Outlook Services client
                var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Mail");

                // Get the event to be removed from the Exchange service. This results in a call to the service.
                thisMailItem = await outlookServicesClient.Me.Folders.GetById("Inbox").Messages.GetById(selectedEventId).ExecuteAsync();

                // Delete the event. This results in a call to the service.
                await thisMailItem.DeleteAsync(false);
            }
            catch (Exception)
            {
                throw new Exception("The message could not be deleted in Outlook Services.");
            }
            return(thisMailItem);
        }
Пример #11
0
        /// <summary>
        /// Gets a collection of events for a specified time span.
        /// </summary>
        /// <param name="hoursBefore">int. The beginning of the TimeSpan that defines which events are returned.</param>
        /// <param name="hoursAfter">int. The end of the TimeSpan that defines which events are returned.</param>
        /// <returns>A collection of all calendar events found for the specified time range.</returns>
        internal async Task <List <model.CalendarEvent> > GetTodaysCalendar(int hoursBefore, int hoursAfter, int pageNo, int pageSize)
        {
            // Make sure we have a reference to the Outlook Services client
            var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Calendar");

            List <model.CalendarEvent> returnResults = new List <model.CalendarEvent>();

            var eventsResults = await(from i in outlookServicesClient.Me.Calendar.Events
                                      where i.Start >= DateTimeOffset.Now.Subtract(new TimeSpan(hoursBefore, 0, 0)) &&
                                      i.Start <= DateTimeOffset.Now.AddHours(hoursAfter)
                                      orderby i.Start
                                      select i).Skip((pageNo - 1) * pageSize).Take(pageSize).ExecuteAsync();



            var events = eventsResults.CurrentPage;

            foreach (IEvent serverEvent in events)
            {
                //model.CalendarEvent modelEvent = await GetEventDetailsAsync(ctx, serverEvent.Id);
                model.CalendarEvent modelEvent = new model.CalendarEvent(serverEvent);
                if ((!eventsResults.MorePagesAvailable))
                {
                    if (modelEvent.ID == events.Last <IEvent>().Id)
                    {
                        modelEvent.IsLastItem = true;
                    }
                }
                if ((modelEvent.ID == events.First <IEvent>().Id) && pageNo == 1)
                {
                    modelEvent.IsFirstItem = true;
                }

                returnResults.Add(modelEvent);
            }


            return(returnResults);
        }
Пример #12
0
        /// <summary>
        /// Removes an event from the user's default calendar.
        /// </summary>
        /// <param name="selectedEventId">string. The unique Id of the event to delete.</param>
        /// <returns></returns>
        internal async Task <IEvent> DeleteCalendarEventAsync(string selectedEventId)
        {
            IEvent thisEvent = null;

            try
            {
                // Make sure we have a reference to the Outlook Services client
                var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Calendar");

                // Get the event to be removed from the Exchange service. This results in a call to the service.
                var thisEventFetcher = outlookServicesClient.Me.Calendar.Events.GetById(selectedEventId);
                thisEvent = await thisEventFetcher.ExecuteAsync();

                // Delete the event. This results in a call to the service.
                await thisEvent.DeleteAsync(false);
            }
            catch (Exception)
            {
                throw new Exception("Your calendar event was not deleted on the Exchange service");
            }
            return(thisEvent);
        }
Пример #13
0
        /// <summary>
        /// Adds a new event to user's default calendar
        /// </summary>
        /// <param name="LocationName">string. The name of the event location</param>
        /// <param name="BodyContent">string. The body of the event.</param>
        /// <param name="Attendees">string. semi-colon delimited list of invitee email addresses</param>
        /// <param name="EventName">string. The subject of the event</param>
        /// <param name="start">DateTimeOffset. The start date of the event</param>
        /// <param name="end">DateTimeOffset. The end date of the event</param>
        /// <returns></returns>
        internal async Task <String> AddCalendarEventAsync(

            string LocationName,
            string BodyContent,
            string Attendees,
            string Subject,
            DateTimeOffset start,
            DateTimeOffset end
            )
        {
            string   newEventId = string.Empty;
            Location location   = new Location();

            location.DisplayName = LocationName;
            ItemBody body = new ItemBody();

            body.Content     = BodyContent;
            body.ContentType = BodyType.Text;
            string[] splitter            = { ";" };
            var      splitAttendeeString = Attendees.Split(splitter, StringSplitOptions.RemoveEmptyEntries);

            Attendee[] attendees = new Attendee[splitAttendeeString.Length];
            for (int i = 0; i < splitAttendeeString.Length; i++)
            {
                attendees[i]              = new Attendee();
                attendees[i].Type         = AttendeeType.Required;
                attendees[i].EmailAddress = new EmailAddress()
                {
                    Address = splitAttendeeString[i]
                };
            }


            Event newEvent = new Event
            {
                Subject   = Subject,
                Location  = location,
                Attendees = attendees,
                Start     = start,
                End       = end,
                Body      = body,
            };


            newEvent.Start = (DateTimeOffset?)CalcNewTime(newEvent.Start, start);
            newEvent.End   = (DateTimeOffset?)CalcNewTime(newEvent.End, end);

            try
            {
                // Make sure we have a reference to the Outlook Services client
                var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Calendar");

                // This results in a call to the service.
                await outlookServicesClient.Me.Events.AddEventAsync(newEvent);

                await((IEventFetcher)newEvent).ExecuteAsync();
                newEventId = newEvent.Id;
            }
            catch (Exception e)
            {
                throw new Exception("We could not create your calendar event: " + e.Message);
            }
            return(newEventId);
        }
        /// <summary>
        /// Compose and send a new email.
        /// </summary>
        /// <param name="subject">string. The subject line of the email.</param>
        /// <param name="bodyContent">string. The body of the email.</param>
        /// <param name="recipients">string. A semi-colon separated list of email addresses.</param>
        /// <returns></returns>
        internal async Task <String> ComposeAndSendMailAsync(string subject,
                                                             string bodyContent,
                                                             string recipients)
        {
            // The identifier of the composed and sent message.
            string newMessageId = string.Empty;

            // Prepare the recipient liost
            var toRecipients = new List <Recipient>();

            string[] splitter = { ";" };
            var      splitRecipientsString = recipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries);

            foreach (string recipient in splitRecipientsString)
            {
                toRecipients.Add(new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = recipient,
                        Name    = recipient,
                    },
                });
            }

            // Prepare the draft message.
            var draft = new Message
            {
                Subject = subject,
                Body    = new ItemBody
                {
                    ContentType = BodyType.Text,
                    Content     = bodyContent
                },
                ToRecipients = toRecipients,
            };

            try
            {
                // Make sure we have a reference to the Outlook Services client.
                var outlookServicesClient = await AuthenticationHelper.EnsureOutlookServicesClientCreatedAsync("Mail");

                // To send a message without saving to Sent Items, specify false for
                // the SavetoSentItems parameter. This method is useful only when you
                // don't need a handle (identifier) on the item saved in
                // the sent items folder.
                // await outlookServicesClient.Me.SendMailAsync(draft, true);


                // Creates the draft message in the drafts folder.
                // This results in a call to the service.
                // Returns full item but unfortunately you dont have access to it.
                await outlookServicesClient.Me.Folders.GetById("Drafts").Messages.AddMessageAsync(draft);

                // Gets the full draft message, including the identifier needed to issue a send mail request.
                // This results in a call to the service.
                IMessage updatedDraft = await outlookServicesClient.Me.Folders.GetById("Drafts").Messages.GetById(draft.Id).ExecuteAsync();

                // Issues a send command so that the draft mail is sent to the recipient list.
                // This results in a call to the service.
                await outlookServicesClient.Me.Folders.GetById("Drafts").Messages.GetById(updatedDraft.Id).SendAsync();

                newMessageId = draft.Id;
            }
            catch (Exception e)
            {
                throw new Exception("We could not send the message: " + e.Message);
            }
            return(newMessageId);
        }