Пример #1
0
        public List <Events> GetEvents()
        {
            var mailbox = "*****@*****.**";

            service.Credentials     = new WebCredentials("*****@*****.**", "Sommar23", "cybercom.com");
            service.EnableScpLookup = false;
            //service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback);
            service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");


            List <AttendeeInfo> attendees = new List <AttendeeInfo>();

            attendees.Add(new AttendeeInfo(mailbox, MeetingAttendeeType.Required, false));
            //service.TraceEnabled = true;
            GetUserAvailabilityResults result = service.GetUserAvailability(attendees, new TimeWindow(DateTime.Now, DateTime.Now.AddDays(1)), AvailabilityData.FreeBusy);

            List <Events> model = new List <Events>();

            foreach (var a in result.AttendeesAvailability)
            {
                foreach (var b in a.CalendarEvents)
                {
                    Events events = new Events();
                    events.EventStart = b.StartTime;
                    events.EventEnd   = b.EndTime;


                    model.Add(events);
                }
            }

            return(model);
        }
Пример #2
0
        //gavdcodeend 03

        //gavdcodebegin 04
        private static void FindAppointmentsByUser(ExchangeService ExService)
        {
            List <AttendeeInfo> accountsToScan = new List <AttendeeInfo>
            {
                new AttendeeInfo()
                {
                    SmtpAddress  = "*****@*****.**",
                    AttendeeType = MeetingAttendeeType.Organizer
                }
            };

            AvailabilityOptions myOptions = new AvailabilityOptions
            {
                MeetingDuration       = 30,
                RequestedFreeBusyView = FreeBusyViewType.FreeBusy
            };

            GetUserAvailabilityResults scanResults = ExService.GetUserAvailability(
                accountsToScan,
                new TimeWindow(DateTime.Now, DateTime.Now.AddDays(1)),
                AvailabilityData.FreeBusy,
                myOptions);

            foreach (AttendeeAvailability accountAvailability in
                     scanResults.AttendeesAvailability)
            {
                foreach (CalendarEvent oneCalendarEvent in
                         accountAvailability.CalendarEvents)
                {
                    Console.WriteLine("Status: " + oneCalendarEvent.FreeBusyStatus);
                    Console.WriteLine("Start time: " + oneCalendarEvent.StartTime);
                    Console.WriteLine("End time: " + oneCalendarEvent.EndTime);
                }
            }
        }
Пример #3
0
        private void AddAvailabilityInfoToRooms(List <Room> rooms, DateTime?dateTime = null)
        {
            if (dateTime == null)
            {
                dateTime = DateTime.Now;
            }

            var attendees = rooms.Select(room => new AttendeeInfo(room.Email)).ToList();
            GetUserAvailabilityResults availabilityResults = ReceiveRoomAvailabilityInfo(attendees, dateTime);

            var i = 0;

            foreach (var attendeeAvailability in availabilityResults.AttendeesAvailability)
            {
                if (attendeeAvailability.ErrorCode != ServiceError.NoError)
                {
                    rooms[i].Error = true;
                    Logger.Logger.Error("Room " + rooms[i].Email + " availability contains error: " + attendeeAvailability.ErrorCode.ToString() + " " + attendeeAvailability.ErrorMessage);
                }
                else
                {
                    foreach (var calendarEvent in attendeeAvailability.CalendarEvents)
                    {
                        var booking = CreateBooking(calendarEvent);
                        rooms[i].BookedTimes.Add(booking);
                    }
                }

                i++;
            }
        }
Пример #4
0
        private void btnGetAvailability_Click(object sender, RoutedEventArgs e)
        {
            List <string> attendees = new List <string>();

            if (!string.IsNullOrWhiteSpace(txtAttendee1.Text))
            {
                attendees.Add(txtAttendee1.Text);
            }

            if (!string.IsNullOrWhiteSpace(txtAttendee2.Text))
            {
                attendees.Add(txtAttendee2.Text);
            }

            if (attendees.Count == 0)
            {
                MessageBox.Show("You must add at least one attendee to proceed.");
                return;
            }

            GetUserAvailabilityResults results = _context.GetAvailability(txtEmailAddress.Text, attendees, 30, 2);

            foreach (Suggestion suggestion in results.Suggestions)
            {
                foreach (TimeSuggestion time in suggestion.TimeSuggestions)
                {
                    lstSuggestions.Items.Add(time);
                }
            }
        }
Пример #5
0
        private bool IsValidOutlookLogin(Page _Page, string sEmailID, string sEmailPass)
        {
            bool bRet = false;

            try
            {
                ExchangeService     service   = GetServiceEx(sEmailID, sEmailPass);
                List <AttendeeInfo> attendees = new List <AttendeeInfo>();
                attendees.Add(new AttendeeInfo(sEmailID));

                GetUserAvailabilityResults results = service.GetUserAvailability(attendees,
                                                                                 new TimeWindow(DateTime.Now, DateTime.Now.AddHours(24)), AvailabilityData.FreeBusy);

                AttendeeAvailability myAvailablity = results.AttendeesAvailability.FirstOrDefault();
                if (myAvailablity != null)
                {
                    Console.WriteLine(String.Format("FREE", myAvailablity.CalendarEvents.Count));
                }
                return(true);
            }
            catch (Exception ex)
            {
                var w32ex = ex as Win32Exception;
                uh.ShowHTMLMessage(_Page, ErrorNumber.SetType("00", errorType.LoginError), ex.Message);
                bRet = false;
            }
            return(bRet);
        }
Пример #6
0
        public IHttpActionResult Availability(AvailabilityRequest request)
        {
            List <AttendeeInfo> attendees = new List <AttendeeInfo>();

            foreach (var user in request.Users)
            {
                attendees.Add(new AttendeeInfo()
                {
                    SmtpAddress  = user,
                    AttendeeType = MeetingAttendeeType.Required
                });
            }

            // Specify availability options.
            AvailabilityOptions myOptions = new AvailabilityOptions();

            myOptions.MeetingDuration       = request.DurationMinutes;
            myOptions.RequestedFreeBusyView = FreeBusyViewType.FreeBusy;

            // Return a set of free/busy times.
            var service = ExchangeServer.Open();

            var startTime = DateTime.Parse(request.Start);
            var endTime   = DateTime.Parse(request.End);
            GetUserAvailabilityResults freeBusyResults = service.GetUserAvailability(attendees,
                                                                                     new TimeWindow(startTime, endTime),
                                                                                     AvailabilityData.FreeBusy,
                                                                                     myOptions);

            var response = new AvailabilityResponse
            {
                AvailabilityResult = new List <AvailabilityUser>()
            };


            foreach (AttendeeAvailability availability in freeBusyResults.AttendeesAvailability)
            {
                var user  = new AvailabilityUser();
                var avail = new List <TimeBlock>();

                foreach (CalendarEvent calendarItem in availability.CalendarEvents)
                {
                    var block = new TimeBlock
                    {
                        Start      = calendarItem.StartTime,
                        End        = calendarItem.EndTime,
                        StatusEnum = calendarItem.FreeBusyStatus,
                        Status     = calendarItem.FreeBusyStatus.ToString()
                    };

                    avail.Add(block);
                }
                user.Availability = avail;
                response.AvailabilityResult.Add(user);
            }

            return(Ok(response));
        }
        public string GetSuggestedMeetingTimesAndFreeBusyInfo(string RoomAdress, string Start, string End, int meetingDuration)
        {
            // Create a collection of attendees(only room)
            List <AttendeeInfo> attendees = new List <AttendeeInfo>();

            attendees.Add(new AttendeeInfo()
            {
                SmtpAddress  = RoomAdress,
                AttendeeType = MeetingAttendeeType.Room
            });

            // Specify options to request free/busy information and suggested meeting times.
            AvailabilityOptions availabilityOptions = new AvailabilityOptions();

            availabilityOptions.GoodSuggestionThreshold = 49;
            availabilityOptions.MaximumNonWorkHoursSuggestionsPerDay = 0;
            availabilityOptions.MaximumSuggestionsPerDay             = 5;
            availabilityOptions.MeetingDuration           = meetingDuration;
            availabilityOptions.MinimumSuggestionQuality  = SuggestionQuality.Good;
            availabilityOptions.DetailedSuggestionsWindow = new TimeWindow(Convert.ToDateTime(Start), Convert.ToDateTime(End));
            availabilityOptions.RequestedFreeBusyView     = FreeBusyViewType.FreeBusy;

            //Return free-busy information and a set of suggested meeting times.
            GetUserAvailabilityResults results = serviceExchange.GetUserAvailability(attendees,
                                                                                     availabilityOptions.DetailedSuggestionsWindow,
                                                                                     AvailabilityData.FreeBusyAndSuggestions,
                                                                                     availabilityOptions);
            //Display suggested meeting times.
            ReservationRoomInfo roomInfo = new ReservationRoomInfo();

            roomInfo.RoomName = attendees[0].SmtpAddress;

            foreach (Suggestion suggestion in results.Suggestions)
            {
                foreach (TimeSuggestion timeSuggestion in suggestion.TimeSuggestions)
                {
                    roomInfo.ListOfSuggestedMeetingTime.Add(timeSuggestion.MeetingTime.AddHours(3).ToShortTimeString() + "," +
                                                            timeSuggestion.MeetingTime.AddHours(3).Add(TimeSpan.FromMinutes(availabilityOptions.MeetingDuration)).ToShortTimeString());
                }
            }

            int i = 0;

            //Display free-busy times.
            foreach (AttendeeAvailability availability in results.AttendeesAvailability)
            {
                foreach (CalendarEvent calEvent in availability.CalendarEvents)
                {
                    roomInfo.ListFreeBusyTimes.Add(calEvent.StartTime.AddHours(3).ToString() + "," +
                                                   calEvent.EndTime.AddHours(3).ToString());
                }
                i++;
            }
            return(JsonConvert.SerializeObject(roomInfo, Formatting.Indented));
        }
Пример #8
0
        /// <summary>
        /// Get the availability details of the accounts
        /// </summary>
        static void GetAvailabilityDetails(ExchangeService service, String startDate,
                                           String endDate, params String[] emailAddresses)
        {
            // If the date is invaild, we will set today as the start date.
            DateTime startMeetingDate;

            startMeetingDate =
                DateTime.TryParse(startDate, out startMeetingDate) ? startMeetingDate : DateTime.Now;
            // If the date is invaild, we will set two days after the start date as the end date.
            DateTime endMeetingDate;

            endMeetingDate =
                DateTime.TryParse(endDate, out endMeetingDate) && endMeetingDate >= startMeetingDate ?
                endMeetingDate : startMeetingDate.AddDays(2);

            List <AttendeeInfo> attendees = new List <AttendeeInfo>();

            foreach (String emailAddress in emailAddresses)
            {
                AttendeeInfo attendee = new AttendeeInfo(emailAddress);
                attendees.Add(attendee);
            }

            TimeWindow          timeWindow          = new TimeWindow(startMeetingDate, endMeetingDate);
            AvailabilityOptions availabilityOptions = new AvailabilityOptions();

            availabilityOptions.MeetingDuration = 60;

            GetUserAvailabilityResults userAvailabilityResults = service.GetUserAvailability(attendees,
                                                                                             timeWindow, AvailabilityData.FreeBusyAndSuggestions, availabilityOptions);

            Console.WriteLine("{0,-15}{1,-21}{2,-11}{3,-14}{4,-10}{5,-9}", "FreeBusyStatus",
                              "StartTime", "EndTime", "Subject", "Location", "IsMeeting");
            foreach (AttendeeAvailability userAvailabilityResult in
                     userAvailabilityResults.AttendeesAvailability)
            {
                if (userAvailabilityResult.ErrorCode.CompareTo(ServiceError.NoError) == 0)
                {
                    foreach (CalendarEvent calendarEvent in userAvailabilityResult.CalendarEvents)
                    {
                        Console.WriteLine("{0,-15}{1,-21}{2,-11}{3,-14}{4,-10}{5,-9}",
                                          calendarEvent.FreeBusyStatus,
                                          calendarEvent.StartTime.ToShortDateString() + " " +
                                          calendarEvent.StartTime.ToShortTimeString(),
                                          calendarEvent.EndTime.ToShortTimeString(),
                                          calendarEvent.Details.Subject,
                                          calendarEvent.Details.Location,
                                          calendarEvent.Details.IsMeeting);
                    }
                }
            }
        }
Пример #9
0
        private static void GetSuggestedMeetingTimes(ExchangeService service)
        {
            // Create a list of attendees.
            List <AttendeeInfo> attendees = new List <AttendeeInfo>();

            attendees.Add(new AttendeeInfo()
            {
                // Change [email protected] to your email address.
                SmtpAddress  = UserDataFromConsole.GetUserData().EmailAddress,
                AttendeeType = MeetingAttendeeType.Organizer
            });

            attendees.Add(new AttendeeInfo()
            {
                // Change [email protected] to your email address.
                SmtpAddress  = "*****@*****.**",
                AttendeeType = MeetingAttendeeType.Required
            });

            // Specify suggested meeting time options.
            AvailabilityOptions meetingOptions = new AvailabilityOptions();

            meetingOptions.MeetingDuration = 60;
            meetingOptions.MaximumNonWorkHoursSuggestionsPerDay = 0;
            meetingOptions.GoodSuggestionThreshold   = 49;
            meetingOptions.MinimumSuggestionQuality  = SuggestionQuality.Good;
            meetingOptions.DetailedSuggestionsWindow = new TimeWindow(DateTime.Now.AddDays(4), DateTime.Now.AddDays(5));

            // Return a set of of suggested meeting times.
            GetUserAvailabilityResults results = service.GetUserAvailability(attendees,
                                                                             new TimeWindow(DateTime.Now, DateTime.Now.AddDays(2)),
                                                                             AvailabilityData.Suggestions,
                                                                             meetingOptions);

            // Display available meeting times.
            Console.WriteLine("Availability for {0} and {1}", attendees[0].SmtpAddress, attendees[1].SmtpAddress);
            Console.WriteLine();

            foreach (Suggestion suggestion in results.Suggestions)
            {
                Console.WriteLine(suggestion.Date);
                Console.WriteLine();
                foreach (TimeSuggestion timeSuggestion in suggestion.TimeSuggestions)
                {
                    Console.WriteLine("Suggested meeting time:" + timeSuggestion.MeetingTime);
                    Console.WriteLine();
                }
            }
        }
Пример #10
0
    public List <string> GetSuggestedMeetingTimes(ExchangeService service, string room, int duration,
                                                  DateTime start, DateTime end)
    {
        // Create a list of attendees.
        List <AttendeeInfo> attendees = new List <AttendeeInfo>();

        attendees.Add(new AttendeeInfo()
        {
            SmtpAddress  = room,
            AttendeeType = MeetingAttendeeType.Organizer
        });

        // Specify suggested meeting time options.
        AvailabilityOptions myOptions = new AvailabilityOptions();

        myOptions.MeetingDuration = duration;
        myOptions.MaximumNonWorkHoursSuggestionsPerDay = 0;
        myOptions.GoodSuggestionThreshold   = 10;
        myOptions.MaximumSuggestionsPerDay  = 40;
        myOptions.MinimumSuggestionQuality  = SuggestionQuality.Good;
        myOptions.DetailedSuggestionsWindow = new TimeWindow(start, end);

        // Return a set of suggested meeting times.
        GetUserAvailabilityResults results = service.GetUserAvailability(attendees,
                                                                         new TimeWindow(start, end),
                                                                         AvailabilityData.Suggestions,
                                                                         myOptions);

        // Display available meeting times.
        Console.WriteLine("Availability for {0}", attendees[0].SmtpAddress);
        Console.WriteLine();

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

        foreach (Suggestion suggestion in results.Suggestions)
        {
            Console.WriteLine(suggestion.Date);
            Console.WriteLine();
            foreach (TimeSuggestion timeSuggestion in suggestion.TimeSuggestions)
            {
                Console.WriteLine("Suggested meeting time:" + timeSuggestion.MeetingTime);
                times.Add(timeSuggestion.MeetingTime.ToString("HH:mm"));
                Console.WriteLine();
            }
        }

        return(times);
    }
Пример #11
0
        private static void GetUserFreeBusy(ExchangeService service)
        {
            // Create a list of attendees
            List <AttendeeInfo> attendees = new List <AttendeeInfo>();

            attendees.Add(new AttendeeInfo()
            {
                // Use the email address supplied from the console for the organizer's email address
                SmtpAddress  = UserDataFromConsole.GetUserData().EmailAddress,
                AttendeeType = MeetingAttendeeType.Organizer
            });

            attendees.Add(new AttendeeInfo()
            {
                // Change [email protected] to the email address of your prospective attendee
                SmtpAddress  = "*****@*****.**",
                AttendeeType = MeetingAttendeeType.Required
            });

            // Specify availability options
            AvailabilityOptions availabilityOptions = new AvailabilityOptions();

            availabilityOptions.MeetingDuration       = 30;
            availabilityOptions.RequestedFreeBusyView = FreeBusyViewType.FreeBusy;

            // Return a set of of free/busy times
            GetUserAvailabilityResults freeBusyResults = service.GetUserAvailability(attendees,
                                                                                     new TimeWindow(DateTime.Now, DateTime.Now.AddDays(1)),
                                                                                     AvailabilityData.FreeBusy,
                                                                                     availabilityOptions);

            // Display available meeting times
            Console.WriteLine("Availability for {0} and {1}", attendees[0].SmtpAddress, attendees[1].SmtpAddress);
            Console.WriteLine();

            foreach (AttendeeAvailability availability in freeBusyResults.AttendeesAvailability)
            {
                Console.WriteLine(availability.Result);
                Console.WriteLine();
                foreach (CalendarEvent calendarItem in availability.CalendarEvents)
                {
                    Console.WriteLine("Free/busy status: " + calendarItem.FreeBusyStatus);
                    Console.WriteLine("Start time: " + calendarItem.StartTime);
                    Console.WriteLine("End time: " + calendarItem.EndTime);
                    Console.WriteLine();
                }
            }
        }
Пример #12
0
        /** Tries to receive availability data (bookings) for all rooms. It is possible that a room sometimes returns an error.
         *  In this case the method waits a few seconds and tries again. If unable to receive successful data after
         *  too many tries, returns the data it got.*/
        private GetUserAvailabilityResults ReceiveRoomAvailabilityInfo(List <AttendeeInfo> attendees, DateTime?dateTime)
        {
            GetUserAvailabilityResults availabilityResults = null;
            var tryToReceiveResults = true;
            var maxTries            = 3;
            var currentAttempt      = 0;

            while (tryToReceiveResults)
            {
                currentAttempt++;

                availabilityResults = _exchangeService.GetUserAvailability(
                    attendees,
                    new TimeWindow(dateTime.Value,
                                   dateTime.Value.AddDays(1)),
                    AvailabilityData.FreeBusy);

                var allResultsOk = true;
                foreach (var attendeeAvailability in availabilityResults.AttendeesAvailability)
                {
                    if (attendeeAvailability.ErrorCode != ServiceError.NoError)
                    {
                        allResultsOk = false;
                    }
                }

                if (allResultsOk == true)
                {
                    Logger.Logger.Info("Room availability info received successfully.");
                    tryToReceiveResults = false;
                }
                else
                {
                    if (currentAttempt < maxTries)
                    {
                        Logger.Logger.Error("Room availability info returned an error. Trying again...");
                        Thread.Sleep(5000);
                    }
                    else
                    {
                        Logger.Logger.Error("Room availability info returned an error too many times. Using the data we got.");
                        tryToReceiveResults = false;
                    }
                }
            }

            return(availabilityResults);
        }
    object ParseResponse(EwsServiceXmlReader reader)
    {
        GetUserAvailabilityResults serviceResponse = new GetUserAvailabilityResults();

        if (this.IsFreeBusyViewRequested)
        {
            serviceResponse.AttendeesAvailability = new ServiceResponseCollection <AttendeeAvailability>();

            reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.FreeBusyResponseArray);

            do
            {
                reader.Read();

                if (reader.IsStartElement(XmlNamespace.Messages, XmlElementNames.FreeBusyResponse))
                {
                    AttendeeAvailability freeBusyResponse = new AttendeeAvailability();

                    freeBusyResponse.LoadFromXml(reader, XmlElementNames.ResponseMessage);

                    if (freeBusyResponse.ErrorCode == ServiceError.NoError)
                    {
                        freeBusyResponse.LoadFreeBusyViewFromXml(reader, this.Options.RequestedFreeBusyView);
                    }

                    serviceResponse.AttendeesAvailability.Add(freeBusyResponse);
                }
            }while (!reader.IsEndElement(XmlNamespace.Messages, XmlElementNames.FreeBusyResponseArray));
        }

        if (this.IsSuggestionsViewRequested)
        {
            serviceResponse.SuggestionsResponse = new SuggestionsResponse();

            reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.SuggestionsResponse);

            serviceResponse.SuggestionsResponse.LoadFromXml(reader, XmlElementNames.ResponseMessage);

            if (serviceResponse.SuggestionsResponse.ErrorCode == ServiceError.NoError)
            {
                serviceResponse.SuggestionsResponse.LoadSuggestedDaysFromXml(reader);
            }

            reader.ReadEndElement(XmlNamespace.Messages, XmlElementNames.SuggestionsResponse);
        }

        return(serviceResponse);
    }
        public GetUserAvailabilityResults GetAvailability
            (string organizer,
            List <string> requiredAttendees,
            int meetingDuration,
            int timeWindowDays)
        {
            List <AttendeeInfo> attendees = new List <AttendeeInfo>();

            //add organizer
            attendees.Add(new AttendeeInfo()
            {
                SmtpAddress  = organizer,
                AttendeeType = MeetingAttendeeType.Organizer
            });

            //add required attendees
            foreach (string attendee in requiredAttendees)
            {
                attendees.Add(new AttendeeInfo()
                {
                    SmtpAddress  = attendee,
                    AttendeeType = MeetingAttendeeType.Required
                });
            }

            //setup options
            AvailabilityOptions options = new AvailabilityOptions()
            {
                MeetingDuration = meetingDuration,
                MaximumNonWorkHoursSuggestionsPerDay = 4,
                MinimumSuggestionQuality             = SuggestionQuality.Good,
                RequestedFreeBusyView = FreeBusyViewType.FreeBusy
            };

            GetUserAvailabilityResults results = _service.GetUserAvailability
                                                     (attendees,
                                                     new TimeWindow(DateTime.Now, DateTime.Now.AddDays(timeWindowDays)),
                                                     AvailabilityData.FreeBusyAndSuggestions,
                                                     options);

            return(results);
        }
Пример #15
0
    public void GetUserFreeBusy(ExchangeService service, //List<AttendeeInfo> attendees,
                                int duration, DateTime start, DateTime end)
    {
        // Create a list of attendees.
        List <AttendeeInfo> attendees = new List <AttendeeInfo>();

        attendees.Add(new AttendeeInfo()
        {
            SmtpAddress  = "*****@*****.**",
            AttendeeType = MeetingAttendeeType.Organizer
        });

        // Specify availability options.
        AvailabilityOptions myOptions = new AvailabilityOptions();

        myOptions.MeetingDuration       = 30;
        myOptions.RequestedFreeBusyView = FreeBusyViewType.FreeBusy;

        // Return a set of free/busy times.
        GetUserAvailabilityResults freeBusyResults = service.GetUserAvailability(attendees,
                                                                                 new TimeWindow(start, end),
                                                                                 AvailabilityData.FreeBusy,
                                                                                 myOptions);

        // Display available meeting times.
        Console.WriteLine("Availability for {0}", attendees[0].SmtpAddress);
        Console.WriteLine();

        foreach (AttendeeAvailability availability in freeBusyResults.AttendeesAvailability)
        {
            Console.WriteLine(availability.Result);
            Console.WriteLine();
            foreach (CalendarEvent calendarItem in availability.CalendarEvents)
            {
                Console.WriteLine("Free/busy status: " + calendarItem.FreeBusyStatus);
                Console.WriteLine("Start time: " + calendarItem.StartTime);
                Console.WriteLine("End time: " + calendarItem.EndTime);
                Console.WriteLine();
            }
        }
    }
Пример #16
0
        private void GetRoomAppointments(ref Room room, DateTime start, DateTime end)
        {
            List <AttendeeInfo> attend = new List <AttendeeInfo>();

            attend.Clear();
            attend.Add(room.Address);

            AvailabilityOptions options = new AvailabilityOptions
            {
                MaximumSuggestionsPerDay = 48,
            };

            GetUserAvailabilityResults userAvailability = null;

            System.Threading.Tasks.Task tUserAvailability = System.Threading.Tasks.Task.Run(async() =>
            {
                userAvailability = await Service.GetUserAvailability(attend, new TimeWindow(start, end), AvailabilityData.FreeBusyAndSuggestions, options);
            });
            tUserAvailability.Wait();

            foreach (AttendeeAvailability attendeeAvailability in userAvailability.AttendeesAvailability)
            {
                if (attendeeAvailability.ErrorCode == ServiceError.NoError)
                {
                    foreach (CalendarEvent calendarEvent in attendeeAvailability.CalendarEvents)
                    {
                        Event singleEvent = new Event
                        {
                            Start   = calendarEvent.StartTime,
                            End     = calendarEvent.EndTime,
                            Subject = calendarEvent.Details?.Subject,
                            Id      = calendarEvent.Details?.StoreId
                        };
                        room.Events.Add(singleEvent);
                    }
                }
            }
        }
Пример #17
0
        //Event handler for load free busy button click
        public static void loadFreeBusy(object sender, EventArgs e)
        {
            List <AttendeeInfo> attendees = new List <AttendeeInfo>();

            for (int i = 0; i < RoomSelectionGui.buttons.Count; i++)
            {
                RoomSelectionGui.buttons[i].BackColor = System.Drawing.Color.LightGoldenrodYellow;
                attendees.Add(RoomSelectionGui.buttons[i].Name);
            }

            ExchangeService exchangeService = new ExchangeService();

            exchangeService.UseDefaultCredentials = true;
            exchangeService.Url = new Uri("https://email.netapp.com/EWS/Exchange.asmx");
            AvailabilityOptions myOptions = new AvailabilityOptions();

            myOptions.MeetingDuration       = appointmentItem.Duration;
            myOptions.RequestedFreeBusyView = FreeBusyViewType.Detailed;
            GetUserAvailabilityResults freeBusyResults = exchangeService.GetUserAvailability(attendees, new TimeWindow(appointmentItem.Start.Date, appointmentItem.Start.Date.AddDays(1)), AvailabilityData.FreeBusy, myOptions);


            //Check for each of the attendees availability
            for (int attendeeIndex = 0; attendeeIndex < freeBusyResults.AttendeesAvailability.Count; attendeeIndex++)
            {
                //Calendar events contains the count and the information for each attendee meetings
                foreach (CalendarEvent calenderItem in freeBusyResults.AttendeesAvailability[attendeeIndex].CalendarEvents)
                {
                    //if the attendee has a 'Busy' status at that time slot, mark red
                    //appointmentItem.Body += "Debug:\n"+"appointmentItem.Start:=" + appointmentItem.Start + "\n" + "calenderItem.StartTime:=" + calenderItem.StartTime + "\n" + "appointmentItem.End:=" + appointmentItem.End + "\n" + "calenderItem.EndTime:=" + calenderItem.EndTime + "\n" + "DateTime.Compare(appointmentItem.Start, calenderItem.StartTime) should be <=0:="+ DateTime.Compare(appointmentItem.Start, calenderItem.StartTime) + "\n" + "DateTime.Compare(appointmentItem.End, calenderItem.EndTime) should be <=0:=" + DateTime.Compare(appointmentItem.End, calenderItem.EndTime)+"\n";
                    if ((DateTime.Compare(appointmentItem.Start, calenderItem.StartTime) <= 0 && DateTime.Compare(appointmentItem.End, calenderItem.EndTime) >= 0) || (DateTime.Compare(appointmentItem.Start, calenderItem.StartTime) >= 0 && DateTime.Compare(appointmentItem.End, calenderItem.EndTime) <= 0))
                    {
                        //appointmentItem.Body += "Match!";
                        RoomSelectionGui.buttons[attendeeIndex].BackColor = System.Drawing.Color.OrangeRed;
                    }
                }
            }
        }
Пример #18
0
        private static void DetermineRoomAvailability(List <Room> rooms,
                                                      GetUserAvailabilityResults result, DateTime startDate,
                                                      DateTime endDate
                                                      )
        {
            //DateTime utcTime = DateTime.Now.ToUniversalTime();
            DateTime utcTime = startDate.ToUniversalTime();

            if (rooms.Count != result.AttendeesAvailability.Count)
            {
                throw new Exception($"The number of known rooms ({rooms.Count}) did not match the number of availabilities ({result.AttendeesAvailability.Count}).");
            }

            for (int i = 0; i < rooms.Count; i++)
            {
                var availability = result.AttendeesAvailability[i];
                var room         = rooms[i];

                room.Available = !(from n in result.AttendeesAvailability[i].CalendarEvents
                                   where (n.StartTime <utcTime && n.EndTime> utcTime) ||
                                   (n.StartTime > utcTime && n.StartTime < endDate.ToUniversalTime())
                                   select n).Any();
            }
        }
Пример #19
0
        protected List <AgentDLInfo> GetListDetails(string toBeCheckedDL, TimeSpan toBeCheckedOffset, DateTime startDate, DateTime endDate)
        {
            List <AgentDLInfo> agentDLList = new List <AgentDLInfo>();

            try
            {
                EWSUtility    ewsUtility = new EWSUtility("SMBSPWEB", "]#Uun6~QqN7k@Z}c", "REDMOND", "*****@*****.**");
                List <string> lstEmailID = (List <string>)ewsUtility.ExpandDistributionLists(toBeCheckedDL);
                // List<string> lstEmailID = new List<string>();
                // lstEmailID.Clear();
                //lstEmailID.Add("*****@*****.**");
                //lstEmailID.Add("*****@*****.**");
                //lstEmailID.Add("*****@*****.**");
                //lstEmailID.Add("v - [email protected]");
                //lstEmailID.Add("v - [email protected]");
                //lstEmailID.Add("v - [email protected]");
                //lstEmailID.Add("v - [email protected]");

                //lstEmailID.Add("*****@*****.**");
                //lstEmailID.Add("*****@*****.**");


                // Temporary fix : The below agent is causing some issue while fetching data from Exchange, The error is "The XML document ended unexpectedly."
                // The affected team are : MastOpt and CoachNA (since both DLs have the same list of agents)
                // lstEmailID.Remove("*****@*****.**"); //todo
                //--End temporary fix 16 Feb 2017

                foreach (string agentEmailID in lstEmailID)
                {
                    GetUserAvailabilityResults freeBusyResults = ewsUtility.Exchange.GetUserAvailability(
                        Enumerable.Repeat(new AttendeeInfo {
                        SmtpAddress = agentEmailID, AttendeeType = MeetingAttendeeType.Required
                    }, 1),
                        new TimeWindow(startDate, endDate), AvailabilityData.FreeBusy,
                        new AvailabilityOptions()
                    {
                        MeetingDuration = 30, RequestedFreeBusyView = FreeBusyViewType.FreeBusy
                    });

                    AgentDLInfo agentDLInfo = new AgentDLInfo();
                    agentDLInfo.DLName  = toBeCheckedDL;
                    agentDLInfo.EmailId = agentEmailID;

                    if (freeBusyResults.AttendeesAvailability.First().WorkingHours != null)
                    {
                        agentDLInfo.TimeZoneInfo       = freeBusyResults.AttendeesAvailability.First().WorkingHours.TimeZone;
                        agentDLInfo.AgentOffset        = agentDLInfo.TimeZoneInfo.BaseUtcOffset.ToString();
                        agentDLInfo.DLOffset           = toBeCheckedOffset.ToString();
                        agentDLInfo.IsBaseOffset       = agentDLInfo.TimeZoneInfo.BaseUtcOffset.Equals(toBeCheckedOffset);
                        agentDLInfo.WorkhoursStartTime = freeBusyResults.AttendeesAvailability.First().WorkingHours.StartTime.ToString();
                        agentDLInfo.WorkhoursEndTime   = freeBusyResults.AttendeesAvailability.First().WorkingHours.EndTime.ToString();
                    }
                    else
                    {
                        agentDLInfo.DLOffset     = toBeCheckedOffset.ToString();
                        agentDLInfo.AgentOffset  = "Unknown";
                        agentDLInfo.TimeZoneInfo = null;
                        agentDLInfo.IsBaseOffset = false;
                    }

                    agentDLList.Add(agentDLInfo);
                }

                return(agentDLList);
            }
            catch (Exception ex)
            {
                lblError.Text    = "Some Exception occurs due to invalid DL or due to some another issue.";
                lblError.Visible = true;
                return(agentDLList);
            }
        }
Пример #20
0
        public static List <Availability> GetCalendarInfo(string username)
        {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

            service.Credentials  = new WebCredentials("*****@*****.**", Settings.Password);
            service.TraceEnabled = true;
            service.TraceFlags   = TraceFlags.All;
            service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback);



            DateTime startDate = DateTime.Now;
            DateTime endDate   = startDate.AddDays(2);

            List <AttendeeInfo> attendees = new List <AttendeeInfo>();


            attendees.Add(new AttendeeInfo()
            {
                SmtpAddress  = username,
                AttendeeType = MeetingAttendeeType.Required
            });

            // Specify availability options.
            AvailabilityOptions myOptions = new AvailabilityOptions();

            myOptions.MeetingDuration       = 30;
            myOptions.RequestedFreeBusyView = FreeBusyViewType.FreeBusy;
            var list = new List <Availability>();

            try
            {
                // Return a set of free/busy times.
                GetUserAvailabilityResults freeBusyResults = service.GetUserAvailability(attendees,
                                                                                         new TimeWindow(DateTime.Now, DateTime.Now.AddDays(1)),
                                                                                         AvailabilityData.FreeBusy,
                                                                                         myOptions);
                // Display available meeting times.
                Console.WriteLine("Availability for {0}", attendees[0].SmtpAddress);
                Console.WriteLine();

                if (freeBusyResults.AttendeesAvailability.Count > 0)
                {
                    foreach (CalendarEvent calendarItem in freeBusyResults.AttendeesAvailability[0].CalendarEvents)
                    {
                        list.Add(new Availability()
                        {
                            StartDate = calendarItem.StartTime,
                            EndDate   = calendarItem.EndTime,
                            Status    = calendarItem.FreeBusyStatus.ToString()
                        });
                    }
                }

                return(list.OrderBy(o => o.StartDate).ToList());
            }
            catch (Exception ex)
            {
                return(list);
            }

            /*
             * // Initialize the calendar folder object with only the folder ID.
             * //CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
             * var folderIdFromCalendar = new FolderId(WellKnownFolderName.Calendar, username);
             *
             * CalendarFolder calendar = CalendarFolder.Bind(service, folderIdFromCalendar, new PropertySet());
             *
             * // Set the start and end time and number of appointments to retrieve.
             * CalendarView ccView = new CalendarView(startDate, endDate, NUM_APPTS);
             *
             * // Limit the properties returned to the appointment's subject, start time, and end time.
             * ccView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End);
             *
             * // Retrieve a collection of appointments by using the calendar view.
             * FindItemsResults<Appointment> appointments2 = calendar.FindAppointments(ccView);
             *
             * Console.WriteLine("\nThe first " + NUM_APPTS + " appointments on your calendar from " + startDate.Date.ToShortDateString() +
             *                " to " + endDate.Date.ToShortDateString() + " are: \n");
             *
             * foreach (Appointment a in appointments2)
             * {
             *  Console.Write("Subject: " + a.Subject.ToString() + " ");
             *  Console.Write("Start: " + a.Start.ToString() + " ");
             *  Console.Write("End: " + a.End.ToString());
             *  Console.WriteLine();
             * }
             */
        }
Пример #21
0
        static string GetCalItems(Options cmdline, string[] users, string serverUrl)
        {
            var service = new ExchangeService(ExchangeVersion.Exchange2016)
            {
                Credentials = new WebCredentials() // use default network credentials
            };

            service.TraceEnabled = cmdline.Tracing;
            service.TraceFlags   = TraceFlags.All;

            if (users.Length == 0)
            {
                throw new ApplicationException("List of users is empty");
            }

            if (cmdline.Verbose)
            {
                Console.WriteLine("Using '{0}' as server URL", serverUrl);
            }
            service.Url = new Uri(serverUrl);

            const int NUM_DAYS = 5;

            // Create a collection of attendees.
            List <AttendeeInfo> attendees = new List <AttendeeInfo>();

            foreach (var u in users)
            {
                attendees.Add(new AttendeeInfo()
                {
                    SmtpAddress  = u,
                    AttendeeType = MeetingAttendeeType.Required
                });
            }

            // Specify options to request free/busy information and suggested meeting times.
            AvailabilityOptions availabilityOptions = new AvailabilityOptions
            {
                GoodSuggestionThreshold = 49,
                MaximumNonWorkHoursSuggestionsPerDay = 0,
                MaximumSuggestionsPerDay             = 2,
                // Note that 60 minutes is the default value for MeetingDuration, but setting it explicitly for demonstration purposes.
                MeetingDuration           = 60,
                MinimumSuggestionQuality  = SuggestionQuality.Good,
                DetailedSuggestionsWindow = new TimeWindow(DateTime.Now.AddDays(0), DateTime.Now.AddDays(NUM_DAYS)),
                RequestedFreeBusyView     = FreeBusyViewType.Detailed
            };

            // Return free/busy information and a set of suggested meeting times.
            // This method results in a GetUserAvailabilityRequest call to EWS.
            GetUserAvailabilityResults results = service.GetUserAvailability(attendees,
                                                                             availabilityOptions.DetailedSuggestionsWindow,
                                                                             AvailabilityData.FreeBusyAndSuggestions,
                                                                             availabilityOptions);

            Data data = new Data
            {
                querytime         = DateTime.Now,
                appointments      = new Dictionary <string, System.Collections.ObjectModel.Collection <CalendarEvent> >(),
                freebusystatusmap = new Dictionary <int, string>()
                {
                    { 0, "Free" },             //     The time slot associated with the appointment appears as free.
                    { 1, "Tentative" },        //     The time slot associated with the appointment appears as tentative.
                    { 2, "Busy" },             //     The time slot associated with the appointment appears as busy.
                    { 3, "OOF" },              //     The time slot associated with the appointment appears as Out of Office.
                    { 4, "WorkingElsewhere" }, //     The time slot associated with the appointment appears as working else where.
                    { 5, "NoData" } //     No free/busy status is associated with the appointment.
                }
            };

            for (int i = 0; i < results.AttendeesAvailability.Count; i++)
            {
                data.appointments[users[i]] = results.AttendeesAvailability[i].CalendarEvents;
            }
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented);

            if (cmdline.Verbose)
            {
                Console.WriteLine(json);
            }
            return(json);
        }
Пример #22
0
        public static void GetRoom(ExchangeService service)
        {
            service.GetRoomLists();

            EmailAddress locationAddress = new EmailAddress();

            service.GetRooms(locationAddress);

            System.DateTime startTime = System.DateTime.Now;
            System.DateTime endTime   = System.DateTime.Now.AddHours(1);


            Appointment appointment = new Appointment(service)
            {
                Subject = "Created by ExchangeTest app",
                Body    = "Some body text....",
                Start   = startTime,
                End     = endTime
            };

            appointment.RequiredAttendees.Add("*****@*****.**");
            appointment.Resources.Add("*****@*****.**");
            appointment.Save(SendInvitationsMode.SendOnlyToAll);

            // https://stackoverflow.com/questions/4224451/exchange-web-services-create-appointment-with-resource-but-attendees-cannot-se
            // https://github.com/OfficeDev/ews-java-api/issues/528
            // https://stackoverflow.com/questions/35082377/how-to-get-truly-free-rooms-from-exchange-ews


            System.Collections.ObjectModel.Collection <EmailAddress> rooms = service.GetRooms(locationAddress);

            // all the meeting rooms at location
            //System.Collections.Generic.IEnumerable<AttendeeInfo> rooms2 = rooms.Select(i => new AttendeeInfo { SmtpAddress = i.Address, AttendeeType = MeetingAttendeeType.Room });
            System.Collections.Generic.List <AttendeeInfo> rooms2 = new System.Collections.Generic.List <AttendeeInfo>();
            foreach (EmailAddress thisRoom in rooms)
            {
                rooms2.Add(new AttendeeInfo()
                {
                    SmtpAddress = thisRoom.Address, AttendeeType = MeetingAttendeeType.Room
                });
            }


            TimeWindow timeframe = new TimeWindow(startTime, endTime);

            // Get all availabilites from all rooms at given locations
            GetUserAvailabilityResults availability = service.GetUserAvailability(rooms2, timeframe, AvailabilityData.FreeBusy);


            foreach (AttendeeAvailability a in availability.AttendeesAvailability)
            {
                // a.CalendarEvents[0].StartTime
                // a.CalendarEvents[0].EndTime

                // Here we always get all the free rooms
                // including the ones we booked earlier
                // UNTIL somebody clicks accept in Outlook and then it does not appear here!?
                // CalendarEvent busyRoomToRemove = a.CalendarEvents.ToList().Find(x => x.FreeBusyStatus == LegacyFreeBusyStatus.Busy);
                // a.CalendarEvents.Remove(busyRoomToRemove);
            }

            // http://blog.darrenparkinson.uk/2013/12/using-ews-managed-api-to-access-meeting_13.html
            // https://docs.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/hh532568(v%3Dexchg.80)
            // https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/distribution-groups-and-ews-in-exchange
            // https://www.linkedin.com/pulse/creating-meeting-using-ews-managed-api-sunil-chauhan

            // https://support.zoom.us/hc/en-us/articles/203847339-Setting-Up-Zoom-Rooms-with-Exchange-2013-2016


            // https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/calendars-and-ews-in-exchange
            Appointment meeting = new Appointment(service);

            // Set the properties on the meeting object to create the meeting.
            meeting.Subject  = "Team building exercise";
            meeting.Body     = "Let's learn to really work as a team and then have lunch!";
            meeting.Start    = System.DateTime.Now.AddDays(2);
            meeting.End      = meeting.Start.AddHours(2);
            meeting.Location = "Conference Room 12";
            meeting.RequiredAttendees.Add("*****@*****.**");
            meeting.RequiredAttendees.Add("*****@*****.**");
            meeting.OptionalAttendees.Add("*****@*****.**");
            meeting.ReminderMinutesBeforeStart = 60;
            // Send the meeting request
            meeting.Save(SendInvitationsMode.SendToAllAndSaveCopy);


            // Create and manage room mailboxes
            // https://technet.microsoft.com/en-us/library/jj215781(v=exchg.160).aspx
            // https://blogs.technet.microsoft.com/exchange/2007/12/13/how-to-access-multiple-resource-mailboxes-in-exchange-web-services-ews/
            // https://docs.microsoft.com/en-us/exchange/client-developer/management/create-exchange-management-shell-tools
        } // End Sub ListAllMails
Пример #23
0
        /// <summary>
        /// Obtem a disponibilidade de um usuário smtp
        /// </summary>
        /// <param name="smtp"></param>
        /// <returns></returns>
        public Status obterDisponibilidadeExchange(string smtp, string zoneId = "E. South America Standard Time")
        {
            // SE O SMTP NÃO ENVIAR O ENDEREÇO DO HOST "@XPTO.COM.BR", PREENCHE AUTOMATICAMENTE COM O DOMINIO DA CONTA CONFIGURADA
            if (!smtp.Contains("@"))
            {
                var config = new ConfiguracaoBS().obterConfiguracao();
                if (config != null)
                {
                    string host = config.EmailAddress.Split('@')[1];
                    smtp = smtp + '@' + host;
                }
            }
            // Instancia o objeto de retorno de status
            Status retorno = new Status();

            try
            {
                // Atribui a janela de tempo da Pesquisa
                // Precisamos de salas de reunião que já tenham iniciado seu cronômetro em 15 minutos
                // O prazo de 6 horas é necessário para cumprir especificação técnica do método.
                DateTime startTime = DateTime.Now.ToUniversalTime();

                var diferencaParaOutroDia = 24 - DateTime.Now.ToUniversalTime().Hour;

                var janelaDeTempo = new TimeWindow(startTime,
                                                   startTime.AddHours(diferencaParaOutroDia));

                var janelaDeSugestao = new TimeWindow(startTime,
                                                      startTime.AddHours(diferencaParaOutroDia));
                // Atribui os parametros de busca
                var options = new AvailabilityOptions
                {
                    MeetingDuration = 30
                    ,
                    RequestedFreeBusyView = FreeBusyViewType.Detailed
                    ,
                    MergedFreeBusyInterval = 5
                    ,
                    MaximumSuggestionsPerDay = 1
                    ,
                    GoodSuggestionThreshold = 25
                    ,
                    CurrentMeetingTime = startTime //DateTime.Now
                    ,
                    DetailedSuggestionsWindow = janelaDeSugestao
                    ,
                    MinimumSuggestionQuality = SuggestionQuality.Poor
                };

                // Para a consulta, é obrigatorio enviar uma lista de participantes da reuniao
                // Como a única informação que precisamos é a da Sala, enviamos apenas um elemento
                List <AttendeeInfo> listaUnicoElemento = new List <AttendeeInfo>();
                AttendeeInfo        UnicoElemento      = new AttendeeInfo(); // instancia o elemento unico para a lista obrigatória
                UnicoElemento.SmtpAddress = smtp;                            // preenche com o smtp da checagem
                listaUnicoElemento.Add(UnicoElemento);

                // INICIO - Efetua a busca no exchange com os parâmetros selecionados
                GetUserAvailabilityResults resultadoDisponibilidade = this.service.GetUserAvailability(listaUnicoElemento,
                                                                                                       janelaDeTempo,
                                                                                                       AvailabilityData.FreeBusyAndSuggestions,
                                                                                                       options);
                // FIM - busca Exchange

                // PRIMEIRA TENTATIVA DE OBTENCAO DA DISPONIBILIDADE - ATRAVÉS DO RESULTADO DA DISPONIBILIDADE

                foreach (AttendeeAvailability avail in resultadoDisponibilidade.AttendeesAvailability)
                {
                    string erro = string.Empty;
                    if (avail.Result == ServiceResult.Error)
                    {
                        erro = (avail.Result != null ? "RESULT = " + avail.Result.ToString() + " | " : "") +
                               (avail.ErrorCode != null ? "ErrorCode = " + avail.ErrorCode.ToString() + " | " : "") +
                               (avail.ErrorDetails != null ? "ErrorDetais = " + avail.ErrorDetails.ToString() + " | " : "") +
                               (avail.ErrorMessage != null ? "ErrorMessage = " + avail.ErrorMessage.ToString() + " | " : "") +
                               (avail.ErrorProperties.Count() > 0 ? "ErrorProperties = " + avail.ErrorProperties.ToString() : "");
                    }

                    var calendarios = avail.CalendarEvents.Where(x => x.StartTime <DateTime.Now.ToUniversalTime() &&
                                                                                   x.EndTime> DateTime.Now.ToUniversalTime()).ToList();

                    if (calendarios.Count() > 0)
                    {
                        foreach (CalendarEvent calItem in calendarios)
                        {
                            if (calItem.FreeBusyStatus == LegacyFreeBusyStatus.Busy ||
                                calItem.FreeBusyStatus == LegacyFreeBusyStatus.OOF ||
                                calItem.FreeBusyStatus == LegacyFreeBusyStatus.Tentative ||
                                calItem.FreeBusyStatus == LegacyFreeBusyStatus.WorkingElsewhere)
                            {
                                // Se a data de fim da reuniao já tiver passado, então a sala está livre
                                if (calItem.EndTime < DateTime.Now.ToUniversalTime())
                                {
                                    retorno.StatusDisponibilidade = StatusDisponibilidade.Livre;
                                    retorno.Mensagem = "";
                                }
                                // Se já passou 30 minutos de iniciada uma reunião e não terminou
                                else if ((DateTime.Now.ToUniversalTime() >= calItem.StartTime.ToUniversalTime().AddMinutes(30)) &&
                                         (DateTime.Now.ToUniversalTime() <= calItem.EndTime.ToUniversalTime()))
                                {
                                    retorno.StatusDisponibilidade = StatusDisponibilidade.EmReuniao30;

                                    TimeZoneInfo zonaFuso        = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
                                    var          dataFimZonaFuso = TimeZoneInfo.ConvertTimeFromUtc(calItem.EndTime, zonaFuso);

                                    retorno.Mensagem = "Reunião já inicada há mais de 30 minutos com término às " + dataFimZonaFuso.ToString(); // calItem.EndTime.ToLocalTime().ToString();
                                    // inclui na lista de eventos de calendários do retorno
                                    retorno.ListaEventos.Add(converterCalendarEventParaCalendarioEvento(calItem));
                                }
                                // Se já passou 15 minutos de iniciada uma reunião e não terminou
                                else if ((DateTime.Now.ToUniversalTime() >= calItem.StartTime.ToUniversalTime().AddMinutes(15)) &&
                                         (DateTime.Now.ToUniversalTime() <= calItem.EndTime.ToUniversalTime()))
                                {
                                    TimeZoneInfo zonaFuso        = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
                                    var          dataFimZonaFuso = TimeZoneInfo.ConvertTimeFromUtc(calItem.EndTime, zonaFuso);

                                    retorno.StatusDisponibilidade = StatusDisponibilidade.EmReuniao;
                                    retorno.Mensagem = "Reunião já inicada há mais de 15 minutos com término às " + dataFimZonaFuso.ToString(); // calItem.EndTime.ToLocalTime().ToString();
                                    // inclui na lista de eventos de calendários do retorno
                                    retorno.ListaEventos.Add(converterCalendarEventParaCalendarioEvento(calItem));
                                }
                                else
                                {
                                    TimeZoneInfo zonaFuso           = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
                                    var          dataInicioZonaFuso = TimeZoneInfo.ConvertTimeFromUtc(calItem.StartTime, zonaFuso);
                                    var          dataFimZonaFuso    = TimeZoneInfo.ConvertTimeFromUtc(calItem.EndTime, zonaFuso);

                                    retorno.StatusDisponibilidade = StatusDisponibilidade.Ocupado;
                                    retorno.Mensagem = " Ocupado de " + dataInicioZonaFuso.ToString() + " até " + dataFimZonaFuso.ToString();
                                    //retorno.Mensagem = " Ocupado de " + calItem.StartTime.ToLocalTime().ToString() + " até " + calItem.EndTime.ToLocalTime().ToString();
                                    // inclui na lista de eventos de calendários do retorno
                                    retorno.ListaEventos.Add(converterCalendarEventParaCalendarioEvento(calItem));
                                }
                                break;
                            }
                            else
                            {
                                TimeZoneInfo zonaFuso           = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
                                var          dataInicioZonaFuso = TimeZoneInfo.ConvertTimeFromUtc(calItem.StartTime, zonaFuso);

                                retorno.StatusDisponibilidade = StatusDisponibilidade.Livre;
                                retorno.Mensagem = "Livre a partir de " + dataInicioZonaFuso.ToString(); //calItem.StartTime.ToString();
                            }
                        }
                    }
                    else
                    {
                        // O Status ainda é desconhecido
                        // Se for usar a opção de lógica por sugestão, manter desconhecido
                        retorno.StatusDisponibilidade = StatusDisponibilidade.Livre; // StatusDisponibilidade.Desconhecido;
                        // Mensagem ao usuário
                        retorno.Mensagem = "Não encontramos eventos de calendário para esta sala.";

                        if (!erro.Equals(string.Empty))
                        {
                            retorno.StatusDisponibilidade = StatusDisponibilidade.Desconhecido;
                            // Mensagem ao usuário
                            retorno.Mensagem = "[ERROR] " + erro;
                        }
                    }
                }

                // SUGESTÃO DE DATA MAIS PRÓXIMA DA DATA ATUAL
                if (resultadoDisponibilidade.Suggestions.Count > 0)
                {
                    // PEGAR A SUGESTAO MAIS CEDO
                    var sugestaoMaisCedo = resultadoDisponibilidade.Suggestions.OrderBy(x => x.Date).FirstOrDefault();

                    // SE POR VENTURA HOUVE SUGESTOES DE HORA, ELA TEM PRIORIDADE NO RETORNO
                    if (sugestaoMaisCedo.TimeSuggestions.Count > 0)
                    {
                        var horaDoEncontro = sugestaoMaisCedo.TimeSuggestions.OrderBy(x => x.MeetingTime).FirstOrDefault().MeetingTime;

                        TimeZoneInfo zonaFuso = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
                        horaDoEncontro = TimeZoneInfo.ConvertTimeFromUtc(horaDoEncontro, zonaFuso);


                        retorno.SugestaoProximaReuniao = horaDoEncontro.ToLocalTime();
                    }
                    else
                    {
                        TimeZoneInfo zonaFuso = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
                        var          sugestao = TimeZoneInfo.ConvertTimeFromUtc(sugestaoMaisCedo.Date, zonaFuso);

                        retorno.SugestaoProximaReuniao = sugestaoMaisCedo.Date;
                    }
                }
            }
            catch (Exception ex)
            {
                string msgDisponibilidade = "[EXCEPTION] " +
                                            (ex.Message != null ? "MESSAGE = " + ex.Message.ToString() + " | " : "") +
                                            (ex.InnerException != null ? "INNER = " + ex.InnerException.ToString() + " | " : "") +
                                            (ex.StackTrace != null ? "STACKTRACE = " + ex.StackTrace.ToString() + " | " : "") +
                                            (ex.Source != null ? "SOURCE = " + ex.Source.ToString() : "");
                retorno.Mensagem = msgDisponibilidade;

                retorno.StatusDisponibilidade = StatusDisponibilidade.Desconhecido;
            }
            return(retorno);
        }
Пример #24
0
            private static void initFromFrame(OutlookData data, Outlook outlook, Location location)
            {
                DateTime
                    locationTime  = location.LocationTime,
                    locationToday = new DateTime(locationTime.Year, locationTime.Month, locationTime.Day),
                    windowBeg     = locationToday, //locationTime,
                    windowEnd     = locationToday.AddDays(1).AddMilliseconds(-1)
                ;

                // EWS: create connection point
                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;

                ExchangeService service = new ExchangeService(outlook.EwsVersion)
                {
                    Credentials = new WebCredentials(
                        outlook.Account,
                        RsaUtil.Decrypt(outlook.Password)
                        ),
                };

                // EWS: get URL
                if (!string.IsNullOrWhiteSpace(outlook.URL))
                {
                    service.Url = new Uri(outlook.URL);
                }
                else
                {
                    service.Url = HttpRuntime.Cache.GetOrAddSliding(
                        string.Format("exchange_account_{0}", outlook.Account),
                        () =>
                    {
                        service.AutodiscoverUrl(outlook.Account, RedirectionUrlValidationCallback);
                        return(service.Url);
                    },
                        TimeSpan.FromMinutes(60)
                        );
                }

                // mailbox: get display name
                data.DisplayName = outlook.Name;
                if (string.IsNullOrWhiteSpace(data.DisplayName))
                {
                    var match = service.ResolveName(outlook.Mailbox);
                    if (match.Count > 0)
                    {
                        if (match[0].Contact != null)
                        {
                            data.DisplayName =
                                match[0].Contact.CompleteName.FullName
                                ?? match[0].Contact.DisplayName
                                ?? data.DisplayName
                            ;
                        }

                        else if (match[0].Mailbox != null)
                        {
                            data.DisplayName =
                                match[0].Mailbox.Name
                                ?? data.DisplayName
                            ;
                        }
                    }
                    //else
                    //    throw new ApplicationException(string.Format("Mailbox {0} not found", mailbox));
                }

                // mailbox: get availability
                GetUserAvailabilityResults uars = service.GetUserAvailability(
                    new AttendeeInfo[] { new AttendeeInfo(outlook.Mailbox, MeetingAttendeeType.Required, true) },
                    new TimeWindow(locationToday, locationToday.AddDays(1)),
                    AvailabilityData.FreeBusy
                    );
                var u = uars.AttendeesAvailability[0];

                if (u.WorkingHours != null)
                {
                    data.startTime = u.WorkingHours.StartTime;
                    data.endTime   = u.WorkingHours.EndTime;
                    data.timeZone  = u.WorkingHours.TimeZone;
                }

                // events: prep filter
                FolderId       folderId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(outlook.Mailbox));
                CalendarFolder calendar = CalendarFolder.Bind(service, folderId, new PropertySet());
                CalendarView   cView    = new CalendarView(windowBeg, windowEnd)
                {
                    PropertySet = new PropertySet(
                        AppointmentSchema.Subject,
                        AppointmentSchema.DateTimeCreated,
                        AppointmentSchema.Start,
                        AppointmentSchema.End,
                        AppointmentSchema.Duration
                        )
                };

                // events: get list
                data.events = calendar
                              .FindAppointments(cView)
                              .OrderBy(i => i.Start)
                              .ThenBy(i => i.DateTimeCreated)
                              .ThenBy(i => i.Subject)
                              //.Take(Math.Max(1, outlook.ShowEvents))
                              .Select(a => new EventEntry
                {
                    Subject   = a.Subject,
                    CreatedOn = a.DateTimeCreated,
                    Starts    = a.Start,
                    Ends      = a.End,
                    Duration  = a.Duration,
                    Today     = locationToday,
                })
                              //.ToList()
                ;
            }
Пример #25
0
            public static async System.Threading.Tasks.Task <OutlookData> FromFrameAsync(Outlook outlook, Location location, int reserveMinutes)
            {
                OutlookData data = new OutlookData();
                DateTime
                    locationTime  = location.LocationTime,
                    locationToday = new DateTime(locationTime.Year, locationTime.Month, locationTime.Day),
                    windowBeg     = locationToday, //locationTime,
                    windowEnd     = locationToday.AddDays(1).AddMilliseconds(-1)
                ;

                // EWS: create connection point
                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;

                ExchangeService service = new ExchangeService(outlook.EwsVersion)
                {
                    Credentials = new WebCredentials(
                        outlook.Account,
                        Encryptor.Current.Decrypt(outlook.Password) // 1.4.0
                        ),
                };

                // https://msdn.microsoft.com/en-us/library/office/dn458789%28v=exchg.150%29.aspx?f=255&MSPPError=-2147217396#bk_howmaintained
                // https://social.msdn.microsoft.com/Forums/lync/en-US/bd032e3d-2501-40ba-a2b0-29a404685c35/error-exchange-web-services-are-not-currently-available?forum=exchangesvrdevelopment
                service.HttpHeaders.Add("X-AnchorMailbox", outlook.Account);

                // EWS: get URL
                if (!string.IsNullOrWhiteSpace(outlook.URL))
                {
                    service.Url = new Uri(outlook.URL);
                }
                else
                {
                    service.Url = await HttpRuntime.Cache.GetOrAddSlidingAsync(
                        string.Format("exchange_account_{0}", outlook.Account),
                        async (expire) =>
                    {
                        expire.After = TimeSpan.FromMinutes(60);
                        return(await System.Threading.Tasks.Task.Run(() =>
                        {
                            service.AutodiscoverUrl(outlook.Account, RedirectionUrlValidationCallback);
                            return service.Url;
                        }));
                    });
                }

                // mailbox: get display name
                data.DisplayName = outlook.Name;
                if (string.IsNullOrWhiteSpace(data.DisplayName))
                {
                    var match = await System.Threading.Tasks.Task.Run(() => service.ResolveName(outlook.Mailbox));

                    if (match.Count > 0)
                    {
                        if (match[0].Contact != null)
                        {
                            data.DisplayName =
                                match[0].Contact.CompleteName.FullName
                                ?? match[0].Contact.DisplayName
                                ?? data.DisplayName
                            ;
                        }

                        else if (match[0].Mailbox != null)
                        {
                            data.DisplayName =
                                match[0].Mailbox.Name
                                ?? data.DisplayName
                            ;
                        }
                    }
                    //else
                    //    throw new ApplicationException(string.Format("Mailbox {0} not found", mailbox));
                }

                // mailbox: get availability
                GetUserAvailabilityResults uars = await System.Threading.Tasks.Task.Run(() =>
                {
                    return(service.GetUserAvailability(
                               new AttendeeInfo[] { new AttendeeInfo(outlook.Mailbox, MeetingAttendeeType.Required, true) },
                               new TimeWindow(locationToday, locationToday.AddDays(1)),
                               AvailabilityData.FreeBusy
                               ));
                });

                var u = uars.AttendeesAvailability[0];

                if (u.WorkingHours != null)
                {
                    data.startTime = u.WorkingHours.StartTime;
                    data.endTime   = u.WorkingHours.EndTime;
                    data.timeZone  = u.WorkingHours.TimeZone;
                }

                if (reserveMinutes > 0)
                {
                    Appointment appointment = new Appointment(service)
                    {
                        Subject = outlook.BookingSubject,
                        Body    = string.Format("{0} | {1}", Resources.Outlook_BookingOnDemand, Resources.DisplayMonkey),
                        Start   = DateTime.Now,
                        End     = DateTime.Now.AddMinutes(reserveMinutes),
                    };

                    if (outlook.Mailbox == outlook.Account)
                    {
                        await System.Threading.Tasks.Task.Run(() =>
                        {
                            appointment.Save(SendInvitationsMode.SendToNone);
                            return(true);
                        });
                    }
                    else
                    {
                        appointment.Resources.Add(outlook.Mailbox);
                        await System.Threading.Tasks.Task.Run(() =>
                        {
                            appointment.Save(SendInvitationsMode.SendOnlyToAll);
                            return(true);
                        });
                    }
                }

                // events: prep filter
                FolderId       folderId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(outlook.Mailbox));
                CalendarFolder calendar = await System.Threading.Tasks.Task.Run(() => CalendarFolder.Bind(service, folderId, new PropertySet()));

                CalendarView cView = new CalendarView(windowBeg, windowEnd)
                {
                    PropertySet = new PropertySet(
                        //BasePropertySet.FirstClassProperties,
                        AppointmentSchema.Subject,
                        AppointmentSchema.DateTimeCreated,
                        AppointmentSchema.Start,
                        AppointmentSchema.End,
                        AppointmentSchema.Duration,
                        AppointmentSchema.Sensitivity,
                        AppointmentSchema.LegacyFreeBusyStatus
                        )
                };

                // events: get list
                var appointments = await System.Threading.Tasks.Task.Run(() => calendar.FindAppointments(cView));

                data.events = appointments
                              //.FindAppointments(cView)
                              .Where(a =>
                                     (outlook.Privacy != Models.OutlookPrivacy.OutlookPrivacy_NoClassified || a.Sensitivity == Sensitivity.Normal) &&
                                     (outlook.IsShowAsAllowed(a.LegacyFreeBusyStatus))
                                     )
                              .OrderBy(i => i.Start)
                              .ThenBy(i => i.DateTimeCreated)
                              .ThenBy(i => i.Subject)
                              //.Take(Math.Max(1, outlook.ShowEvents))
                              .Select(a => new EventEntry
                {
                    Subject =
                        outlook.Privacy == Models.OutlookPrivacy.OutlookPrivacy_All || a.Sensitivity == Sensitivity.Normal ? a.Subject :
                        DataAccess.StringResource(string.Format("EWS_Sensitivity_{0}", a.Sensitivity.ToString())),
                    CreatedOn   = a.DateTimeCreated,
                    Starts      = a.Start,
                    Ends        = a.End,
                    Duration    = a.Duration,
                    Sensitivity = a.Sensitivity,
                    Today       = locationToday,
                    ShowAs      = a.LegacyFreeBusyStatus,
                })
                              .ToList()
                ;

                return(data);
            }
Пример #26
0
        public IReadOnlyList <ServiceAgent> GetUserFreeBusy(IReadOnlyList <string> agentIDs, string targetTimeZone, TimeSpan shiftStartTime, TimeSpan shiftEndTime, DateTime startDate, DateTime endDate, out int rehitcount, out bool isExchangeFailure)
        {
            try
            {
                rehitcount          = 0;
                isExchangeFailure   = false;
                RequestedTimeWindow = new TimeWindow(startDate, endDate);
                List <string>             missedAgentIDs = new List <string>();
                Collection <TimeSlot>     lstTimeSlot;
                Collection <ServiceAgent> lstServiceAgent = new Collection <ServiceAgent>();
                // Create a list of attendees.
                Collection <AttendeeInfo> attendees         = new Collection <AttendeeInfo>();
                Collection <AttendeeInfo> attendeesInternal = new Collection <AttendeeInfo>();
                bool exchangeDataRetrival = true;
                int  exchangeRehit        = 0;
                int  count               = 0;
                int  totalcount          = 0;
                int  agentsQueried       = 0;
                int  agentsQueriedMissed = 0;
                int  agentsRetrieved     = 0;
                if (agentIDs != null || agentIDs.Count > 0)
                {
                    foreach (var agentID in agentIDs)
                    {
                        count      += 1;
                        totalcount += 1;
                        attendees.Add(new AttendeeInfo()
                        {
                            SmtpAddress  = agentID,
                            AttendeeType = MeetingAttendeeType.Required
                        });

                        if ((count == 13) || (totalcount == agentIDs.Count))
                        {
                            count = 0;
                            while (exchangeDataRetrival)
                            {
                                missedAgentIDs.Clear();
                                // Specify availability options.
                                AvailabilityOptions myOptions = new AvailabilityOptions();
                                myOptions.MeetingDuration       = 30;
                                myOptions.RequestedFreeBusyView = FreeBusyViewType.FreeBusy;
                                agentsQueried = attendees.Count;


                                // Return a set of free/busy times.
                                GetUserAvailabilityResults freeBusyResults = this.Exchange.GetUserAvailability(attendees,
                                                                                                               this.RequestedTimeWindow,
                                                                                                               AvailabilityData.FreeBusy,
                                                                                                               myOptions);
                                int i = 0;
                                foreach (AttendeeAvailability availability in freeBusyResults.AttendeesAvailability)
                                {
                                    if (availability.WorkingHours != null)
                                    {
                                        ServiceAgent srAgent = new ServiceAgent();
                                        srAgent.ServiceAgentEmail = attendees[i++].SmtpAddress;
                                        ServiceAgentWorkingHours srAgntWorkingHours = new ServiceAgentWorkingHours();
                                        srAgntWorkingHours.StartTime            = availability.WorkingHours.StartTime;
                                        srAgntWorkingHours.EndTime              = availability.WorkingHours.EndTime;
                                        srAgntWorkingHours.ServiceAgentTimeZone = targetTimeZone;
                                        srAgent.ServiceWorkingHours             = srAgntWorkingHours;
                                        lstTimeSlot = new Collection <TimeSlot>();
                                        foreach (CalendarEvent calendarItem in availability.CalendarEvents)
                                        {
                                            if (calendarItem.FreeBusyStatus.ToString() != "Free")
                                            {
                                                TimeSlot tmSlot = new TimeSlot();
                                                tmSlot.StartTime = TimeZoneInfo.ConvertTimeFromUtc(calendarItem.StartTime, TimeZoneInfo.FindSystemTimeZoneById(targetTimeZone));
                                                tmSlot.EndTime   = TimeZoneInfo.ConvertTimeFromUtc(calendarItem.EndTime, TimeZoneInfo.FindSystemTimeZoneById(targetTimeZone));
                                                tmSlot.FreeSlot  = false;
                                                lstTimeSlot.Add(tmSlot);
                                            }
                                        }
                                        srAgent.BusyTimeSlotsCustomerTimeZone = lstTimeSlot;
                                        lstServiceAgent.Add(srAgent);
                                    }
                                    else
                                    {
                                        missedAgentIDs.Add(attendees[i].SmtpAddress);
                                        i++;
                                    }
                                }

                                agentsQueriedMissed = missedAgentIDs.Count;

                                if (missedAgentIDs.Count > 0 && exchangeRehit == 0)
                                {
                                    attendees.Clear();
                                    foreach (var agentMissed in missedAgentIDs)
                                    {
                                        attendees.Add(new AttendeeInfo()
                                        {
                                            SmtpAddress  = agentMissed,
                                            AttendeeType = MeetingAttendeeType.Required
                                        });
                                    }
                                    exchangeRehit += 1;
                                    rehitcount     = exchangeRehit;
                                    // isExchangeFailure = false;
                                }
                                else if (missedAgentIDs.Count > 0 && exchangeRehit != 0)
                                {
                                    if ((agentsQueried - agentsQueriedMissed == 0))
                                    {
                                        rehitcount        = exchangeRehit;
                                        isExchangeFailure = true;
                                        break;
                                    }

                                    attendees.Clear();
                                    foreach (var agentMissed in missedAgentIDs)
                                    {
                                        attendees.Add(new AttendeeInfo()
                                        {
                                            SmtpAddress  = agentMissed,
                                            AttendeeType = MeetingAttendeeType.Required
                                        });
                                    }
                                    exchangeRehit += 1;
                                }
                                else if (missedAgentIDs.Count == 0)
                                {
                                    break;
                                }
                            }
                            attendees.Clear();
                        }
                    }
                }
                return(lstServiceAgent);
            }
            catch
            {
                throw;
            }
        }
Пример #27
0
        private static GetUserAvailabilityResults GetSuggestedMeetingTimesAndFreeBusyInfo(ExchangeService service)
        {
            // Create a collection of attendees.
            List <AttendeeInfo> attendees = new List <AttendeeInfo>();

            attendees.Add(new AttendeeInfo()
            {
                SmtpAddress  = "*****@*****.**", //get the current user email
                AttendeeType = MeetingAttendeeType.Organizer
            });

            attendees.Add(new AttendeeInfo()
            {
                SmtpAddress  = "*****@*****.**",
                AttendeeType = MeetingAttendeeType.Required
            });

            // Specify options to request free/busy information and suggested meeting times.
            AvailabilityOptions availabilityOptions = new AvailabilityOptions();

            availabilityOptions.GoodSuggestionThreshold = 49;
            availabilityOptions.MaximumNonWorkHoursSuggestionsPerDay = 0;
            availabilityOptions.MaximumSuggestionsPerDay             = 2;
            // Note that 60 minutes is the default value for MeetingDuration, but setting it explicitly for demonstration purposes.
            availabilityOptions.MeetingDuration           = 60;
            availabilityOptions.MinimumSuggestionQuality  = SuggestionQuality.Good;
            availabilityOptions.DetailedSuggestionsWindow = new TimeWindow(DateTime.Now.AddDays(1), DateTime.Now.AddDays(2));
            availabilityOptions.RequestedFreeBusyView     = FreeBusyViewType.FreeBusy;

            // Return free/busy information and a set of suggested meeting times.
            // This method results in a GetUserAvailabilityRequest call to EWS.
            GetUserAvailabilityResults results = null;

            results = service.GetUserAvailability(attendees,
                                                  availabilityOptions.DetailedSuggestionsWindow,
                                                  AvailabilityData.FreeBusyAndSuggestions,
                                                  availabilityOptions);
            return(results);

            #region find the suggestions and availability
            // Display suggested meeting times.
            //Console.WriteLine("Availability for {0} and {1}", attendees[0].SmtpAddress, attendees[1].SmtpAddress);
            //Console.WriteLine();

            //foreach (Suggestion suggestion in results.Suggestions)
            //{
            //    Console.WriteLine("Suggested date: {0}\n", suggestion.Date.ToShortDateString());
            //    Console.WriteLine("Suggested meeting times:\n");
            //    foreach (TimeSuggestion timeSuggestion in suggestion.TimeSuggestions)
            //    {
            //        Console.WriteLine("\t{0} - {1}\n",
            //                          timeSuggestion.MeetingTime.ToShortTimeString(),
            //                          timeSuggestion.MeetingTime.Add(TimeSpan.FromMinutes(availabilityOptions.MeetingDuration)).ToShortTimeString());



            //    }
            //}

            //int i = 0;

            //// Display free/busy times.
            //foreach (AttendeeAvailability availability in results.AttendeesAvailability)
            //{
            //    Console.WriteLine("Availability information for {0}:\n", attendees[i].SmtpAddress);

            //    foreach (CalendarEvent calEvent in availability.CalendarEvents)
            //    {
            //        Console.WriteLine("\tBusy from {0} to {1} \n", calEvent.StartTime.ToString(), calEvent.EndTime.ToString());
            //    }

            //    i++;
            //}

            #endregion
        }
Пример #28
0
        private void GetAvailabilityButton_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                // Get AttendeeInfo from AttendeeList
                List <AttendeeInfo> attendees = null;
                if (!this.TryGetAttendeesFromList(out attendees))
                {
                    ErrorDialog.ShowWarning("There must be at least one attendee listed to retrieve availability for.");
                    return;
                }

                // Get TimeWindow from input
                TimeWindow window = new TimeWindow(
                    this.StartWindowDate.Value.ToUniversalTime(),
                    this.EndWindowDate.Value.ToUniversalTime());

                // Get RequestedData from input
                AvailabilityData requestedData = AvailabilityData.FreeBusy;
                if (this.availDataCombo.SelectedItem.HasValue)
                {
                    requestedData = this.availDataCombo.SelectedItem.Value;
                }

                // Collect AvailabilityOptions from form input
                AvailabilityOptions options = new AvailabilityOptions();
                if (this.CurrentMeetingCheck.Checked)
                {
                    options.CurrentMeetingTime = this.CurrentMeetingDate.Value;
                }
                else
                {
                    options.CurrentMeetingTime = null;
                }

                options.MeetingDuration           = Convert.ToInt32(this.MeetingDurationText.Text);
                options.DetailedSuggestionsWindow = new TimeWindow(
                    this.StartDetailDate.Value,
                    this.EndDetailDate.Value);
                options.GlobalObjectId          = this.GlobalObjectIdText.Text;
                options.GoodSuggestionThreshold = Convert.ToInt32(this.GoodSuggestThresholdText.Text);
                options.MaximumNonWorkHoursSuggestionsPerDay = Convert.ToInt32(this.MaxNonWorkSuggestText.Text);
                options.MaximumSuggestionsPerDay             = Convert.ToInt32(this.MaxSuggestPerDayText.Text);
                options.MergedFreeBusyInterval = Convert.ToInt32(this.MergeFBIntervalText.Text);

                if (this.minSuggestQualCombo.SelectedItem.HasValue)
                {
                    options.MinimumSuggestionQuality = this.minSuggestQualCombo.SelectedItem.Value;
                }

                if (this.requestFBViewCombo.SelectedItem.HasValue)
                {
                    options.RequestedFreeBusyView = this.requestFBViewCombo.SelectedItem.Value;
                }

                // Remember which attendee was selected in the AttendeeList
                int selectedIndex = -1;
                if (this.AttendeeList.SelectedItems != null &&
                    this.AttendeeList.SelectedItems.Count == 1)
                {
                    selectedIndex = this.AttendeeList.SelectedItems[0].Index;
                    this.AttendeeList.Items[selectedIndex].Selected = false;
                }

                // Make the EWS request
                GetUserAvailabilityResults results = this.CurrentService.GetUserAvailability(
                    attendees,
                    window,
                    requestedData,
                    options);

                // Enable result lists
                this.AttendeeAvailabilityList.Enabled = true;
                this.CalEventsList.Enabled            = true;
                this.SuggestionsList.Enabled          = true;

                // Attach AttendeeAvailability to the associated attendee in the ListView.
                // It can be assumed that the order of the AttendeesAvailability and Suggestions
                // results arrays correspond to the order of the attendees.
                for (int i = 0; i < attendees.Count; i++)
                {
                    AttendeeAvailability availResult = null;
                    if (results.AttendeesAvailability != null &&
                        results.AttendeesAvailability[i] != null)
                    {
                        availResult = results.AttendeesAvailability[i];
                    }

                    this.AddResultsToAttendee(attendees[i], availResult);
                }

                if (results.Suggestions != null)
                {
                    // Display the Suggestion in the ListView
                    foreach (Suggestion suggest in results.Suggestions)
                    {
                        foreach (TimeSuggestion time in suggest.TimeSuggestions)
                        {
                            ListViewItem timeItem = this.SuggestionsList.Items.Add(suggest.Date.ToShortDateString());
                            timeItem.SubItems.Add(suggest.Quality.ToString());
                            timeItem.SubItems.Add(time.MeetingTime.ToShortTimeString());
                            timeItem.SubItems.Add(time.Quality.ToString());
                            timeItem.SubItems.Add(time.Conflicts.Count.ToString());
                            timeItem.SubItems.Add(time.IsWorkTime.ToString());
                        }
                    }
                }

                // Reset the selected Attendee and display the results or show a message
                // to inform the user how to display results.
                if (selectedIndex > -1)
                {
                    this.AttendeeList.Items[selectedIndex].Selected = true;
                }
                else
                {
                    //this.AttendeeAvailabilityGroup.Text = "Select an attendee in the list to display availability results.";
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
Пример #29
0
        /// <summary>
        /// 获取建议的会议时间和忙/闲信息
        /// </summary>
        /// <param name="config"></param>
        /// <param name="startTime"></param>
        /// <param name="endDateTime"></param>
        public static void GetSuggestedMeetingTimesAndFreeBusyInfo(ExchangeAdminConfig config, DateTime startTime,
                                                                   DateTime endDateTime)
        {
            InitializeEws(config);
            // Create a collection of attendees.
            List <AttendeeInfo> attendees = new List <AttendeeInfo>();

            attendees.Add(new AttendeeInfo()
            {
                SmtpAddress  = "*****@*****.**",
                AttendeeType = MeetingAttendeeType.Room
            });

            attendees.Add(new AttendeeInfo()
            {
                SmtpAddress  = "*****@*****.**",
                AttendeeType = MeetingAttendeeType.Room
            });

            // Specify options to request free/busy information and suggested meeting times.
            //AvailabilityOptions availabilityOptions = new AvailabilityOptions();
            //availabilityOptions.GoodSuggestionThreshold = 49;
            //availabilityOptions.MaximumNonWorkHoursSuggestionsPerDay = 0;
            //availabilityOptions.MaximumSuggestionsPerDay = 2;
            // Note that 60 minutes is the default value for MeetingDuration, but setting it explicitly for demonstration purposes.
            //availabilityOptions.MeetingDuration = 30;
            //availabilityOptions.MinimumSuggestionQuality = SuggestionQuality.Good;
            //availabilityOptions.DetailedSuggestionsWindow = new TimeWindow(startTime, endDateTime);
            //availabilityOptions.RequestedFreeBusyView = FreeBusyViewType.FreeBusy;

            // Return free/busy information and a set of suggested meeting times.
            // This method results in a GetUserAvailabilityRequest call to EWS.
            GetUserAvailabilityResults results = Service.GetUserAvailability(attendees,
                                                                             new TimeWindow(startTime, endDateTime),
                                                                             AvailabilityData.FreeBusy);

            // Display suggested meeting times.
            Console.WriteLine("Availability for {0} and {1}", attendees[0].SmtpAddress, attendees[1].SmtpAddress);
            Console.WriteLine();

            //foreach (Suggestion suggestion in results.Suggestions)
            //{
            //    Console.WriteLine("Suggested date: {0}\n", suggestion.Date.ToString("yyyy-MM-dd HH:mm:ss"));
            //    Console.WriteLine("Suggested meeting times:\n");
            //    foreach (TimeSuggestion timeSuggestion in suggestion.TimeSuggestions)
            //    {
            //        Console.WriteLine("\t{0} - {1}\n",
            //                          timeSuggestion.MeetingTime.ToString("yyyy-MM-dd HH:mm:ss"),
            //                          timeSuggestion.MeetingTime.Add(TimeSpan.FromMinutes(availabilityOptions.MeetingDuration)).ToString("yyyy-MM-dd HH:mm:ss"));



            //    }
            //}

            int i = 0;

            // Display free/busy times.
            foreach (AttendeeAvailability availability in results.AttendeesAvailability)
            {
                Console.WriteLine("Availability information for {0}:\n", attendees[i].SmtpAddress);

                foreach (CalendarEvent calEvent in availability.CalendarEvents)
                {
                    Console.WriteLine("\tBusy from {0} to {1} \n", calEvent.StartTime.ToString("yyyy-MM-dd HH:mm:ss"), calEvent.EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
                }

                i++;
            }
        }