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 static async Task<string> CreateDraftAndSendAsync(
            string Subject,
            string Body,
            string RecipientAddress)
        {

            // Make sure we have a reference to the Outlook Services client
            OutlookServicesClient outlookClient = await GetOutlookClientAsync();

            ItemBody body = new ItemBody
            {
                Content = Body,
                ContentType = BodyType.HTML
            };
            List<Recipient> toRecipients = new List<Recipient>();
            toRecipients.Add(new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = RecipientAddress
                }
            });
            Message draftMessage = new Message
            {
                Subject = Subject,
                Body = body,
                ToRecipients = toRecipients,
                Importance = Importance.High
            };

            // Save the draft message. This ensures that we'll get a message Id to return.
            await outlookClient.Me.Messages.AddMessageAsync(draftMessage);

            //Send the message.

            await outlookClient.Me.Messages[draftMessage.Id].SendAsync();

            Debug.WriteLine("Created and sent draft: " + draftMessage.Id);

            return draftMessage.Id;

        }
        public async Task CreateNewMeeting()
        {
            try
            {
                Microsoft.Graph.Event evt = new Microsoft.Graph.Event();

                Location location = new Location();
                location.DisplayName = tbLocation.Text;

                ItemBody body = new ItemBody();
                body.Content = tbBody.Text;
                body.ContentType = BodyType.Html;

                List<Attendee> attendees = new List<Attendee>();
                Attendee attendee = new Attendee();
                EmailAddress email = new EmailAddress();
                email.Address = tbToRecipients.Text;
                attendee.EmailAddress = email;
                attendee.Type = AttendeeType.Required;
                attendees.Add(attendee);

                evt.Subject = tbSubject.Text;
                evt.Body = body;
                evt.Location = location;
                evt.Attendees = attendees;

                DateTimeTimeZone dtStart = new DateTimeTimeZone();
                dtStart.TimeZone = TimeZoneInfo.Local.Id;
                DateTime dts = dtpStartDate.Value.Date + dtpStartTime.Value.TimeOfDay;
                dtStart.DateTime = dts.ToString();
                
                DateTimeTimeZone dtEnd = new DateTimeTimeZone();
                dtEnd.TimeZone = TimeZoneInfo.Local.Id;
                DateTime dte = dtpEndDate.Value.Date + dtpEndTime.Value.TimeOfDay;
                dtEnd.DateTime = dte.ToString();

                evt.Start = dtStart;
                evt.End = dtEnd;
                
                // log the request info
                sdklogger.Log(graphClient.Me.Events.Request().GetHttpRequestMessage().Headers.ToString());
                sdklogger.Log(graphClient.Me.Events.Request().GetHttpRequestMessage().RequestUri.ToString());

                // send the new message
                var createdEvent = await graphClient.Me.Events.Request().AddAsync(evt);

                // log the send and associated id
                sdklogger.Log("Meeting Sent : Id = " + createdEvent.Id);
            }
            catch (Exception ex)
            {
                sdklogger.Log("NewMeetingSend Failed: " + ex.Message);
                sdklogger.Log(ex.Message);
            }
            finally
            {
                // close the form
                Close();
            }
        }
Beispiel #4
0
        public static bool SendMail(string Subject, string Message, string[] Recipient, GraphCfg config)
        {
            var result = false;

            var recipients = new List <Recipient>();

            foreach (var r in Recipient)
            {
                AddReciepient(recipients, r);
            }

            var body = new ItemBody
            {
                ContentType = BodyType.Html,
                Content     = Message,
            };

            Message message = new Message
            {
                Subject      = Subject,
                Body         = body,
                ToRecipients = recipients,
            };

            config.returnUrl = config.frontendUrl;
            sendMail(config, message, config.mailSender);

            result = true;
            return(result);
        }
Beispiel #5
0
 public Item(ItemBody body, int index)
 {
     this.body  = body;
     body.index = index;
     iType      = body.type;
     _iLoc      = ILOC.VOID;
 }
Beispiel #6
0
        /// <summary>
        /// Sends the mail.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public async t.Task SendMailAsync <T>(EmailRequest <T> request) where T : class
        {
            GraphServiceClient graphClient = await ConnectClient().ConfigureAwait(false);

            Message message = new()
            {
                Subject = request.Subject,
                Body    = new ItemBody {
                    ContentType = BodyType.Html, Content = request.Body
                },
                ToRecipients = request.To.Select(x => new Recipient {
                    EmailAddress = new EmailAddress {
                        Address = x
                    }
                }),
                CcRecipients = request.Cc.Select(x => new Recipient {
                    EmailAddress = new EmailAddress {
                        Address = x
                    }
                }),
                BccRecipients = request.Bcc.Select(x => new Recipient {
                    EmailAddress = new EmailAddress {
                        Address = x
                    }
                }),
                Attachments = request.AddAttachments()
            };

            await graphClient.Users[Credentials.From]
            .SendMail(message, false)
            .Request()
            .PostAsync()
            .ConfigureAwait(false);
        }
        /// <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>
        /// <param name="startTime">TimeSpan. The start hour:Min:Sec of the event</param>
        /// <param name="endTime">TimeSpan. The end hour:Min:Sec of the event</param>
        /// <returns></returns>
        internal async Task <string> AddCalendarEventAsync(
            string LocationName,
            string BodyContent,
            string Attendees,
            string EventName,
            DateTimeOffset start,
            DateTimeOffset end,
            TimeSpan startTime,
            TimeSpan endTime)
        {
            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].Address = splitAttendeeString[i];
            }

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

            //Add new times to start and end dates.
            newEvent.Start = (DateTimeOffset?)CalcNewTime(newEvent.Start, start, startTime);
            newEvent.End   = (DateTimeOffset?)CalcNewTime(newEvent.End, end, endTime);

            try
            {
                // Make sure we have a reference to the calendar client
                var calendarClient = await AuthenticationHelper.EnsureCalendarClientCreatedAsync();

                // This results in a call to the service.
                await calendarClient.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);
        }
        public override void CopyFrom(IProperty srcProperty)
        {
            IContent16Property content16Property = srcProperty as IContent16Property;

            if (content16Property != null)
            {
                ItemBody itemBody = new ItemBody();
                switch (content16Property.GetNativeType())
                {
                case Microsoft.Exchange.AirSync.SchemaConverter.Common.BodyType.None:
                    base.Item.Body = null;
                    return;

                case Microsoft.Exchange.AirSync.SchemaConverter.Common.BodyType.PlainText:
                    itemBody.ContentType = Microsoft.Exchange.Entities.DataModel.Items.BodyType.Text;
                    break;

                case Microsoft.Exchange.AirSync.SchemaConverter.Common.BodyType.Html:
                    itemBody.ContentType = Microsoft.Exchange.Entities.DataModel.Items.BodyType.Html;
                    break;

                default:
                    throw new NotImplementedException(string.Format("Unable to convert content type {0}", content16Property.GetNativeType()));
                }
                itemBody.Content = content16Property.BodyString;
                base.Item.Body   = itemBody;
            }
        }
Beispiel #9
0
        public static ItemBody Parse(HtmlNode table)
        {
            var itemBody = new ItemBody();

            foreach (var p in table.SelectNodes(".//p"))
            {
                var answer = p.SelectNodes(".//span")?
                             .FirstOrDefault(
                    x => StringUtilities.MatchesCharacterInRange(x.InnerText, 'A', 'D'))?
                             .InnerText.Trim();

                if (!string.IsNullOrEmpty(answer))
                {
                    Logger.Trace($"Parsing answer for {answer}");
                    itemBody.AnswerChoices.Add(answer,
                                               HtmlNodeUtilities.BodyElementFromNode(ExtractionSettings.Input, p));
                    if (!itemBody.AnswerChoices[answer].IsResource())
                    {
                        var document = new HtmlDocument();
                        document.LoadHtml(itemBody.AnswerChoices[answer].Text);
                        var span = document.DocumentNode.SelectNodes("//span").Last();
                        itemBody.AnswerChoices[answer].Text = span.OuterHtml.Trim();
                    }
                }
                else
                {
                    Logger.Trace("Parsing item body");
                    itemBody.Elements.Add(HtmlNodeUtilities.BodyElementFromNode(ExtractionSettings.Input, p));
                }
            }
            return(itemBody);
        }
Beispiel #10
0
        public async Task CreateNewMeeting()
        {
            try
            {
                Microsoft.Graph.Event evt = new Microsoft.Graph.Event();

                Location location = new Location();
                location.DisplayName = tbLocation.Text;

                ItemBody body = new ItemBody();
                body.Content     = tbBody.Text;
                body.ContentType = BodyType.Html;

                List <Attendee> attendees = new List <Attendee>();
                Attendee        attendee  = new Attendee();
                EmailAddress    email     = new EmailAddress();
                email.Address         = tbToRecipients.Text;
                attendee.EmailAddress = email;
                attendee.Type         = AttendeeType.Required;
                attendees.Add(attendee);

                evt.Subject   = tbSubject.Text;
                evt.Body      = body;
                evt.Location  = location;
                evt.Attendees = attendees;

                DateTimeTimeZone dtStart = new DateTimeTimeZone();
                dtStart.TimeZone = TimeZoneInfo.Local.Id;
                DateTime dts = dtpStartDate.Value.Date + dtpStartTime.Value.TimeOfDay;
                dtStart.DateTime = dts.ToString();

                DateTimeTimeZone dtEnd = new DateTimeTimeZone();
                dtEnd.TimeZone = TimeZoneInfo.Local.Id;
                DateTime dte = dtpEndDate.Value.Date + dtpEndTime.Value.TimeOfDay;
                dtEnd.DateTime = dte.ToString();

                evt.Start = dtStart;
                evt.End   = dtEnd;

                // log the request info
                sdklogger.Log(graphClient.Me.Events.Request().GetHttpRequestMessage().Headers.ToString());
                sdklogger.Log(graphClient.Me.Events.Request().GetHttpRequestMessage().RequestUri.ToString());

                // send the new message
                var createdEvent = await graphClient.Me.Events.Request().AddAsync(evt);

                // log the send and associated id
                sdklogger.Log("Meeting Sent : Id = " + createdEvent.Id);
            }
            catch (Exception ex)
            {
                sdklogger.Log("NewMeetingSend Failed: " + ex.Message);
                sdklogger.Log(ex.Message);
            }
            finally
            {
                // close the form
                Close();
            }
        }
Beispiel #11
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);
        }
Beispiel #12
0
        private ItemBody CreateItemBody(string content, bool isHtml = false)
        {
            ItemBody body = new ItemBody();

            body.ContentType = isHtml ? BodyType.Html : BodyType.Text;
            body.Content     = content;
            return(body);
        }
Beispiel #13
0
        public async Task <bool> UpdateEventAsync(string eventId, string eventAttendees, string eventDescription, string eventLocation, string eventSubject, DateTime startDateTime, DateTime endDateTime, bool isAllDayMeeting)
        {
            bool eventUpdated = false;

            var eventToUpdate = new Event();

            // Prepare the List of attendees
            // Prepare the recipient list
            string[]        splitter = { ";" };
            var             splitRecipientsString = eventAttendees.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
            List <Attendee> attendeesList         = new List <Attendee>();

            foreach (string attendee in splitRecipientsString)
            {
                attendeesList.Add(new Attendee {
                    EmailAddress = new EmailAddress {
                        Address = attendee.Trim()
                    }, Type = AttendeeType.Required
                });
            }

            // Event body
            var eventBody = new ItemBody();

            eventBody.Content     = eventDescription;
            eventBody.ContentType = BodyType.Text;

            var eventStartTime = new DateTimeTimeZone();
            var eventEndTime   = new DateTimeTimeZone();

            // Event start and end time
            eventStartTime.DateTime = startDateTime.ToString("o");
            eventStartTime.TimeZone = "UTC";
            eventEndTime.TimeZone   = "UTC";
            eventEndTime.DateTime   = endDateTime.ToString("o");

            // Create an event to add to the events collection
            var location = new Location();

            location.DisplayName = eventLocation;

            eventToUpdate.Subject   = eventSubject;
            eventToUpdate.Location  = location;
            eventToUpdate.Attendees = attendeesList;
            eventToUpdate.Body      = eventBody;
            eventToUpdate.Start     = eventStartTime;
            eventToUpdate.End       = eventEndTime;

            var updatedEvent = await GraphClient.Instance.Beta.Me.Events[eventId].Request()
                               .UpdateAsync(eventToUpdate);

            if (updatedEvent != null)
            {
                eventUpdated = true;
            }

            return(eventUpdated);
        }
        /// <summary>
        /// Updates an existing event in the user's default calendar
        /// </summary>
        /// <param name="eventId">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>
        /// <param name="startTime">TimeSpan. The start hour:Min:Sec of the event</param>
        /// <param name="endTime">TimeSpan. The end hour:Min:Sec of the event</param>
        /// <returns>IEvent. The updated event</returns>
        public static async Task <IEvent> UpdateCalendarEventAsync(string eventId,
                                                                   string LocationName,
                                                                   string BodyContent,
                                                                   string Attendees,
                                                                   string EventName,
                                                                   DateTimeOffset start,
                                                                   DateTimeOffset end,
                                                                   TimeSpan startTime,
                                                                   TimeSpan endTime)
        {
            // Make sure we have a reference to the Exchange client
            var client = await GetOutlookClientAsync();

            var eventToUpdate = await client.Me.Calendar.Events.GetById(eventId).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, startTime);
            eventToUpdate.End      = (DateTimeOffset?)CalcNewTime(eventToUpdate.End, end, endTime);
            ItemBody body = new ItemBody();

            body.ContentType   = BodyType.Text;
            body.Content       = BodyContent;
            eventToUpdate.Body = body;

            // Update the calendar event in Exchange
            await eventToUpdate.UpdateAsync();

            Debug.WriteLine("Updated event: " + eventToUpdate.Id);
            return(eventToUpdate);

            // 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 event 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 event updates you have saved locally
            //    using the preceding UpdateAsync(true) call to the server, i.e., the user's Office 365 calendar.
        }
Beispiel #15
0
    public TutorialStateCarrot(StateMachine stateMachine, ItemBody carrot) : base(stateMachine)
    {
        _tutoCarrot = carrot;

        _game = GameObject.FindObjectOfType <Game>();
        _game.tutoArrow.SetActive(true);
        _game.tutoArrow.transform.position = carrot.transform.position + new Vector3(0, 5, 0);
        _game.messageCanvas.GetComponentInChildren <Text>().text = "Ramasser la carotte";
    }
Beispiel #16
0
        private static Message CreateMessage(IFluentEmail email)
        {
            var messageBody = new ItemBody
            {
                Content     = email.Data.Body,
                ContentType = email.Data.IsHtml ? BodyType.Html : BodyType.Text,
            };

            var message = new Message();

            message.Subject       = email.Data.Subject;
            message.Body          = messageBody;
            message.From          = ConvertToRecipient(email.Data.FromAddress);
            message.ReplyTo       = CreateRecipientList(email.Data.ReplyToAddresses);
            message.ToRecipients  = CreateRecipientList(email.Data.ToAddresses);
            message.CcRecipients  = CreateRecipientList(email.Data.CcAddresses);
            message.BccRecipients = CreateRecipientList(email.Data.BccAddresses);

            if (email.Data.Attachments != null && email.Data.Attachments.Count > 0)
            {
                message.Attachments = new MessageAttachmentsCollectionPage();

                email.Data.Attachments.ForEach(
                    a =>
                {
                    var attachment = new FileAttachment
                    {
                        Name         = a.Filename,
                        ContentType  = a.ContentType,
                        ContentBytes = GetAttachmentBytes(a.Data),
                    };

                    message.Attachments.Add(attachment);
                });
            }

            switch (email.Data.Priority)
            {
            case Priority.High:
                message.Importance = Importance.High;
                break;

            case Priority.Normal:
                message.Importance = Importance.Normal;
                break;

            case Priority.Low:
                message.Importance = Importance.Low;
                break;

            default:
                message.Importance = Importance.Normal;
                break;
            }

            return(message);
        }
Beispiel #17
0
        public static async Task Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            log.LogInformation(eventGridEvent.Data.ToString());

            JObject         dataObject = eventGridEvent.Data as JObject;
            ActivityDetails details    = dataObject.ToObject <ActivityDetails>();

            string clientId     = Environment.GetEnvironmentVariable("ClientId");
            string clientSecret = Environment.GetEnvironmentVariable("ClientSecret");
            string tenantId     = Environment.GetEnvironmentVariable("TenantId");

            string authority       = $"https://login.microsoftonline.com/{tenantId}/v2.0";
            string userId          = details.userId;
            string taskId          = details.taskId;
            string notificationUrl = details.notificationUrl;

            var cca = ConfidentialClientApplicationBuilder.Create(clientId)
                      .WithClientSecret(clientSecret)
                      .WithAuthority(authority)
                      .Build();

            List <string> scopes = new List <string>();

            scopes.Add("https://graph.microsoft.com/.default");

            MSALAuthenticationProvider authenticationProvider = new MSALAuthenticationProvider(cca, scopes.ToArray());
            GraphServiceClient         graphServiceClient     = new GraphServiceClient(authenticationProvider);

            var topic = new TeamworkActivityTopic
            {
                Source = TeamworkActivityTopicSource.Text,
                Value  = "New Task Created",
                WebUrl = notificationUrl
            };

            var activityType = "taskCreated";

            var previewText = new ItemBody
            {
                Content = "A new task has been created for you"
            };

            var templateParameters = new List <KeyValuePair>()
            {
                new KeyValuePair
                {
                    Name  = "taskId",
                    Value = taskId
                }
            };

            await graphServiceClient.Users[userId].Teamwork
            .SendActivityNotification(topic, activityType, null, previewText, templateParameters)
            .Request()
            .PostAsync();
        }
Beispiel #18
0
        public Item(ItemPreset itemPreset, int index, bool startVisible, Vector3 position)
        {
            ItemBody b = Instantiate(itemPreset.bodyPrefab, position, Quaternion.Euler(itemPreset.baseRotation)).GetComponent <ItemBody>();

            body       = b;
            body.index = index;
            body.SetVisible(startVisible);
            iType = itemPreset.type;
            _iLoc = ILOC.VOID;
        }
        private RestItemData CreateAndAddResponseContent(IResponseModifier modifier, Response response)
        {
            var itemData = new RestItemData();

            _fixture.AddManyTo(itemData, 10);
            var resourceBody = new ItemBody(itemData);

            modifier.AddResource(response, resourceBody);
            return(itemData);
        }
        /// <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>
        /// <param name="startTime">TimeSpan. The start hour:Min:Sec of the event</param>
        /// <param name="endTime">TimeSpan. The end hour:Min:Sec of the event</param>
        /// <returns>The Id of the event that was created; Otherwise, null.</returns>
        public static async Task <string> AddCalendarEventWithArgsAsync(
            string LocationName,
            string BodyContent,
            string Attendees,
            string EventName,
            DateTimeOffset start,
            DateTimeOffset end,
            TimeSpan startTime,
            TimeSpan endTime)
        {
            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   = EventName,
                Location  = location,
                Attendees = attendees,
                Start     = start,
                End       = end,
                Body      = body,
            };

            //Add new times to start and end dates.
            newEvent.Start = (DateTimeOffset?)CalcNewTime(newEvent.Start, start, startTime);
            newEvent.End   = (DateTimeOffset?)CalcNewTime(newEvent.End, end, endTime);

            // Make sure we have a reference to the calendar client
            var exchangeClient = await GetOutlookClientAsync();

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

            Debug.WriteLine("Added event: " + newEvent.Id);
            return(newEvent.Id);
        }
        public async Task <dynamic> GetUserInformation()
        {
            var ccemailAddress = new EmailAddress
            {
                Address = "*****@*****.**",
            };

            var ccRecipients = new Recipient
            {
                EmailAddress = ccemailAddress,
            };

            var ccRecipientsList = new List <Recipient>
            {
                ccRecipients
            };

            var emailAddress = new EmailAddress
            {
                Address = "*****@*****.**",
            };

            var toRecipients = new Recipient
            {
                EmailAddress = emailAddress,
            };

            var toRecipientsList = new List <Recipient>
            {
                toRecipients
            };

            var body = new ItemBody
            {
                ContentType = BodyType.Text,
                Content     = "The new cafeteria is open.",
            };

            var message = new Message
            {
                Subject      = "Meet for lunch?",
                Body         = body,
                ToRecipients = toRecipientsList,
                CcRecipients = ccRecipientsList,
            };

            Boolean saveToSentItems = true;

            await _client.Me
            .SendMail(message, saveToSentItems)
            .Request()
            .PostAsync();

            return(null);
        }
        /// <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>
        /// <param name="startTime">TimeSpan. The start hour:Min:Sec of the event</param>
        /// <param name="endTime">TimeSpan. The end hour:Min:Sec of the event</param>
        /// <returns></returns>
        internal async Task<string> AddCalendarEventAsync(
            string LocationName,
            string BodyContent,
            string Attendees,
            string EventName,
            DateTimeOffset start,
            DateTimeOffset end,
            TimeSpan startTime,
            TimeSpan endTime)
        {
            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], Name = splitAttendeeString[i] };
            }

            Event newEvent = new Event
            {
                Subject = EventName,
                Location = location,
                Attendees = attendees,
                Start = start,
                End = end,
                Body = body,
            };
            //Add new times to start and end dates.
            newEvent.Start = (DateTimeOffset?)CalcNewTime(newEvent.Start, start, startTime);
            newEvent.End = (DateTimeOffset?)CalcNewTime(newEvent.End, end, endTime);

            try
            {
                // Make sure we have a reference to the calendar client
                var exchangeClient = await AuthenticationHelper.EnsureOutlookClientCreatedAsync();

                // This results in a call to the service.
                await exchangeClient.Me.Events.AddEventAsync(newEvent);
                newEventId = newEvent.Id;
            }
            catch (Exception e)
            {
                throw new Exception("We could not create your calendar event: " + e.Message);
            }
            return newEventId;
        }
Beispiel #23
0
        // Token: 0x06001225 RID: 4645 RVA: 0x00062A6C File Offset: 0x00060C6C
        public static ItemBody ParseBody(XmlNode bodyNode)
        {
            if (!bodyNode.HasChildNodes)
            {
                throw new RequestParsingException("NoChildNodes");
            }
            XmlNode xmlNode = bodyNode["Type", "AirSyncBase:"];

            if (xmlNode == null || string.IsNullOrEmpty(xmlNode.InnerText))
            {
                throw new RequestParsingException("NoBodyType");
            }
            int num;

            if (!int.TryParse(xmlNode.InnerText, out num))
            {
                throw new RequestParsingException("InvalidBodyType:" + xmlNode.InnerText);
            }
            ItemBody itemBody;

            switch (num)
            {
            case 0:
                itemBody = null;
                break;

            case 1:
                itemBody = new ItemBody
                {
                    ContentType = BodyType.Text
                };
                break;

            case 2:
                itemBody = new ItemBody
                {
                    ContentType = BodyType.Html
                };
                break;

            default:
                throw new RequestParsingException("UnsupportedBodyType:" + num);
            }
            if (itemBody != null)
            {
                XmlNode xmlNode2 = bodyNode["Data", "AirSyncBase:"];
                if (xmlNode2 == null || string.IsNullOrEmpty(xmlNode2.InnerText))
                {
                    throw new RequestParsingException("NoBodyText");
                }
                itemBody.Content = xmlNode2.InnerText;
            }
            return(itemBody);
        }
Beispiel #24
0
 public void CreateItem(ItemBody b)
 {
     if (itemsList == null)
     {
         itemsList = new List <Item>();
         if (!destroyOnLoad)
         {
             DontDestroyOnLoad(items);
         }
     }
     itemsList.Add(new Item(b, itemsList.Count));
 }
Beispiel #25
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            // 读取当前群聊中的用户列表
            var members = await TeamsInfo.GetMembersAsync(turnContext);

            // 准备用来访问Microsoft Graph的本地代理
            GraphServiceClient graphClient = new GraphServiceClient(new SimpleAuth(_configuration));

            // 为每个用户发送一个通知,这里解析得到他们的AadObjectId,用来发送
            members.Select(_ => _.AadObjectId).AsParallel().ForAll(async(_) =>
            {
                // 以下代码,其实你可以在官网找到,并且简单地做些修改即可
                // https://docs.microsoft.com/zh-cn/graph/api/chat-sendactivitynotification?view=graph-rest-1.0&tabs=http#example-1-notify-a-user-about-a-task-created-in-a-chat
                var topic = new TeamworkActivityTopic
                {
                    Source = TeamworkActivityTopicSource.EntityUrl,
                    Value  = $"https://graph.microsoft.com/beta/me/chats/{turnContext.Activity.Conversation.Id}/messages/{turnContext.Activity.Id}"
                };
                // 这个是通知的自定义模板(在manifest.json文件中要定义)
                var activityType = "metionall";
                // 预览文字
                var previewText = new ItemBody
                {
                    Content = "有人在群聊中提到你了,请点击查看"
                };
                // 收件人的id
                var recipient = new AadUserNotificationRecipient
                {
                    UserId = _
                };
                // 替换掉模板中的值
                var templateParameters = new List <Microsoft.Graph.KeyValuePair>()
                {
                    new Microsoft.Graph.KeyValuePair
                    {
                        Name  = "from",
                        Value = turnContext.Activity.From.Name
                    },
                    new Microsoft.Graph.KeyValuePair
                    {
                        Name  = "message",
                        Value = turnContext.Activity.RemoveMentionText(turnContext.Activity.Recipient.Id)
                    }
                };
                // 调用接口发送通知
                await graphClient.Chats[turnContext.Activity.Conversation.Id]
                .SendActivityNotification(topic, activityType, null, previewText, templateParameters, recipient)
                .Request()
                .PostAsync();
            });
        }
        /// <summary>
        /// This method calls GraphService.Me.Events.AddEventAsync() to create an event
        /// on singed-in user's default calendar.  Due to a bug after the call does not
        /// the execution flow does not return back to the next line after the call.
        /// </summary>
        /// <param name="subject"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="attendeeEmails"></param>
        /// <param name="description"></param>
        /// <param name="locationDisplayName"></param>
        /// <returns></returns>
        public static async Task AddEventAsync(
            string subject,
            DateTimeOffset startTime,
            DateTimeOffset endTime,
            IEnumerable <string> attendeeEmails,
            string description,
            string locationDisplayName)
        {
            var client = await GetGraphClientAsync(PermissionScope);

            if (client == null)
            {
                throw new Exception("Error getting Microsoft Graph service client");
            }

            var @event = new Event();

            @event.Subject  = subject;
            @event.Start    = startTime;
            @event.End      = endTime;
            @event.Location = new Location()
            {
                DisplayName = locationDisplayName
            };
            var listOfAttendees = new List <Attendee>();

            foreach (var email in attendeeEmails)
            {
                var name = await GetUserDisplayNameAsync(email);

                var attendee = new Attendee()
                {
                    EmailAddress = new EmailAddress()
                    {
                        Address = email, Name = name
                    }
                };
                listOfAttendees.Add(attendee);
            }
            @event.Attendees = listOfAttendees;
            var itemBody = new ItemBody();

            itemBody.ContentType = BodyType.Text;
            itemBody.Content     = description;
            @event.Body          = itemBody;
            // The following call never returns.  A bug was logged against O365 client library,
            // but it later was resolved as Not Repro.
            await client.Me.Events.AddEventAsync(@event);

            // So have to workaround using Rest Api below.
        }
Beispiel #27
0
        internal static void SetOnStorageItem(this ItemBody entityBody, IItem storageItem, bool update)
        {
            string value = entityBody.Content ?? string.Empty;
            HtmlUpdateBodyCallback htmlUpdateBodyCallback;

            using (TextWriter textWriter = BodyConverter.CreateTextWriter(storageItem, entityBody.ContentType, update, out htmlUpdateBodyCallback))
            {
                textWriter.Write(value);
            }
            if (htmlUpdateBodyCallback != null)
            {
                htmlUpdateBodyCallback.SaveChanges();
            }
        }
Beispiel #28
0
        public async Task ItemEndpoint()
        {
            IRestEndpoint endpoint = _navigator.GetEndpointFromPath("artists/123");

            ItemBody itemBody = (ItemBody)(await endpoint.GetAsync(null));

            RestItemData itemData = itemBody.Item;

            Assert.Equal("ID", itemData.Keys.First());

            int firstId = (int)itemData["ID"];

            Assert.True(firstId > 0);
        }
Beispiel #29
0
        internal static ItemBody GetEntityBody(this IItem input, char[] buffer)
        {
            Body     body;
            BodyType bodyType;

            try
            {
                body = IrmUtils.GetBody(input);
                BodyFormat format = body.Format;
                bodyType = format.ToEntityType();
            }
            catch (PropertyErrorException ex)
            {
                ExTraceGlobals.CommonTracer.TraceDebug <string, string>(0L, "[BodyConverter::GetEntityBody] Encountered exception - Class: {0}; Message: {1}", ex.GetType().FullName, ex.Message);
                throw new CorruptDataException(Strings.ErrorItemCorrupt, ex);
            }
            catch (StoragePermanentException ex2)
            {
                if (ex2.InnerException is MapiExceptionNoSupport)
                {
                    throw new CorruptDataException(Strings.ErrorItemCorrupt, ex2);
                }
                ExTraceGlobals.CommonTracer.TraceDebug(0L, "[BodyConverter::GetEntityBody] Encountered exception - Class: {0}, Message: {1} Inner exception was not MapiExceptionNoSupport but rather Class: {2}; Message: {3}", new object[]
                {
                    ex2.GetType().FullName,
                    ex2.Message,
                    (ex2.InnerException == null) ? "<NULL>" : ex2.InnerException.GetType().FullName,
                    (ex2.InnerException == null) ? "<NULL>" : ex2.InnerException.Message
                });
                throw;
            }
            ItemBody itemBody = new ItemBody
            {
                ContentType = bodyType
            };

            using (TextWriter textWriter = new StringWriter())
            {
                if (bodyType == BodyType.Html)
                {
                    BodyConverter.WriteHtmlContent(textWriter, input, buffer);
                }
                else
                {
                    BodyConverter.WriteTextContent(textWriter, body, buffer);
                }
                itemBody.Content = textWriter.ToString();
            }
            return(itemBody);
        }
Beispiel #30
0
        private Message CreateMessage(string from, string to, ItemBody content)
        {
            Message msg = new Message();

            msg.Body         = content;
            msg.ToRecipients = new Recipient[] { new Recipient()
                                                 {
                                                     EmailAddress = new EmailAddress()
                                                     {
                                                         Address = to
                                                     }
                                                 } };
            return(msg);
        }
        public async Task SendMailAsync(string sendByUserEmail, string[] toRecipientMails, string[] bccRecipientMails, string replyToMail, string subject, string bodyString)
        {
            var toRecipients = toRecipientMails.Select(email => new Recipient()
            {
                EmailAddress = new EmailAddress()
                {
                    Address = email.Split(';')[0],
                    Name    = email.Split(';')[1]
                }
            });

            var bccRecipients = bccRecipientMails.Select(email => new Recipient()
            {
                EmailAddress = new EmailAddress()
                {
                    Address = email.Split(';')[0],
                    Name    = email.Split(';')[1]
                }
            });

            var replyTo = new Recipient()
            {
                EmailAddress = new EmailAddress()
                {
                    Address = replyToMail.Split(';')[0],
                    Name    = replyToMail.Split(';')[1]
                }
            };

            var body = new ItemBody()
            {
                Content     = $@"{bodyString}",
                ContentType = BodyType.Html
            };


            var mail = new Message()
            {
                Subject       = subject,
                ToRecipients  = toRecipients,
                BccRecipients = bccRecipients,
                Body          = body,
                From          = replyTo,
                ReplyTo       = new[] { replyTo }
            };

            await _graphService.GraphClient.Users[sendByUserEmail].SendMail(mail, true)
            .Request().PostAsync();
        }
        public static async Task <bool> SendReplyAllMessageAsync(string body, string subject, bool?isOrganizer)
        {
            bool emailSent = false;

            try
            {
                GraphServiceClient graphClient = AuthenticationHelper.GetAuthenticatedClient();
                // Get meeting message from user's Sent Items folder or Inbox
                IMailFolderMessagesCollectionPage eventMessages;

                if (isOrganizer.GetValueOrDefault())
                {
                    eventMessages = await graphClient.Me.MailFolders.SentItems.Messages.Request().Filter("Subject eq '" + subject + "'").GetAsync();
                }
                else
                {
                    eventMessages = await graphClient.Me.MailFolders.Inbox.Messages.Request().Filter("Subject eq '" + subject + "'").GetAsync();
                }

                if (eventMessages.Count > 0)
                {
                    Message messageToReplyAll = eventMessages[0];

                    // Reply all to message
                    Message replyMessage = await graphClient.Me.Messages[messageToReplyAll.Id].CreateReplyAll().Request().PostAsync();

                    if (!String.IsNullOrEmpty(body))
                    {
                        ItemBody replyMessageBody = new ItemBody {
                            ContentType = BodyType.Text, Content = body
                        };
                        replyMessage.Body = replyMessageBody;
                        await graphClient.Me.Messages[replyMessage.Id].Request().UpdateAsync(replyMessage);
                    }
                    await graphClient.Me.Messages[replyMessage.Id].Send().Request().PostAsync();
                    emailSent = true;
                }
            }

            catch (ServiceException e)
            {
                Debug.WriteLine("Failed to send message" + e.Error.Message);
                emailSent = false;
            }

            return(emailSent);
        }
        /// <summary>
        /// Send a message
        /// <para> Permission Scope: (Send mail as user)</para>
        /// </summary>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
        /// <param name="subject">The subject of the message.</param>
        /// <param name="content">The text or HTML content.</param>
        /// <param name="contentType">The content type: Text = 0, HTML = 1</param>
        /// <param name="to">The To recipients for the message.</param>
        /// <param name="cc">The Cc recipients for the message.</param>
        /// <param name="importance">The importance of the message: Low = 0, Normal = 1, High = 2.</param>
        /// <returns><see cref="Task"/> representing the asynchronous operation.</returns>
        public Task SendEmailAsync(CancellationToken cancellationToken, string subject, string content, BodyType contentType, string[] to, string[] cc = null, Importance importance = Importance.Normal)
        {
            if (_currentUser == null)
            {
                throw new ServiceException(new Error {
                    Message = "No user connected", Code = "NoUserConnected", ThrowSite = "UWP Community Toolkit"
                });
            }

            List <Recipient> ccRecipients = null;

            if (to == null)
            {
                throw new ArgumentNullException(nameof(to));
            }

            ItemBody body = new ItemBody
            {
                Content     = content,
                ContentType = contentType
            };
            List <Recipient> toRecipients = new List <Recipient>();

            to.CopyTo(toRecipients);

            if (cc != null)
            {
                ccRecipients = new List <Recipient>();
                cc.CopyTo(ccRecipients);
            }

            Message coreMessage = new Message
            {
                Subject       = subject,
                Body          = body,
                Importance    = importance,
                ToRecipients  = toRecipients,
                CcRecipients  = ccRecipients,
                BccRecipients = null,
                IsDeliveryReceiptRequested = false,
            };

            var userBuilder = _graphProvider.Users[_currentUser.Id];

            return(userBuilder.SendMail(coreMessage, false).Request().PostAsync(cancellationToken));
        }
Beispiel #34
0
        public async Task <ActionResult> SendMessage()
        {
            try
            {
                // Get an access token.
                string accessToken = await SampleAuthProvider.Instance.GetUserAccessTokenAsync();

                UserInfo addresse = await graphService.getMe(accessToken);

                Recipient recipient = new Recipient
                {
                    EmailAddress = addresse
                };
                List <Recipient> recipients = new List <Recipient>();
                recipients.Add(recipient);
                ItemBody body = new ItemBody
                {
                    Content = "Is a test"
                };

                Message message = new Message
                {
                    ToRecipients = recipients,
                    Body         = body,
                    Subject      = "Test API"
                };
                MessageRequest messageRequest = new MessageRequest
                {
                    Message         = message,
                    SaveToSentItems = true
                };
                var items = await graphService.SendEmail(accessToken, messageRequest);

                ViewBag.API    = "Postmessage/";
                ViewBag.Values = items.ToString();
                return(View("Test"));
            }
            catch (Exception e)
            {
                if (e.Message == Resource.Error_AuthChallengeNeeded)
                {
                    return(new EmptyResult());
                }
                return(RedirectToAction("Index", "Error", new { message = Resource.Error_Message + Request.RawUrl + ": " + e.Message }));
            }
        }
        public IMailItem NewMailItem()
        {
            ItemBody body = new ItemBody
            {
                Content = "New Body",
                ContentType = BodyType.HTML
            };

            Message message = new Message
            {
                Subject = "New Subject",
                Body = body,
                ToRecipients = new List<Recipient>(),
                Importance = Importance.High
            };

            // Save the draft message. Saving to Me.Messages saves the message in the Drafts folder.
            _outlookClient.Me.Messages.AddMessageAsync(message).GetResult();

            return new MailItemProviderSDK(_outlookClient, message);
        }
        public async Task<bool> Create(MailModel model)
        {
            try
            {
                ItemBody body = new ItemBody();
                body.Content = model.Body;

                List<Recipient> recipients = new List<Recipient>();
                foreach (var item in model.ToRecipients)
                {
                    Recipient recipient = new Recipient();
                    recipient.Address = item;
                    recipients.Add(recipient);
                }
                var mail = new Message()
                {
                    Subject = model.Subject,
                    BodyPreview = model.Body,
                    Body = body,
                    ToRecipients = recipients
                };

                var client = await Office365Authenticator.GetClientInstance();

                await client.Me.Messages.AddMessageAsync(mail);

                return true;
            }
            catch 
            {
                
              
            }

            return false;
        }
        /// <summary>
        /// Updates an existing event in the user's default calendar
        /// </summary>
        /// <param name="eventId">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>
        /// <param name="startTime">TimeSpan. The start hour:Min:Sec of the event</param>
        /// <param name="endTime">TimeSpan. The end hour:Min:Sec of the event</param>
        /// <returns>IEvent. The updated event</returns>
        public static async Task<IEvent> UpdateCalendarEventAsync(string eventId,
            string LocationName,
            string BodyContent,
            string Attendees,
            string EventName,
            DateTimeOffset start,
            DateTimeOffset end,
            TimeSpan startTime,
            TimeSpan endTime)
        {
            // Make sure we have a reference to the Exchange client
            var client = await GetOutlookClientAsync();

            var eventToUpdate = await client.Me.Calendar.Events.GetById(eventId).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, startTime);
            eventToUpdate.End = (DateTimeOffset?)CalcNewTime(eventToUpdate.End, end, endTime);
            ItemBody body = new ItemBody();
            body.ContentType = BodyType.Text;
            body.Content = BodyContent;
            eventToUpdate.Body = body;

            // Update the calendar event in Exchange
            await eventToUpdate.UpdateAsync();

            Debug.WriteLine("Updated event: " + eventToUpdate.Id);
            return eventToUpdate;

            // 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 event 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 event updates you have saved locally  
            //    using the preceding UpdateAsync(true) call to the server, i.e., the user's Office 365 calendar.

        }
        public static async Task<bool> SendMessageAsync(
            string Subject,
            string Body,
            string RecipientAddress
            )
        {

            // Make sure we have a reference to the Outlook Services client
            var outlookClient = await GetOutlookClientAsync();

            //Create Body
            ItemBody body = new ItemBody
            {
                Content = Body,
                ContentType = BodyType.HTML
            };
            List<Recipient> toRecipients = new List<Recipient>();
            toRecipients.Add(new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = RecipientAddress
                }
            });

            Message newMessage = new Message
            {
                Subject = Subject,
                Body = body,
                ToRecipients = toRecipients
            };

            // To send a message without saving to Sent Items, specify false for  
            // the SavetoSentItems parameter. 
            await outlookClient.Me.SendMailAsync(newMessage, true);

            Debug.WriteLine("Sent mail: " + newMessage.Id);

            return true;

        }
        /// <summary>
        /// This method calls GraphService.Me.Events.AddEventAsync() to create an event
        /// on singed-in user's default calendar.  Due to a bug after the call does not
        /// the execution flow does not return back to the next line after the call.
        /// </summary>
        /// <param name="subject"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="attendeeEmails"></param>
        /// <param name="description"></param>
        /// <param name="locationDisplayName"></param>
        /// <returns></returns>
        public static async Task AddEventAsync(
            string subject,
            DateTimeOffset startTime,
            DateTimeOffset endTime,
            IEnumerable<string> attendeeEmails,
            string description,
            string locationDisplayName)
        {
            var client = await GetGraphClientAsync(PermissionScope);
            if (client == null)
            {
                throw new Exception("Error getting Microsoft Graph service client");
            }

            var @event = new Event();
            @event.Subject = subject;
            @event.Start = startTime;
            @event.End = endTime;
            @event.Location = new Location() { DisplayName = locationDisplayName };
            var listOfAttendees = new List<Attendee>();

            foreach (var email in attendeeEmails)
            {
                var name = await GetUserDisplayNameAsync(email);
                var attendee = new Attendee() { EmailAddress = new EmailAddress() { Address = email, Name = name } };
                listOfAttendees.Add(attendee);
            }
            @event.Attendees = listOfAttendees;
            var itemBody = new ItemBody();
            itemBody.ContentType = BodyType.Text;
            itemBody.Content = description;
            @event.Body = itemBody;
            // The following call never returns.  A bug was logged against O365 client library,
            // but it later was resolved as Not Repro.
            await client.Me.Events.AddEventAsync(@event);

            // So have to workaround using Rest Api below.
        }
        /// <summary>
        /// Adds a new event to user's default calendar
        /// </summary>
        public static async Task<string> AddCalendarEventAsync()
        {

            // Make sure we have a reference to the Exchange client
            var client = await GetOutlookClientAsync();

            Location location = new Location
            {
                DisplayName = "Water cooler"
            };
            ItemBody body = new ItemBody
            {
                Content = "Status updates, blocking issues, and next steps",
                ContentType = BodyType.Text
            };

            Attendee[] attendees =  
        { 
            new Attendee  
            { 
                Type = AttendeeType.Required, 
                EmailAddress = new EmailAddress  
                { 
                    Address = "*****@*****.**" 
                }, 
            }, 
        };

            Event newEvent = new Event
            {
                Subject = "Weekly Sync",
                Location = location,
                Attendees = attendees,
                Start = new DateTimeOffset(new DateTime(2014, 12, 1, 9, 30, 0)),
                End = new DateTimeOffset(new DateTime(2014, 12, 1, 10, 0, 0)),
                Body = body
            };

            await client.Me.Calendar.Events.AddEventAsync(newEvent);

            // Get the ID of the event. 
            string eventId = newEvent.Id;

            Debug.WriteLine("Added event: " + eventId);
            return eventId;


        }
        /// <summary>
        /// Creates a draft message and stores it in Drafts.
        /// </summary>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="RecipientAddress"></param>
        /// <returns>The ID of the draft.</returns>
        internal async Task<string> CreateDraftAsync(
            string Subject,
            string Body,
            string RecipientAddress)
        {

            // Make sure we have a reference to the Outlook Services client.
            var outlookClient = await AuthenticationHelper.GetOutlookClientAsync("Mail");

            ItemBody body = new ItemBody
            {
                Content = Body,
                ContentType = BodyType.HTML
            };
            List<Recipient> toRecipients = new List<Recipient>();
            toRecipients.Add(new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = RecipientAddress
                }
            });
            Message draftMessage = new Message
            {
                Subject = Subject,
                Body = body,
                ToRecipients = toRecipients,
                Importance = Importance.Normal
            };

            // Save the draft message. Saving to Me.Messages saves the message in the Drafts folder.
            await outlookClient.Me.Messages.AddMessageAsync(draftMessage);

            Debug.WriteLine("Created draft: " + draftMessage.Id);

            return draftMessage.Id;

        }
        public async void CreateNewMessage()
        {
            try
            {
                // split out the different email addresses and add to collection
                char[] delim = { ';' };
                
                // handle To:
                string[] toArray = tbToRecipients.Text.Split(delim);
                foreach (var to in toArray)
                {
                    AddRecipToCollection(to, toRecipients);
                }

                // handle Cc:
                string[] ccArray = tbCC.Text.Split(delim);
                foreach (var cc in toArray)
                {
                    AddRecipToCollection(cc, ccRecipients);
                }

                // handle Bcc:
                string[] bccArray = tbBcc.Text.Split(delim);
                foreach (var bcc in toArray)
                {
                    AddRecipToCollection(bcc, bccRecipients);
                }

                // create the item body
                ItemBody body = new ItemBody();
                body.Content = rtbBody.Text;
                body.ContentType = BodyType.Html;

                // create the message object and add the properties
                Microsoft.Graph.Message msg = new Microsoft.Graph.Message();
                msg.Subject = tbSubject.Text;
                msg.Body = body;
                msg.ToRecipients = toRecipients;
                msg.CcRecipients = ccRecipients;
                msg.BccRecipients = bccRecipients;

                // set importance
                if (cbxImportance.Text == "Normal")
                {
                    msg.Importance = Importance.Normal;
                }
                else if (cbxImportance.Text == "High")
                {
                    msg.Importance = Importance.High;
                }
                else
                {
                    msg.Importance = Importance.Low;
                }

                // setup the attachment collection
                if (dgAttachments.Rows.Count > 0)
                {
                    // setup the attachments collection
                    msg.Attachments = new MessageAttachmentsCollectionPage();

                    // add attachments
                    foreach (DataGridViewRow row in dgAttachments.Rows)
                    {
                        if (row.Cells[0].Value != null)
                        {
                            // create the file attachment from the file path
                            FileAttachment file = new FileAttachment();
                            byte[] array = System.IO.File.ReadAllBytes(row.Cells[0].Value.ToString());
                            file.ContentBytes = array;
                            file.Name = row.Cells[1].Value.ToString();
                            file.ContentType = row.Cells[2].Value.ToString();
                            file.ContentId = row.Cells[4].Value.ToString();
                            file.IsInline = false;
                            file.ODataType = row.Cells[6].Value.ToString();

                            // add it to the message        
                            msg.Attachments.Add(file);
                        }
                    }
                }                

                // log the request info
                sdklogger.Log(graphClient.Me.SendMail(msg, true).Request().GetHttpRequestMessage().Headers.ToString());
                sdklogger.Log(graphClient.Me.SendMail(msg, true).Request().GetHttpRequestMessage().RequestUri.ToString());

                // send the new message
                await graphClient.Me.SendMail(msg, true).Request().PostAsync();
            }
            catch (Exception ex)
            {
                sdklogger.Log("NewMessageSend Failed: ");
                sdklogger.Log(ex.Message);
                sdklogger.Log(ex.StackTrace);
            }
            finally
            {
                // close the form
                Close();
            }
        }
        /// <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>
        /// <param name="startTime">TimeSpan. The start hour:Min:Sec of the event</param>
        /// <param name="endTime">TimeSpan. The end hour:Min:Sec 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,
            TimeSpan startTime,
            TimeSpan endTime)
        {
            // Make sure we have a reference to the calendar client
            var calendarClient = await AuthenticationHelper.EnsureCalendarClientCreatedAsync();

            var thisEventFetcher = calendarClient.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.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, startTime);
            eventToUpdate.End = (DateTimeOffset?)CalcNewTime(eventToUpdate.End, end, endTime);
            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 calendarClient.Context.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw new Exception("Your calendar event was not updated on the Exchange service");
            }
            return eventToUpdate;
        }
        /// <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>
        /// <param name="startTime">TimeSpan. The start hour:Min:Sec of the event</param>
        /// <param name="endTime">TimeSpan. The end hour:Min:Sec of the event</param>
        /// <returns>The Id of the event that was created; Otherwise, null.</returns>
        public static async Task<string> AddCalendarEventWithArgsAsync(
            string LocationName,
            string BodyContent,
            string Attendees,
            string EventName,
            DateTimeOffset start,
            DateTimeOffset end,
            TimeSpan startTime,
            TimeSpan endTime)
        {
            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 = EventName,
                Location = location,
                Attendees = attendees,
                Start = start,
                End = end,
                Body = body,
            };
            //Add new times to start and end dates.
            newEvent.Start = (DateTimeOffset?)CalcNewTime(newEvent.Start, start, startTime);
            newEvent.End = (DateTimeOffset?)CalcNewTime(newEvent.End, end, endTime);

            // Make sure we have a reference to the calendar client
            var exchangeClient = await GetOutlookClientAsync();

            // This results in a call to the service.
            await exchangeClient.Me.Events.AddEventAsync(newEvent);
            Debug.WriteLine("Added event: " + newEvent.Id);
            return newEvent.Id;

        }