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 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(); } }
public object Convert(object value, Type targetType, object parameter, string language) { DateTimeTimeZone date = value as DateTimeTimeZone; if (date != null) { // Resolve the time zone var timezone = TimeZoneInfo.FindSystemTimeZoneById(date.TimeZone); // Parse method assumes local time, which may not be the case var parsedDateAsLocal = DateTimeOffset.Parse(date.DateTime); // Determine the offset from UTC time for the specific date // Making this call adjusts for DST as appropriate var tzOffset = timezone.GetUtcOffset(parsedDateAsLocal.DateTime); // Create a new DateTimeOffset with the specific offset from UTC var correctedDate = new DateTimeOffset(parsedDateAsLocal.DateTime, tzOffset); // Return the local date time string return(correctedDate.LocalDateTime.ToString()); } return(string.Empty); }
public async Task <bool> CreateAppointment(string subject, string content, int day, string monthName, int year, int startTime, int EndTime) { try { User user = (await _graphServiceClient.Users.Request().GetAsync()).Where(x => x.DisplayName.Contains("Ferran")).FirstOrDefault(); Microsoft.Graph.Event @event = new Event(); @event.Subject = subject; ItemBody body = new ItemBody(); body.Content = content; body.ContentType = Microsoft.Graph.BodyType.Html; DateTimeTimeZone start = new DateTimeTimeZone(); start.DateTime = new DateTime(year, DateTime.ParseExact(monthName, "MMMM", new CultureInfo("es-ES")).Month, day, startTime, 0, 0).ToString("yyyy-MM-ddTHH:mm:ss"); start.TimeZone = "Europe/Madrid"; DateTimeTimeZone end = new DateTimeTimeZone(); end.DateTime = new DateTime(year, DateTime.ParseExact(monthName, "MMMM", new CultureInfo("es-ES")).Month, day, EndTime, 0, 0).ToString("yyyy-MM-ddTHH:mm:ss"); end.TimeZone = "Europe/Madrid"; Location location = new Location(); location.DisplayName = "Microsoft Iberica Madrid"; @event.Body = body; @event.Start = start; @event.End = end; @event.Location = location; await _graphServiceClient.Users[user.Id].Calendar.Events.Request().AddAsync(@event); return(true); } catch (Exception ex) { throw ex; } }
public Task <ICalendarGetScheduleCollectionPage> SearchAvailableTime(string[] emails, string start, string end, int interval) { var schedules = new List <string>(emails); var startTime = new DateTimeTimeZone { DateTime = start, TimeZone = "UTC" }; var endTime = new DateTimeTimeZone { DateTime = end, TimeZone = "UTC" }; return(GraphClient.Me.Calendar .GetSchedule(schedules, endTime, startTime, interval) .Request() .Header("Prefer", "outlook.timezone=\"UTC\"") .PostAsync()); }
private async Task DoSomethingAsync() { try { var token = await TokenService.GetAuthenticationResultForUserAsync(new[] { "User.Read", "Calendars.ReadWrite" }); Console.WriteLine(token.AccessToken); await Graph.Me.Calendar.Events.Request().AddAsync(new Event { Subject = "Hey stupid", Start = DateTimeTimeZone.FromDateTime(DateTime.Now), End = DateTimeTimeZone.FromDateTime(DateTime.Now.AddMinutes(15)) }); _name = (await Graph.Me.Request().GetAsync()).DisplayName; } catch (Exception ex) { ConsentHandler.HandleException(ex); } }
// </GetEventsSnippet> public List <EventHolder> ListCalendarEvents() { var events = GetEventsAsync().Result; List <EventHolder> eventsList = new List <EventHolder>(); foreach (var calendarEvent in events) { //Console.WriteLine(calendarEvent.Subject); DateTimeTimeZone start = calendarEvent.Start; DateTimeOffset startOffset = OffsetOfDateTimeTimeZone(start); //Console.WriteLine(startOffset.ToString("g")); DateTimeOffset current = new DateTimeOffset(DateTime.Now); DateTimeOffset plus10 = new DateTimeOffset(DateTime.Now).AddMinutes(10); if (startOffset.CompareTo(current) < 0) { //Console.WriteLine("The date is in the past."); continue; } if (startOffset.CompareTo(plus10) > 0) { //Console.WriteLine("The date is in the future."); continue; } var catEnum = calendarEvent.Categories.GetEnumerator(); if (!catEnum.MoveNext()) { //Console.WriteLine("No category."); continue; } var eventHolder = new EventHolder(); eventHolder.Subject = calendarEvent.Subject; eventHolder.Category = catEnum.Current; eventHolder.Date = startOffset; eventsList.Add(eventHolder); } return(eventsList); }
/// <summary> /// Converts DateTimeTimeZone which is a Complex Type to DateTime /// </summary> /// <param name="dateTimeTimeZone"></param> /// <returns></returns> public static DateTime ToDateTime(this DateTimeTimeZone dateTimeTimeZone) { DateTime dateTime = DateTime.ParseExact(dateTimeTimeZone.DateTime, DateTimeTimeZone.DateTimeFormat, CultureInfo.InvariantCulture); // Now we need to determine which DateTimeKind to set based on the time zone specified in the input object. TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(dateTimeTimeZone.TimeZone); DateTimeKind kind; if (timeZoneInfo.Id == TimeZoneInfo.Utc.Id) { kind = DateTimeKind.Utc; } else if (timeZoneInfo.Id == TimeZoneInfo.Local.Id) { kind = DateTimeKind.Local; } else { kind = DateTimeKind.Unspecified; } return(DateTime.SpecifyKind(dateTime, kind)); }
public static async Task <ICalendarGetScheduleCollectionPage> GetSchedules(string userToken, string start, string end) { try { // Set the start and end times of the availability window var startTime = new DateTimeTimeZone { DateTime = start, TimeZone = "UTC" }; var endTime = new DateTimeTimeZone { DateTime = end, TimeZone = "UTC" }; // Get all flight attendants var flightAttendants = await GetGroupMembers("Flight Attendants"); // Build a list of flight attendant emails var flightAttendantEmails = new List <string>(); foreach (var flightAttendant in flightAttendants) { flightAttendantEmails.Add((flightAttendant as User).Mail); } // Call getSchedule API to get availability map return(await userClient.Me.Calendar .GetSchedule(flightAttendantEmails, endTime, startTime) .Request() .WithUserAssertion(new UserAssertion(userToken)) .PostAsync()); } catch (Exception ex) { Console.WriteLine($"GetSchedules - Exception: {ex.ToString()}"); return(null); } }
public async Task <IActionResult> EndsEvent( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "event/ends")] HttpRequest req) { try { var graphClient = GetGraphClient(configuration.GraphV1); var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var input = JsonConvert.DeserializeObject <EndsEvent>(requestBody); var timeZone = input.TimeZone; var endTime = new DateTimeTimeZone { DateTime = input.Ended, TimeZone = timeZone }; //var ev = await graphClient.Users[input.MeetingRoom.Mail].Events[input.Id].Request().GetAsync(); //ev.End = endTime; var ev = new Microsoft.Graph.Event { End = endTime }; await graphClient.Users[input.MeetingRoom.Mail].Events[input.Id].Request().UpdateAsync(ev); return(new OkObjectResult(Result.Ok())); } catch (Exception e) { var error = $"{e.Message}\n\r{e.StackTrace}"; log.Error(error); return(new OkObjectResult(Result.Fail(error))); } }
public static EventModel CreateEventModel( EmailAddress[] emailAddress = null, string eventName = null, string content = null, DateTime?startDateTime = null, DateTime?endDateTime = null, string locationString = null, bool isOrganizer = true, bool isCancelled = false) { var attendees = new List <Attendee>(); if (emailAddress != null) { foreach (var email in emailAddress) { attendees.Add(new Attendee { EmailAddress = email, Type = AttendeeType.Required, }); } } else { attendees.Add(new Attendee { EmailAddress = new EmailAddress { Address = Strings.Strings.DefaultUserEmail, Name = Strings.Strings.DefaultUserName, }, Type = AttendeeType.Required, }); } // Event Name eventName = eventName ?? Strings.Strings.DefaultEventName; // Event body var body = new ItemBody { Content = content ?? Strings.Strings.DefaultContent, ContentType = BodyType.Text, }; // Event start and end time // Another example date format: `new DateTime(2017, 12, 1, 9, 30, 0).ToString("o")` if (startDateTime == null) { DateTime now = DateTime.Now; DateTime startTime = new DateTime(now.Year, now.Month, now.Day, 18, 0, 0); startTime = TimeZoneInfo.ConvertTimeToUtc(startTime); startDateTime = startTime.AddDays(1); } if (endDateTime == null) { endDateTime = startDateTime.Value.AddHours(1); } var startTimeTimeZone = new DateTimeTimeZone { DateTime = startDateTime.Value.ToString("o"), TimeZone = TimeZoneInfo.Local.Id, }; var endTimeTimeZone = new DateTimeTimeZone { DateTime = endDateTime.Value.ToString("o"), TimeZone = TimeZoneInfo.Local.Id, }; // Event location var location = new Location { DisplayName = locationString ?? Strings.Strings.DefaultLocation, }; // Add the event. // await _graphClient.Me.Events.Request().AddAsync var createdEvent = new Event { Subject = eventName, Location = location, Attendees = attendees, Body = body, Start = startTimeTimeZone, End = endTimeTimeZone, IsOrganizer = isOrganizer, IsCancelled = isCancelled, ResponseStatus = new ResponseStatus() { Response = ResponseType.Organizer } }; return(new EventModel(createdEvent)); }
private void CreatePropTable(object itemResult) { try { foreach (var prop in itemResult.GetType().GetProperties()) { DataGridViewRow propRow = new DataGridViewRow(); string propName = prop.Name; string propValue = ""; string propType = ""; if (prop.GetIndexParameters().Length == 0) { try { var tempValue = prop.GetValue(itemResult); propType = tempValue.GetType().ToString(); if (tempValue is DateTimeOffset) { DateTimeOffset dateTimeOffsetValue = (DateTimeOffset)tempValue; propValue = dateTimeOffsetValue.DateTime.ToString("yyyy/MM/dd HH:mm:ss"); } else if (tempValue is ItemBody) { ItemBody itemBodyValue = (ItemBody)tempValue; propValue = itemBodyValue.Content; } else if (tempValue is Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <Recipient> ) { Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <Recipient> recipientValue = (Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <Recipient>)tempValue; foreach (Recipient recipient in recipientValue) { propValue += recipient.EmailAddress.Name + "<" + recipient.EmailAddress.Address + ">; "; } propValue = propValue.TrimEnd(new char[] { ';', ' ' }); } else if (tempValue is Microsoft.OData.ProxyExtensions.EntityCollectionImpl <Attachment> ) { // To get the list of attachments, we have to send a request again. // We don't do that and prepare an attachment view. continue; } else if (tempValue is Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <string> ) { Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <string> stringValue = (Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <string>)tempValue; foreach (string value in stringValue) { propValue += value + "; "; } propValue = propValue.TrimEnd(new char[] { ';', ' ' }); } else if (tempValue is Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <EmailAddress> ) { Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <EmailAddress> emailAddressValue = (Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <EmailAddress>)tempValue; foreach (EmailAddress emailAddress in emailAddressValue) { propValue += emailAddress.Name + "<" + emailAddress.Address + ">; "; } propValue = propValue.TrimEnd(new char[] { ';', ' ' }); } else if (tempValue is PhysicalAddress) { PhysicalAddress physicalAddressValue = (PhysicalAddress)tempValue; propValue = physicalAddressValue.PostalCode + " " + physicalAddressValue.Street + " " + physicalAddressValue.City + " " + physicalAddressValue.State + " " + physicalAddressValue.CountryOrRegion; } else if (tempValue is ResponseStatus) { ResponseStatus responseStatusValue = (ResponseStatus)tempValue; if (responseStatusValue.Time.HasValue) { propValue = responseStatusValue.Time.Value.DateTime.ToString("yyyy/MM/dd HH:mm:ss") + " "; } propValue += responseStatusValue.Response.ToString(); } else if (tempValue is DateTimeTimeZone) { DateTimeTimeZone dateTimeTimeZoneValue = (DateTimeTimeZone)tempValue; propValue = dateTimeTimeZoneValue.TimeZone + " " + dateTimeTimeZoneValue.DateTime; } else if (tempValue is Location) { Location locationValue = (Location)tempValue; propValue = locationValue.DisplayName; } else if (tempValue is Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <Attendee> ) { Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <Attendee> attendeeValue = (Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <Attendee>)tempValue; foreach (Recipient attendee in attendeeValue) { propValue += attendee.EmailAddress.Name + "<" + attendee.EmailAddress.Address + ">; "; } propValue = propValue.TrimEnd(new char[] { ';', ' ' }); } else if (tempValue is Recipient) { Recipient recipientValue = (Recipient)tempValue; propValue = recipientValue.EmailAddress.Name + "<" + recipientValue.EmailAddress.Address + ">"; } else if (tempValue is Microsoft.OData.ProxyExtensions.EntityCollectionImpl <Event> ) { // I'm not sure what this prop is. // This prop has a Nested structure. continue; } else { propValue = tempValue.ToString(); } } catch { propValue = ""; } } else { propValue = "indexed"; } propRow.CreateCells(dataGridView_ItemProps, new object[] { propName, propValue, propType }); if (dataGridView_ItemProps.InvokeRequired) { dataGridView_ItemProps.Invoke(new MethodInvoker(delegate { dataGridView_ItemProps.Rows.Add(propRow); })); } else { dataGridView_ItemProps.Rows.Add(propRow); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Office365APIEditor"); } }
public async System.Threading.Tasks.Task <bool> TrySetOOF365(string oofMessageExternal, string oofMessageInternal, DateTime StartTime, DateTime EndTime) { OOFSponderInsights.TrackInfo(OOFSponderInsights.CurrentMethod()); toolStripStatusLabel1.Text = DateTime.Now.ToString() + " - Sending to O365"; //need to convert the times from local datetime to DateTimeTimeZone and UTC DateTimeTimeZone oofStart = new DateTimeTimeZone { DateTime = StartTime.ToUniversalTime().ToString("u").Replace("Z", ""), TimeZone = "UTC" }; DateTimeTimeZone oofEnd = new DateTimeTimeZone { DateTime = EndTime.ToUniversalTime().ToString("u").Replace("Z", ""), TimeZone = "UTC" }; //create local OOF object AutomaticRepliesSetting localOOF = new AutomaticRepliesSetting(); localOOF.ExternalReplyMessage = oofMessageExternal; localOOF.InternalReplyMessage = oofMessageInternal; localOOF.ScheduledStartDateTime = oofStart; localOOF.ScheduledEndDateTime = oofEnd; localOOF.Status = AutomaticRepliesStatus.Scheduled; try { OOFSponderInsights.Track("Getting OOF settings from O365"); string getOOFraw = await O365.GetHttpContentWithToken(O365.AutomatedReplySettingsURL); AutomaticRepliesSetting remoteOOF = JsonConvert.DeserializeObject <AutomaticRepliesSetting>(getOOFraw); OOFSponderInsights.Track("Successfully got OOF settings"); bool externalReplyMessageEqual = remoteOOF.ExternalReplyMessage.CleanReplyMessage() == localOOF.ExternalReplyMessage.CleanReplyMessage(); bool internalReplyMessageEqual = remoteOOF.InternalReplyMessage.CleanReplyMessage() == localOOF.InternalReplyMessage.CleanReplyMessage(); //local and remote are both UTC, so just compare times //Not sure it can ever happen to have the DateTime empty, but wrap this in a TryCatch just in case //set both to false - that way, we don't care if either one blows up //because if one is false, the overall evaluation is false anyway bool scheduledStartDateTimeEqual = false; bool scheduledEndDateTimeEqual = false; try { scheduledStartDateTimeEqual = DateTime.Parse(remoteOOF.ScheduledStartDateTime.DateTime) == DateTime.Parse(localOOF.ScheduledStartDateTime.DateTime); scheduledEndDateTimeEqual = DateTime.Parse(remoteOOF.ScheduledEndDateTime.DateTime) == DateTime.Parse(localOOF.ScheduledEndDateTime.DateTime); } catch (Exception) { //do nothing because we will just take the initialized false values; } if (!externalReplyMessageEqual || !internalReplyMessageEqual || !scheduledStartDateTimeEqual || !scheduledEndDateTimeEqual ) { OOFSponderInsights.Track("Local OOF doesn't match remote OOF"); System.Net.Http.HttpResponseMessage result = await O365.PatchHttpContentWithToken(O365.MailboxSettingsURL, localOOF); if (result.StatusCode == System.Net.HttpStatusCode.OK) { UpdateStatusLabel(toolStripStatusLabel1, DateTime.Now.ToString() + " - OOF message set - Start: " + StartTime + " - End: " + EndTime); //report back to AppInsights OOFSponderInsights.Track("Successfully set OOF"); return(true); } else { OOFSponderInsights.Track("Unable to set OOF"); UpdateStatusLabel(toolStripStatusLabel1, DateTime.Now.ToString() + " - Unable to set OOF message"); return(false); } } else { OOFSponderInsights.Track("Remote OOF matches - no changes"); UpdateStatusLabel(toolStripStatusLabel1, DateTime.Now.ToString() + " - No changes needed, OOF Message not changed - Start: " + StartTime + " - End: " + EndTime); return(true); } } catch (Exception ex) { notifyIcon1.ShowBalloonTip(100, "OOF Exception", "Unable to set OOF: " + ex.Message, ToolTipIcon.Error); UpdateStatusLabel(toolStripStatusLabel1, DateTime.Now.ToString() + " - Unable to set OOF"); OOFSponderInsights.TrackException("Unable to set OOF: " + ex.Message, ex); return(false); } }
// Creates a new event in the signed-in user's tenant. // Important note: This will create a user with a weak password. Consider deleting this user after you run the sample. public static async Task <string> CreateEventAsync() { string createdEventId = null; //List of attendees List <Attendee> attendees = new List <Attendee>(); var attendee = new Attendee(); var emailAddress = new EmailAddress(); emailAddress.Address = "*****@*****.**"; attendee.EmailAddress = emailAddress; attendee.Type = AttendeeType.Required; attendees.Add(attendee); //Event body var eventBody = new ItemBody(); eventBody.Content = "Status updates, blocking issues, and next steps"; eventBody.ContentType = BodyType.Text; //Event start and end time var eventStartTime = new DateTimeTimeZone(); eventStartTime.DateTime = new DateTime(2014, 12, 1, 9, 30, 0).ToString("o"); eventStartTime.TimeZone = "UTC"; var eventEndTime = new DateTimeTimeZone(); eventEndTime.TimeZone = "UTC"; eventEndTime.DateTime = new DateTime(2014, 12, 1, 10, 0, 0).ToString("o"); //Create an event to add to the events collection var location = new Location(); location.DisplayName = "Water cooler"; var newEvent = new Event(); newEvent.Subject = "weekly sync"; newEvent.Location = location; newEvent.Attendees = attendees; newEvent.Body = eventBody; newEvent.Start = eventStartTime; newEvent.End = eventEndTime; try { var graphClient = AuthenticationHelper.GetAuthenticatedClient(); var createdEvent = await graphClient.Me.Events.Request().AddAsync(newEvent); createdEventId = createdEvent.Id; if (createdEventId != null) { Debug.WriteLine("Created event: " + createdEventId); } } catch (ServiceException e) { Debug.WriteLine("We could not create an event: " + e.Error.Message); return(null); } return(createdEventId); }
/// <summary> /// All properties /// </summary> public AutomaticRepliesSetting(AutomaticRepliesStatus Status, ExternalAudienceScope ExternalAudience, String ExternalReplyMessage, String InternalReplyMessage, DateTimeTimeZone ScheduledStartDateTimeUTC, DateTimeTimeZone ScheduledEndDateTimeUTC, String User, object BaseObject, String Name) { this.Status = Status; this.ExternalAudience = ExternalAudience; this.ExternalReplyMessage = ExternalReplyMessage; this.InternalReplyMessage = InternalReplyMessage; this.ScheduledStartDateTimeUTC = ScheduledStartDateTimeUTC; this.ScheduledEndDateTimeUTC = ScheduledEndDateTimeUTC; this.User = User; this.BaseObject = BaseObject; this.Name = Name; }
// Create the email message. public async Task <Event> BuildEmailMessage(string accessToken, string recipients, string subject) { // Prepare the recipient list. string[] splitter = { ";" }; string[] splitRecipientsString = recipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries); List <Attendee> recipientList = new List <Attendee>(); foreach (string recipient in splitRecipientsString) { Attendee tempAttender = new Attendee(); EmailAddress tempEmailadd = new EmailAddress(); tempEmailadd.Address = recipient.Trim(); tempAttender.EmailAddress = tempEmailadd; recipientList.Add(tempAttender); } Microsoft.Graph.Location loc = new Location(); loc.DisplayName = "The Oval conf room"; Attendee attender1 = new Attendee(); EmailAddress emailadd1 = new EmailAddress(); emailadd1.Address = "*****@*****.**"; emailadd1.Name = "Anne-Marie Sylvester"; attender1.EmailAddress = emailadd1; recipientList.Add(attender1); Attendee attender2 = new Attendee(); EmailAddress emailadd2 = new EmailAddress(); emailadd2.Address = "*****@*****.**"; emailadd2.Name = "Charles Wahome "; attender2.EmailAddress = emailadd2; recipientList.Add(attender2); Attendee attender3 = new Attendee(); EmailAddress emailadd3 = new EmailAddress(); emailadd3.Address = "*****@*****.**"; emailadd3.Name = "Marvin Ochieng "; attender3.EmailAddress = emailadd3; recipientList.Add(attender3); Attendee attender4 = new Attendee(); EmailAddress emailadd4 = new EmailAddress(); emailadd4.Address = "*****@*****.**"; emailadd4.Name = "Duncan Okwako "; attender4.EmailAddress = emailadd4; recipientList.Add(attender4); ItemBody eventBody = new ItemBody(); eventBody.ContentType = "HTML"; eventBody.Content = "Annual Strategic Planning Retreat–2018"; DateTimeTimeZone eventStartTime = new DateTimeTimeZone(); eventStartTime.DateTime = "2018-11-29T06:00:00"; eventStartTime.TimeZone = "Pacific Standard Time"; DateTimeTimeZone eventEndTime = new DateTimeTimeZone(); eventEndTime.DateTime = "2018-11-29T06:55:00"; eventEndTime.TimeZone = "Pacific Standard Time"; var newEvent = new Event(); newEvent.Subject = "Annual Strategic Planning Retreat–2018 "; newEvent.Location = loc; newEvent.Attendees = recipientList; //newEvent.Body = eventBody; newEvent.Start = eventStartTime; newEvent.End = eventEndTime; return(newEvent); }
public async Task <Event> CreateEvent(string subject, DateTimeTimeZone startTime, DateTimeTimeZone endTime, string htmlContent, IEnumerable <Attendee> attendees, Meeting meeting, string bucketId) { //Extension var evExtCollPage = new EventExtensionsCollectionPage(); var dict = new Dictionary <string, object>(); dict.Add("teamId", meeting.TeamId); dict.Add("channelId", meeting.ChannelId); dict.Add("meetingId", meeting.Id); dict.Add("bucketId", bucketId); var openExtension = new OpenTypeExtension { ODataType = "microsoft.graph.openTypeExtension", ExtensionName = EXTENSION_NAME, AdditionalData = dict }; evExtCollPage.Add(openExtension); var groupEvent = new Event() { Subject = subject, Start = startTime, End = endTime, Body = new ItemBody { ContentType = BodyType.Html, Content = htmlContent }, Attendees = attendees, Extensions = evExtCollPage }; return(await GraphClient.Groups[meeting.TeamId].Events.Request().AddAsync(groupEvent)); }
private static async Task <CheckedRoom> GetRoomSchedule(GraphServiceClient graphClient, CheckedRoom room, DateTime dateTime, CheckedRoom roomRecent) { try { var beginTime = new DateTimeTimeZone { DateTime = dateTime.Date.ToString("yyyy-MM-ddTHH:mm:ssZ"), TimeZone = "UTC" }; var endTime = new DateTimeTimeZone { DateTime = dateTime.Date.AddDays(0).AddHours(23).ToString("yyyy-MM-ddTHH:mm:ssZ"), TimeZone = "UTC" }; var roomFreeBusy = await graphClient.Users[room.Id].Calendar.GetSchedule(new List <string> { room.Id }, endTime, beginTime).Request().PostAsync(); if (roomFreeBusy.First().ScheduleItems.Count() == 0) { roomRecent.Available = true; } else { var orderedRoomSchedules = roomFreeBusy.First().ScheduleItems.Where(r => r.Status != FreeBusyStatus.Free).OrderBy(r => r.Start.DateTime).ToList(); var cetTime = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); var scheduleArray = orderedRoomSchedules.ToArray(); var roomBusy = false; for (var s = 0; s < scheduleArray.Length; s++) { var beginHour = TimeZoneInfo.ConvertTimeFromUtc(DateTime.Parse(scheduleArray[s].Start.DateTime), cetTime).Hour; var endHour = TimeZoneInfo.ConvertTimeFromUtc(DateTime.Parse(scheduleArray[s].End.DateTime), cetTime).Hour; var hourSchedule = new HourSchedule { Occupied = true, StartTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.Parse(scheduleArray[s].Start.DateTime), cetTime), EndTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.Parse(scheduleArray[s].End.DateTime), cetTime) }; for (int t = beginHour; t <= endHour; t++) { if (t == endHour) { if (TimeZoneInfo.ConvertTimeFromUtc(DateTime.Parse(scheduleArray[s].End.DateTime), cetTime).Minute > 0) { roomRecent.DaySchedule[t] = hourSchedule; } } else { roomRecent.DaySchedule[t] = hourSchedule; } } if (DateTime.Parse(scheduleArray[s].Start.DateTime) <= dateTime.ToUniversalTime() && DateTime.Parse(scheduleArray[s].End.DateTime) > dateTime.ToUniversalTime()) { //Event is now roomBusy = true; roomRecent.Available = false; if (roomRecent.FreeAt < TimeZoneInfo.ConvertTimeFromUtc(DateTime.Parse(scheduleArray[s].End.DateTime), cetTime)) { //if the end data of current meeting is after the enddate of a previous meeting roomRecent.FreeAt = TimeZoneInfo.ConvertTimeFromUtc(DateTime.Parse(scheduleArray[s].End.DateTime), cetTime); } } if (DateTime.Parse(scheduleArray[s].Start.DateTime) <= dateTime.ToUniversalTime() && DateTime.Parse(scheduleArray[s].End.DateTime) < dateTime.ToUniversalTime()) { //Event has happenend if (!roomBusy) { roomRecent.Available = true; } } if (DateTime.Parse(scheduleArray[s].Start.DateTime) >= dateTime.ToUniversalTime() && DateTime.Parse(scheduleArray[s].End.DateTime) > dateTime.ToUniversalTime()) { //Event needs to happen if (dateTime.Date == DateTime.Now.Date) { //today if (roomRecent.Available && roomRecent.FreeUntil == default(DateTime)) { roomRecent.FreeUntil = TimeZoneInfo.ConvertTimeFromUtc(DateTime.Parse(scheduleArray[s].Start.DateTime), cetTime); } } else { //not today roomRecent.FreeAt = TimeZoneInfo.ConvertTimeFromUtc(DateTime.Parse(scheduleArray[s].End.DateTime), cetTime); } } } } return(roomRecent); } catch (ServiceException e) { roomRecent.Available = false; roomRecent.ReservedBy = "Contact Hospitality Team"; for (int i = 0; i < roomRecent.DaySchedule.Length - 1; i++) { roomRecent.DaySchedule[i] = null; } return(roomRecent); } }
private async Task <MeetingTimeSuggestionsResult> FindMeetingSuggestions(DateTimeTimeZone start, DateTimeTimeZone end) { var timeZone = User.GetUserGraphTimeZone(); var attendees = new List <AttendeeBase>() { new AttendeeBase { Type = AttendeeType.Required, EmailAddress = new EmailAddress { Name = "seetharam konda", Address = "*****@*****.**" } } }; var locationConstraint = new LocationConstraint { IsRequired = false, SuggestLocation = false, Locations = new List <LocationConstraintItem>() { new LocationConstraintItem { ResolveAvailability = false, DisplayName = "Conf room Hood" } } }; var timeConstraint = new TimeConstraint { ActivityDomain = ActivityDomain.Work, TimeSlots = new List <TimeSlot>() { new TimeSlot { Start = start, End = end //Start = new DateTimeTimeZone //{ // DateTime = "2019-04-16T09:00:00", // TimeZone = "Pacific Standard Time" //}, //End = new DateTimeTimeZone //{ // DateTime = "2019-04-18T17:00:00", // TimeZone = "Pacific Standard Time" //} } } }; var isOrganizerOptional = false; var meetingDuration = new Duration("PT1H"); var returnSuggestionReasons = true; var minimumAttendeePercentage = (double)100; MeetingTimeSuggestionsResult x = await _graphClient.Me .FindMeetingTimes(attendees, locationConstraint, timeConstraint, meetingDuration, null, isOrganizerOptional, returnSuggestionReasons, minimumAttendeePercentage) .Request() .Header("Prefer", "outlook.timezone=\"India Standard Time\"") .PostAsync(); return(x); }
public static string ToLocalTime(DateTimeTimeZone value) { // Workaround for https://github.com/microsoft/microsoft-ui-xaml/issues/2407 return(value.ToDateTimeOffset().LocalDateTime.ToString("g")); }
// Create an event. // This snippet creates an hour-long event three days from now. private async Task <List <Event> > CreateEvent(string eventName, string eventContent, string locationDisplayName, List <string> attendeeEmail, DateTime startTime, DateTime endTime) { var items = new List <Event>(); var guid = Guid.NewGuid().ToString(); // List of attendees var attendees = new List <Attendee>(); if (attendeeEmail != null) { foreach (var email in attendeeEmail) { attendees.Add(new Attendee { EmailAddress = new EmailAddress { Address = email, }, Type = AttendeeType.Required, }); } } // Event body var body = new ItemBody { Content = eventContent, ContentType = BodyType.Text, }; // Event start and end time // Another example date format: `new DateTime(2017, 12, 1, 9, 30, 0).ToString("o")` var startTimeTimeZone = new DateTimeTimeZone { DateTime = startTime.ToString("o"), TimeZone = timeZoneInfo.Id, }; var endTimeTimeZone = new DateTimeTimeZone { DateTime = endTime.ToString("o"), TimeZone = timeZoneInfo.Id, }; // Event location var location = new Location { DisplayName = locationDisplayName, }; // Add the event. var createdEvent = await _graphClient.Me.Events.Request().AddAsync(new Event { Subject = eventName, Location = location, Attendees = attendees, Body = body, Start = startTimeTimeZone, End = endTimeTimeZone, }); if (createdEvent != null) { // Get event properties. items.Add(createdEvent); } return(items); }
// Create an event. // This snippet creates an hour-long event three days from now. public async Task <List <ResultsItem> > CreateEvent(GraphServiceClient graphClient) { List <ResultsItem> items = new List <ResultsItem>(); string guid = Guid.NewGuid().ToString(); // List of attendees List <Attendee> attendees = new List <Attendee>(); attendees.Add(new Attendee { EmailAddress = new EmailAddress { Address = "*****@*****.**" }, Type = AttendeeType.Required }); // Event body ItemBody body = new ItemBody { Content = Resource.Event + guid, ContentType = BodyType.Text }; // Event start and end time // Another example date format: `new DateTime(2017, 12, 1, 9, 30, 0).ToString("o")` DateTimeTimeZone startTime = new DateTimeTimeZone { DateTime = DateTime.Now.AddDays(3).ToString("o"), TimeZone = TimeZoneInfo.Local.Id }; DateTimeTimeZone endTime = new DateTimeTimeZone { DateTime = DateTime.Now.AddDays(3).AddHours(1).ToString("o"), TimeZone = TimeZoneInfo.Local.Id }; // Event location Location location = new Location { DisplayName = Resource.Location_DisplayName, }; // Add the event. Event createdEvent = await graphClient.Me.Events.Request().AddAsync(new Event { Subject = Resource.Event + guid.Substring(0, 8), Location = location, Attendees = attendees, Body = body, Start = startTime, End = endTime }); if (createdEvent != null) { // Get event properties. items.Add(new ResultsItem { Display = createdEvent.Subject, Id = createdEvent.Id, Properties = new Dictionary <string, object> { { Resource.Prop_Description, createdEvent.BodyPreview }, { Resource.Prop_Attendees, createdEvent.Attendees.Count() }, { Resource.Prop_Start, createdEvent.Start.DateTime }, { Resource.Prop_End, createdEvent.End.DateTime }, { Resource.Prop_Id, createdEvent.Id } } }); } return(items); }
/// <summary> /// The deserialization information for the current model /// </summary> public IDictionary <string, Action <IParseNode> > GetFieldDeserializers() { return(new Dictionary <string, Action <IParseNode> > { { "newReminderTime", n => { NewReminderTime = n.GetObjectValue <DateTimeTimeZone>(DateTimeTimeZone.CreateFromDiscriminatorValue); } }, }); }
// Creates a new event in the signed-in user's tenant. public static async Task <string> CreateEventAsync(DateTime startDateTime, DateTime endDateTime, string eventDescription, string eventLocation, string eventSubject, string eventAttendees, bool isAllDay) { string createdEventId = null; //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; //Event start and end time var eventStartTime = new DateTimeTimeZone(); eventStartTime.DateTime = startDateTime.ToString("o"); eventStartTime.TimeZone = "UTC"; var eventEndTime = new DateTimeTimeZone(); eventEndTime.TimeZone = "UTC"; eventEndTime.DateTime = endDateTime.ToString("o"); //Create an event to add to the events collection var location = new Location(); location.DisplayName = eventLocation; var newEvent = new Event(); newEvent.Subject = eventSubject; newEvent.Location = location; newEvent.Attendees = attendeesList; newEvent.Body = eventBody; newEvent.Start = eventStartTime; newEvent.End = eventEndTime; if (isAllDay) { newEvent.IsAllDay = true; } try { var graphClient = AuthenticationHelper.GetAuthenticatedClient(); var createdEvent = await graphClient.Me.Events.Request().AddAsync(newEvent); createdEventId = createdEvent.Id; } catch (ServiceException e) { Debug.WriteLine(SampleStrings.CreateMeetingFailedDebug + e.Error.Message); return(null); } return(createdEventId); }
public async Task <IActionResult> New([Bind("Subject,Attendees,Start,End,Body")] NewEvent newEvent) { var timeZone = User.GetUserGraphTimeZone(); //Getting the free/busy shedule time var schedules = new List <String>() { "*****@*****.**", "*****@*****.**" }; var Start = new DateTimeTimeZone { DateTime = newEvent.Start.ToString("o"), // Use the user's time zone TimeZone = timeZone }; var End = new DateTimeTimeZone { DateTime = newEvent.End.ToString("o"), // Use the user's time zone TimeZone = timeZone }; var availabilityViewInterval = 60; var data = await _graphClient.Me.Calendar .GetSchedule(schedules, End, Start, availabilityViewInterval) .Request() .Header("Prefer", $"outlook.timezone=\"{User.GetUserGraphTimeZone()}\"") .PostAsync(); string meetingStartTime = string.Empty; IEnumerable <ScheduleItem> items = data.CurrentPage[0].ScheduleItems; foreach (var item in items) { meetingStartTime = item.End.DateTime.ToString(); } if (String.IsNullOrEmpty(meetingStartTime)) { // string todayDate = // DateTime.Now.ToString("yyyy-MM-dd") + "T12:00:00.0000000"; meetingStartTime = newEvent.Start.ToString("o"); } DateTime objDateTime = DateTime.Parse(meetingStartTime); //Adding 1 hour to meeting Start Time string meetingEndTime = objDateTime.AddHours(1).ToString("yyyy-MM-dd'T'HH:mm:ss.0000000"); // Create a Graph event with the required fields var graphEvent = new Event { Subject = newEvent.Subject, Start = new DateTimeTimeZone { DateTime = meetingStartTime, // newEvent.Start.ToString("o"), // Use the user's time zone TimeZone = timeZone }, End = new DateTimeTimeZone { DateTime = meetingEndTime, //newEvent.End.ToString("o"), // Use the user's time zone TimeZone = timeZone } }; // Add body if present if (!string.IsNullOrEmpty(newEvent.Body)) { graphEvent.Body = new ItemBody { ContentType = BodyType.Text, Content = newEvent.Body }; } // Add attendees if present if (!string.IsNullOrEmpty(newEvent.Attendees)) { var attendees = newEvent.Attendees.Split(';', StringSplitOptions.RemoveEmptyEntries); if (attendees.Length > 0) { var attendeeList = new List <Attendee>(); foreach (var attendee in attendees) { attendeeList.Add(new Attendee { EmailAddress = new EmailAddress { Address = attendee }, Type = AttendeeType.Required }); } } } try { //Add the event await _graphClient.Me.Events .Request() .AddAsync(graphEvent); // Redirect to the calendar view with a success message return(RedirectToAction("Index").WithSuccess("Event created")); } catch (ServiceException ex) { // Redirect to the calendar view with an error message return(RedirectToAction("Index") .WithError("Error creating event", ex.Error.Message)); } }
/// <summary> /// Get user availability. /// </summary> /// <param name="exchangeServiceA">Exchange service of mailbox A.</param> /// <param name="exchangeServiceB">Exchange service of mailbox B.</param> /// <returns></returns> public static async Task GetUserAvailability(ExchangeService exchangeServiceA, ExchangeService exchangeServiceB) { string subject = Guid.NewGuid().ToString(); Event mailboxBEvent = new Event(exchangeServiceB); mailboxBEvent.Subject = subject; mailboxBEvent.Start = new DateTimeTimeZone() { DateTime = DateTimeHelper.GetFormattedDateTime(4).ToString("yyyy-MM-ddThh:mm:ss"), TimeZone = "UTC" }; mailboxBEvent.End = new DateTimeTimeZone() { DateTime = DateTimeHelper.GetFormattedDateTime(5).ToString("yyyy-MM-ddThh:mm:ss"), TimeZone = "UTC" }; await mailboxBEvent.SaveAsync(); // sleep a bit to ensure event is // saved. Thread.Sleep(1500); List <string> users = new List <string>(); users.Add(AppConfig.MailboxB); DateTimeTimeZone start = new DateTimeTimeZone() { DateTime = DateTimeHelper.GetFormattedDateTime().ToString("yyyy-MM-ddThh:mm:ss"), TimeZone = "UTC" }; DateTimeTimeZone end = new DateTimeTimeZone() { DateTime = DateTimeHelper.GetFormattedDateTime(72).ToString("yyyy-MM-ddThh:mm:ss"), TimeZone = "UTC" }; IList <ScheduleInformation> availability = await exchangeServiceA.GetUserAvailability( users, start, end, 60); Assert.AreEqual( 1, availability.Count); bool hasItem = false; foreach (ScheduleItem item in availability[0].ScheduleItems) { if (item.Subject == subject) { Assert.AreEqual( FreeBusyStatus.Busy, item.Status); hasItem = true; } } Assert.IsTrue(hasItem); await mailboxBEvent.DeleteAsync(); }
public async Task <Meeting> SetupMeetingEvent(string title, DateTime start, DateTime end, Meeting meeting, TeamChannel channel, IFormFile[] files, string[] attendees) { var attachments = new List <DriveItem>(); var meetingAttendees = new List <MeetingAttendee>(); var taskFiles = new List <TaskFile>(); if (files != null && files.Length > 0) { var users = new List <User>(); foreach (var attendee in attendees) { var graphUser = await _userService.GetUserByEmail(attendee); users.Add(graphUser); meetingAttendees.Add(new MeetingAttendee { Email = attendee, Name = graphUser.UserPrincipalName, MeetingId = meeting.Id }); } foreach (var file in files) { using (var fileStram = file.OpenReadStream()) { var uploadFile = await _fileService.UploadFile(meeting.TeamId, meeting.FolderId, file.FileName, fileStram); attachments.Add(uploadFile); await _planTaskService.CreatePreReadTaskForEachUser(channel.PlanId, meeting.BucketId, $"[Pre-reading] {file.FileName}", uploadFile, start, users.Select(i => i.Id).ToArray()); taskFiles.Add(new TaskFile { Location = uploadFile.WebUrl, Name = uploadFile.Name, MeetingId = meeting.Id }); } } } var joinUrl = await _communicationService.CreateOnlineMeeting(title, start, (await _userService.Me()).Id); var model = new EmailTemplateViewModel() { Agendas = meeting.Agendas.Select(a => a.Title), Attachments = attachments, JoinUrl = joinUrl }; var emailContent = await _viewRenderService.RenderToStringAsync("Templates/Invitation", model); var meetingEvent = await _calendarService.CreateEvent(title, DateTimeTimeZone.FromDateTime(start), DateTimeTimeZone.FromDateTime(end), emailContent, attendees.Select(mail => new Attendee { EmailAddress = new EmailAddress { Address = mail }, Type = AttendeeType.Required }), meeting, meeting.BucketId); meeting.EventId = meetingEvent.Id; await _meetingDBService.UpdateMeeting(meeting, meetingAttendees, taskFiles); return(meeting); }
public async Task <string> CreateEventAsync(DateTime startDateTime, DateTime endDateTime, string eventDescription, string eventLocation, string eventSubject, string[] eventAttendees, bool isAllDay, string aditionalProperty, PatternedRecurrence pattern) { string createdEventId = null; // Prepare the List of attendees // Prepare the recipient list List <Attendee> attendeesList = new List <Attendee>(); foreach (string attendee in eventAttendees) { attendeesList.Add(new Attendee { EmailAddress = new EmailAddress { Address = attendee.Trim() }, Type = AttendeeType.Required }); } // Event body var eventBody = new ItemBody(); eventBody.Content = string.Format("{0} - {1}{2}", eventDescription, AppSettings.CarpoolEventBody, aditionalProperty); eventBody.ContentType = BodyType.Text; // Event start and end time var eventStartTime = new DateTimeTimeZone(); eventStartTime.DateTime = startDateTime.ToString("o"); eventStartTime.TimeZone = TimeZoneInfo.Local.ToString(); var eventEndTime = new DateTimeTimeZone(); eventEndTime.TimeZone = TimeZoneInfo.Local.ToString(); eventEndTime.DateTime = endDateTime.ToString("o"); // Create an event to add to the events collection var location = new Location(); location.DisplayName = eventLocation; var newEvent = new Event(); newEvent.Subject = eventSubject; newEvent.Location = location; newEvent.Attendees = attendeesList; newEvent.Body = eventBody; newEvent.Start = eventStartTime; newEvent.End = eventEndTime; if (pattern != null) { newEvent.Recurrence = pattern; } if (isAllDay) { newEvent.IsAllDay = true; } var createdEvent = await GraphClient.Instance.Beta.Me.Events.Request().AddAsync(newEvent); createdEventId = createdEvent.Id; return(createdEventId); }
public async Task <IActionResult> CreateEvent( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "event")] HttpRequest req) { try { var graphClient = GetGraphClient(configuration.GraphV1); var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var input = JsonConvert.DeserializeObject <CreateEvent>(requestBody); var timeZone = input.TimeZone; var client = await GetGraphHttpClient(timeZone); var nearestUtc = DateTime.UtcNow.RoundToNearest(TimeSpan.FromMinutes(15)); var nearest = TimeZoneInfo.ConvertTimeFromUtc(nearestUtc, TimeZoneInfo.FindSystemTimeZoneById(timeZone)); var json = new { schedules = new List <string> { input.MeetingRoom.Mail }, startTime = new { dateTime = nearest.ToString("s"), timeZone }, endTime = new { dateTime = nearest.AddMinutes(30).ToString("s"), timeZone }, availabilityViewInterval = "30" }; var getSchedule = new StringContent(JsonConvert.SerializeObject(json), Encoding.UTF8, "application/json"); var response = await client.PostAsync($"{configuration.GraphBeta}/users/{input.MeetingRoom.Mail}/calendar/getSchedule", getSchedule); dynamic result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); if (result.value.First.availabilityView != "0") { return(new OkObjectResult(Result.Fail <Event>(ErrorMessages.RoomItWillBeBusySoonMessage))); } var startTime = new DateTimeTimeZone { DateTime = nearest.ToString("s"), TimeZone = timeZone }; var endTime = new DateTimeTimeZone { DateTime = nearest.AddMinutes(30).ToString("s"), TimeZone = timeZone }; var createdEvent = await graphClient.Users[input.MeetingRoom.Mail].Events.Request().AddAsync(new Microsoft.Graph.Event { Subject = $"Prenotazione Manuale {input.MeetingRoom.Name}", BodyPreview = $"Prenotazione Manuale {input.MeetingRoom.Name}", Start = startTime, End = endTime }); return(new OkObjectResult(Result.Ok(createdEvent.ToEvent(ChangeType.Created, input.MeetingRoom.Id)))); } catch (Exception e) { var error = $"{e.Message}\n\r{e.StackTrace}"; log.Error(error); return(new OkObjectResult(Result.Fail <Event>(error))); } }
static async Task GetMicrosoftGraphAccessTokeyAsync() { string[] scopes = new string[] { "user.read" }; IPublicClientApplication app; app = PublicClientApplicationBuilder.Create(clientId) .WithAuthority($"https://login.microsoftonline.com/{authority}") .Build(); AuthenticationResult result = null; try { #region 將所提供的密碼,使用 SecureString 以加密的方式儲存 // SecureString 代表應該將文字保密,例如於不再使用時將它從電腦記憶體刪除。 var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } #endregion // 使用使用者的帳號與密碼憑證,來獲取存取權杖 result = await app.AcquireTokenByUsernamePassword(scopes, account, securePassword) .ExecuteAsync(); } catch (MsalException ex) { Console.WriteLine(ex.Message); } Console.WriteLine(result.Account.Username); Console.WriteLine($"Access Token : {result.AccessToken}"); foreach (var item in result.Scopes) { Console.WriteLine($"Scope :{item}"); } var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => { requestMessage .Headers .Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken); return(Task.FromResult(0)); })); List <Option> requestOptions = new List <Option>(); // 指定事件開始與結束時間 DateTimeTimeZone startTime = new DateTimeTimeZone { DateTime = DateTime.Now.AddDays(3).ToString("o"), TimeZone = TimeZoneInfo.Local.Id }; DateTimeTimeZone endTime = new DateTimeTimeZone { DateTime = DateTime.Now.AddDays(5).AddHours(1).ToString("o"), TimeZone = TimeZoneInfo.Local.Id }; // 新增這個事件 Event createdEvent = await graphServiceClient.Me.Events.Request(requestOptions) .AddAsync(new Event { Subject = "自動同步行事曆測試" + Guid.NewGuid().ToString(), Start = startTime, End = endTime }); if (createdEvent != null) { Console.WriteLine($"新的行事曆事件已經建立成功"); } }
public async Task <AvailabilityResult> GetUserAvailabilityAsync(string userEmail, List <string> attendees, DateTime startTime, int availabilityViewInterval) { List <bool> availability = new List <bool>(); attendees.Add(userEmail); var schedules = attendees; var endTime = startTime.AddDays(1); var intervalStartTime = new DateTimeTimeZone { DateTime = startTime.ToString(), TimeZone = "UTC" }; var intervalEndTime = new DateTimeTimeZone { DateTime = endTime.ToString(), TimeZone = "UTC" }; ICalendarGetScheduleCollectionPage collectionPage = await _graphClient.Me.Calendar .GetSchedule(schedules, intervalEndTime, intervalStartTime, availabilityViewInterval) .Request() .PostAsync(); var result = new AvailabilityResult(); // set non-working time as 3 in availability view foreach (var collection in collectionPage) { var availabilityView = collection.AvailabilityView.ToCharArray(); if (collection.WorkingHours != null) { var workingTimeZone = TimeZoneInfo.FindSystemTimeZoneById(collection.WorkingHours.TimeZone.Name); var startTimeInWorkTimeZone = TimeConverter.ConvertUtcToUserTime(startTime, workingTimeZone); var workingStartTimeTimeOfDay = collection.WorkingHours.StartTime; var workingStartTime = new DateTime( startTimeInWorkTimeZone.Year, startTimeInWorkTimeZone.Month, startTimeInWorkTimeZone.Day, workingStartTimeTimeOfDay.Hour, workingStartTimeTimeOfDay.Minute, workingStartTimeTimeOfDay.Second); var workingEndTimeTimeOfDay = collection.WorkingHours.EndTime; var workingEndTime = new DateTime( startTimeInWorkTimeZone.Year, startTimeInWorkTimeZone.Month, startTimeInWorkTimeZone.Day, workingEndTimeTimeOfDay.Hour, workingEndTimeTimeOfDay.Minute, workingEndTimeTimeOfDay.Second); var workDays = collection.WorkingHours.DaysOfWeek.Select(li => (int)li); for (int i = 0; i < availabilityView.Length; i++) { if (availabilityView[i] == '0') { var availabilityViewStartTime = startTime.AddMinutes(i * CalendarCommonUtil.AvailabilityViewInterval); availabilityViewStartTime = TimeConverter.ConvertUtcToUserTime(availabilityViewStartTime, workingTimeZone); if (!workDays.Contains((int)availabilityViewStartTime.DayOfWeek)) { availabilityView[i] = '3'; continue; } var availabilityViewEndTime = availabilityViewStartTime.AddMinutes(CalendarCommonUtil.AvailabilityViewInterval); if (!((availabilityViewStartTime.TimeOfDay >= workingStartTime.TimeOfDay && availabilityViewStartTime.TimeOfDay < workingEndTime.TimeOfDay) || (availabilityViewEndTime.TimeOfDay > workingStartTime.TimeOfDay && availabilityViewEndTime.TimeOfDay <= workingEndTime.TimeOfDay))) { availabilityView[i] = '3'; } } } } result.AvailabilityViewList.Add(new string(availabilityView)); } result.MySchedule.AddRange(collectionPage.Last().ScheduleItems.Select(li => new EventModel(EventSource.Microsoft) { Title = li.Subject, StartTime = DateTime.Parse(li.Start.DateTime + "Z").ToUniversalTime(), EndTime = DateTime.Parse(li.End.DateTime + "Z").ToUniversalTime(), Location = li.Location })); return(result); }
private async void CreateEventButton_Click(Object sender, RoutedEventArgs e) { //List of attendees var attendees = new List <Attendee>(); var attendee = new Attendee(); var emailAddress = new EmailAddress() { Address = "*****@*****.**" }; attendee.EmailAddress = emailAddress; attendee.Type = AttendeeType.Required; attendees.Add(attendee); //Event body var eventBody = new ItemBody() { Content = "Status updates, blocking issues, and next steps", ContentType = BodyType.Text }; var location = new Location() { DisplayName = "Big conf room" }; //Event start and end time DateTime eventDay = DateTime.Today.AddDays(1); var eventStartTime = new DateTimeTimeZone() { DateTime = new DateTime(eventDay.Year, eventDay.Month, eventDay.Day, 9, 0, 0).ToString("o"), TimeZone = "Pacific Standard Time" }; var eventEndTime = new DateTimeTimeZone() { DateTime = new DateTime(eventDay.Year, eventDay.Month, eventDay.Day, 10, 0, 0).ToString("o"), TimeZone = "Pacific Standard Time" }; //Create an event to add to the events collection var newEvent = new Event() { Subject = "Weekly sync", Location = location, Attendees = attendees, Body = eventBody, Start = eventStartTime, End = eventEndTime }; try { await graphClient.Me.Events.Request().AddAsync(newEvent); } catch (ServiceException ex) { EventCountTextBlock.Text = $"We could not create this event: {ex.Error.Message}"; } }