public static async Task <IUserCalendarViewCollectionPage> GetDayEventsAsync(string startDateTime, string endDateTime) { IUserCalendarViewCollectionPage events = null; try { GraphServiceClient graphClient = AuthenticationHelper.GetAuthenticatedClient(); string localTimeZone = TimeZoneInfo.Local.Id; List <Option> options = new List <Option>(); options.Add(new QueryOption("StartDateTime", startDateTime)); options.Add(new QueryOption("EndDateTime", endDateTime)); options.Add(new HeaderOption("Prefer", "outlook.timezone=\"" + localTimeZone + "\"")); events = await graphClient.Me.CalendarView.Request(options).OrderBy("start/DateTime").GetAsync(); } catch (ServiceException e) { Debug.WriteLine("Get events failed: " + e.Error.Message); return(null); } return(events); }
// Returns work range based on the calendars events passed as parameter. public static void CalculateWeekdaysCalendarWorkTime(IUserCalendarViewCollectionPage events, out DateTime arrivalTime, out DateTime departureTime) { TimeSpan arrivalStartDateTime = AppSettings.DefaultArrivalTime; TimeSpan arrivalEndDateTime = AppSettings.DefaultArrivalTime.Add(new TimeSpan(2, 0, 0)); TimeSpan departureStartDateTime = AppSettings.DefaultDepartureTime; TimeSpan departureEndDateTime = AppSettings.DefaultArrivalTime.Add(new TimeSpan(2, 0, 0)); arrivalTime = DateTime.Today + AppSettings.DefaultArrivalTime; departureTime = DateTime.Today + AppSettings.DefaultDepartureTime; try { // Get first and last time by day var eventsByDay = events? .Where(e => !string.IsNullOrEmpty(e?.Start?.DateTime)) .Where(e => !e.IsCancelled.HasValue || !e.IsCancelled.Value) .GroupBy(e => ParseLocalDate(e.Start.DateTime).ToString("MM/dd/yyyy"), (key, g) => new { StartDate = key, First = ParseLocalDate(g.First().Start.DateTime), Last = ParseLocalDate(g.Last().End.DateTime) }); if (eventsByDay != null && eventsByDay.Any()) { arrivalTime = eventsByDay.OrderBy(d => d.First.TimeOfDay).FirstOrDefault().First; departureTime = eventsByDay.OrderBy(d => d.Last.TimeOfDay).LastOrDefault().Last; // Range validations if (arrivalTime.TimeOfDay < arrivalStartDateTime || arrivalTime.TimeOfDay > arrivalEndDateTime) { arrivalTime = DateTime.Today + AppSettings.DefaultArrivalTime; } if (departureTime.TimeOfDay < departureStartDateTime || departureTime.TimeOfDay > departureEndDateTime) { departureTime = DateTime.Today + AppSettings.DefaultDepartureTime; } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
//Converts DateTime strings to local time and then strips them for display. public static void ConvertEventDates(IUserCalendarViewCollectionPage events) { foreach (var eventToConvert in events) { //Convert Start datetime if (eventToConvert.IsAllDay.GetValueOrDefault()) { eventToConvert.Start.DateTime = SampleStrings.AllDayMeeting; } else { eventToConvert.Start.DateTime = StripDateTimeForDisplay(eventToConvert.Start.DateTime); eventToConvert.End.DateTime = StripDateTimeForDisplay(eventToConvert.End.DateTime); } } }
private async Task <List <Event> > GetMyCalendarViewByTimeAsync(DateTime startTime, DateTime endTime) { var items = new List <Event>(); // Define the time span for the calendar view. var options = new List <QueryOption> { new QueryOption("startDateTime", startTime.ToString("o")), new QueryOption("endDateTime", endTime.ToString("o")), new QueryOption("$orderBy", "start/dateTime"), }; IUserCalendarViewCollectionPage events = null; try { events = await _graphClient.Me.CalendarView.Request(options).GetAsync(); } catch (ServiceException ex) { throw GraphClient.HandleGraphAPIException(ex); } if (events?.Count > 0) { items.AddRange(events); } while (events.NextPageRequest != null) { events = await events.NextPageRequest.GetAsync(); if (events?.Count > 0) { items.AddRange(events); } } return(items); }
// Get events in all the current user's mail folders. private async Task <List <Event> > GetMyStartTimeEventsAsync(DateTime startTime) { var items = new List <Event>(); // Get events. var options = new List <QueryOption>(); var endTime = startTime.AddDays(3); options.Add(new QueryOption("startdatetime", startTime.ToString("o"))); options.Add(new QueryOption("enddatetime", endTime.ToString("o"))); options.Add(new QueryOption("$orderBy", "start/dateTime")); IUserCalendarViewCollectionPage events = null; try { events = await _graphClient.Me.CalendarView.Request(options).GetAsync(); } catch (ServiceException ex) { throw GraphClient.HandleGraphAPIException(ex); } if (events?.Count > 0) { items.AddRange(events); } while (events.NextPageRequest != null) { events = await events.NextPageRequest.GetAsync(); if (events?.Count > 0) { items.AddRange(events); } } return(items); }
public static async Task <IUserCalendarViewCollectionPage> GetDayEventsAsync(string startDateTime, string endDateTime) { IUserCalendarViewCollectionPage events = null; try { var graphClient = AuthenticationHelper.GetAuthenticatedClient(); var options = new List <Option>(); options.Add(new QueryOption("StartDateTime", startDateTime)); options.Add(new QueryOption("EndDateTime", endDateTime)); events = await graphClient.Me.CalendarView.Request(options).OrderBy("start/DateTime").GetAsync(); } catch (ServiceException e) { Debug.WriteLine(SampleStrings.GetEventsFailed + e.Error.Message); return(null); } return(events); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { // Developer code - if you haven't registered the app yet, we warn you. if (!App.Current.Resources.ContainsKey("ida:ClientID")) { Debug.WriteLine(ResourceLoader.GetForCurrentView().GetString("NoClientIdMessage")); } string parameter = (string)e.Parameter; await ConnectUser(); DateTime startDate = DateTime.Now; DateTime endDate = DateTime.Now.AddDays(1).AddTicks(-1); if (parameter == "showNextMeeting") { IUserCalendarViewCollectionPage events = await CalendarHelper.GetDayEventsAsync(startDate.ToString("o"), endDate.ToString("o")); if (events.Count > 0) { Message.Text = ResourceLoader.GetForCurrentView().GetString("NextMeetingIntro"); MeetingTitle.Text = events[0].Subject; MeetingTimes.Text = events[0].Start.DateTime.Substring(0, 16) + " - " + events[0].End.DateTime.Substring(0, 16); Participants.ItemsSource = events[0].Attendees; Participants.Header = ResourceLoader.GetForCurrentView().GetString("ParticipantsText"); Participants.Visibility = Visibility.Visible; } else { Salutation.Text = ResourceLoader.GetForCurrentView().GetString("NoMeetingsFound"); } } else if (parameter == "lateMeeting") { IUserCalendarViewCollectionPage events = await CalendarHelper.GetDayEventsAsync(startDate.ToString("o"), endDate.ToString("o")); if (events.Count > 0) { bool emailSent = await CalendarHelper.SendReplyAllMessageAsync(ResourceLoader.GetForCurrentView().GetString("RunningLateMessage"), events[0].Subject, events[0].IsOrganizer); if (emailSent) { Message.Text = ResourceLoader.GetForCurrentView().GetString("RunningLateConfirmation"); MeetingTitle.Text = events[0].Subject; MeetingTimes.Text = events[0].Start.DateTime + " - " + events[0].End.DateTime; Participants.ItemsSource = events[0].Attendees; Participants.Header = ResourceLoader.GetForCurrentView().GetString("RecipientsText"); Participants.Visibility = Visibility.Visible; } else { Message.Text = ResourceLoader.GetForCurrentView().GetString("ReplyAllFailed"); } } else { Message.Text = ResourceLoader.GetForCurrentView().GetString("NoMeetingsFound"); } } }
/// <inheritdoc/> internal override async Task <List <CalendarSkillEventModel> > CallGraphServiceWithResultAsync(IGraphServiceClient client, IReadOnlyDictionary <string, object> parameters, CancellationToken cancellationToken) { var startProperty = (DateTime?)parameters["StartProperty"]; var endProperty = (DateTime?)parameters["EndProperty"]; var timeZoneProperty = (string)parameters["TimeZoneProperty"]; var dateTimeTypeProperty = (string)parameters["DateTimeTypeProperty"]; var isFuture = (bool)parameters["FutureEventsOnlyProperty"]; var maxResults = (int)parameters["MaxResultsProperty"]; var userEmail = (string)parameters["UserEmailProperty"]; var timeZone = GraphUtils.ConvertTimeZoneFormat((string)parameters["TimezoneProperty"]); // if start date is not provided, default to DateTime.Now var now = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeZone); // if datetime field just contains time but no date, use date today at use's timezone if (!dateTimeTypeProperty.Contains("date")) { if (startProperty != null) { startProperty = now.Date + startProperty.Value.TimeOfDay; } if (endProperty != null) { endProperty = now.Date + endProperty.Value.TimeOfDay; } } if (startProperty == null || startProperty.Value == DateTime.MinValue || (startProperty <= now && isFuture)) { startProperty = now; } // if end date is not provided, default to end of the current day if (endProperty == null || endProperty.Value == DateTime.MinValue) { endProperty = startProperty.Value.Date.AddHours(23).AddMinutes(59); } var parsedEvents = new List <CalendarSkillEventModel>(); // Define the time span for the calendar view. var queryOptions = new List <QueryOption> { // The API expects the parameters in UTC, but the datetimes come into the action in the user's timezone new QueryOption("startDateTime", TimeZoneInfo.ConvertTimeToUtc(startProperty.Value, timeZone).ToString("o")), new QueryOption("endDateTime", TimeZoneInfo.ConvertTimeToUtc(endProperty.Value, timeZone).ToString("o")), new QueryOption("$orderBy", "start/dateTime"), }; IUserCalendarViewCollectionPage events = await client.Me.CalendarView.Request(queryOptions).GetAsync(cancellationToken).ConfigureAwait(false); int index = 0; if (events?.Count > 0) { foreach (var ev in events) { parsedEvents.Add(this.ParseEvent(ev, timeZone, index++, userEmail)); } } while (events.NextPageRequest != null) { events = await events.NextPageRequest.GetAsync().ConfigureAwait(false); if (events?.Count > 0) { foreach (var ev in events) { parsedEvents.Add(this.ParseEvent(ev, timeZone, index++, userEmail)); } } } // Filter results by datetime if dateTimeType is a specific datetime if (dateTimeTypeProperty != null && dateTimeTypeProperty.Contains("time")) { parsedEvents = parsedEvents.Where(r => DateTime.Parse(r.Start.DateTime) == startProperty).ToList(); } parsedEvents = parsedEvents .Where(ev => ev.IsAllDay == false && DateTime.Parse(ev.Start.DateTime).Date >= startProperty.Value.Date) .OrderBy(ev => DateTime.Parse(ev.Start.DateTime).Date) .Take(maxResults) .ToList(); return(parsedEvents); }
private async Task ShowPersonalizedInfoPanel(Person person) { ClientCredential credential = new ClientCredential(ClientId, ClientSecret); AzureTableStoreTokenCache tokenCache = await AzureTableStoreTokenCache.GetTokenCacheAsync(new TokenCacheConfig(), person.Name); AuthenticationContext authContext = new AuthenticationContext(Authority, tokenCache); AuthenticationResult accessTokenAuthenticationResult = await authContext.AcquireTokenSilentAsync(MicrosoftGraphEndpoint, credential, new UserIdentifier(person.Name, UserIdentifierType.UniqueId)); GraphServiceClient graphClient = new GraphServiceClient( new DelegateAuthenticationProvider( (requestMessage) => { string accessToken = accessTokenAuthenticationResult.AccessToken; requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); return(Task.FromResult(0)); })); User me = await graphClient.Me.Request().Select(UserParameters).GetAsync(); // Get user's unread mail count var inbox = await graphClient.Me.MailFolders.Inbox.Request().GetAsync(); var unreadMail = inbox.UnreadItemCount; if (unreadMail > 99) { unreadMail = 99; } tbMail.Text = unreadMail.ToString(); // Weather var weather = await GetCurrentWeather(); int currentTemperature = (int)weather.Temperature.Value; tbWeatherValue.Text = currentTemperature.ToString(); var icon = GetWeatherIcon(weather.Weather.Icon); WeatherImage.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(base.BaseUri, icon)); tbWeatherText.Text = weather.Weather.Value; List <QueryOption> options = new List <QueryOption> { new QueryOption(StartDatetimeGraphQueryOption, DateTime.UtcNow.ToString("o")), new QueryOption(EndDatetimeGraphQueryOption, DateTime.UtcNow.AddDays(1).ToString("o")) }; IUserCalendarViewCollectionPage cal = await graphClient.Me.CalendarView.Request(options).Top(1).GetAsync(); DrivingInfo drivingInfo; string displayName, displayDrive, displayNext; try { drivingInfo = await GetDrivingInfoAsync(me.City); displayDrive = string.Concat("Office ETA ", (drivingInfo.DurationTrafic / 60).ToString("F0"), "mins (", drivingInfo.Distance.ToString("F0"), "Km)"); } catch (Exception ex) { displayDrive = string.Empty; HockeyClient.Current.TrackEvent("User Driving Info - Exception", new Dictionary <string, string> { { "Message", ex.Message }, { "Stack", ex.StackTrace } }); } if (!string.IsNullOrEmpty(me.DisplayName)) { displayName = string.Concat("Hi ", me.DisplayName); } else { displayName = string.Empty; HockeyClient.Current.TrackEvent("User Display Name", new Dictionary <string, string> { { "User", me.Id } }); } if (cal.FirstOrDefault() != null) { displayNext = string.Concat("Next: ", cal.FirstOrDefault().Subject, " @ ", cal.FirstOrDefault().Location.DisplayName); } else { displayNext = string.Empty; HockeyClient.Current.TrackEvent("User Calendar", new Dictionary <string, string> { { "User", me.Id } }); } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { tbName.Text = displayName; tbDrive.Text = displayDrive; tbNext.Text = displayNext; }); }