Exemplo n.º 1
0
        public async Task <GetUserAvailabilityResults> getFreeBusyResultsAsync()
        {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

            service.UseDefaultCredentials = true; // Use domain account for connecting
            //service.Credentials = new WebCredentials("*****@*****.**", "password"); // used if we need to enter a password, but for now we are using domain credentials
            //service.AutodiscoverUrl("*****@*****.**");  //XXX we should use the service user for webmgmt!
            service.Url = new Uri("https://mail.aau.dk/EWS/exchange.asmx");

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

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

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

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

            // Return a set of free/busy times.
            DateTime dayBegin = DateTime.Now.Date;
            var      window   = new TimeWindow(dayBegin, dayBegin.AddDays(1));

            return(await service.GetUserAvailability(attendees, window, AvailabilityData.FreeBusy, myOptions));
        }
Exemplo n.º 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);
                }
            }
        }
Exemplo n.º 3
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));
        }
Exemplo n.º 5
0
        //private void ImportStatusForm_Resize(object sender, EventArgs e)
        //{
        //    if (this.WindowState == FormWindowState.Minimized)
        //    {
        //        .Visible = true;
        //        notifyIcon.ShowBalloonTip(3000);
        //        this.ShowInTaskbar = false;
        //    }
        //}

        //private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        //{
        //    this.WindowState = FormWindowState.Normal;
        //    this.ShowInTaskbar = true;
        //    notifyIcon.Visible = false;
        //}

        void RefreshExchangeStatus()
        {
            if (ReadSetting("username") != null)
            {
                exchangeService = new ExchangeService(ExchangeVersion.Exchange2013);
                AvailabilityOptions myOptions = new AvailabilityOptions();
                myOptions.MeetingDuration       = 2;
                myOptions.RequestedFreeBusyView = FreeBusyViewType.FreeBusy;

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

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

                // TODO: get url for webservice
                exchangeService.Url         = new Uri("your asmx url");
                exchangeService.Credentials = new WebCredentials(ReadSetting("username"), ReadSetting("password"));
                var userStatus = exchangeService.GetUserAvailability(attendees, new TimeWindow(DateTime.Now, DateTime.Now.AddDays(1)),
                                                                     AvailabilityData.FreeBusy,
                                                                     myOptions);

                var userDetailedStatus = userStatus.AttendeesAvailability.First();

                // initial green
                PushGreen();

                foreach (var calendarItem in userDetailedStatus.CalendarEvents)
                {
                    Console.WriteLine("User status for: " + ReadSetting("username"));
                    Console.WriteLine("  Free/busy status: " + calendarItem.FreeBusyStatus);
                    Console.WriteLine("  Start time: " + calendarItem.StartTime);
                    Console.WriteLine("  End time: " + calendarItem.EndTime);

                    if (calendarItem.StartTime <= DateTime.Now && DateTime.Now <= calendarItem.EndTime &&
                        calendarItem.FreeBusyStatus == LegacyFreeBusyStatus.Busy)
                    {
                        PushRed();
                    }
                    else if (calendarItem.StartTime <= DateTime.Now && DateTime.Now <= calendarItem.EndTime &&
                             calendarItem.FreeBusyStatus == LegacyFreeBusyStatus.Free)
                    {
                        PushGreen();
                    }
                    else if (calendarItem.StartTime <= DateTime.Now && DateTime.Now <= calendarItem.EndTime &&
                             calendarItem.FreeBusyStatus == LegacyFreeBusyStatus.OOF || calendarItem.FreeBusyStatus == LegacyFreeBusyStatus.Tentative || calendarItem.FreeBusyStatus == LegacyFreeBusyStatus.WorkingElsewhere)
                    {
                        PushYellow();
                    }
                }
            }
        }
Exemplo n.º 6
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);
                    }
                }
            }
        }
Exemplo n.º 7
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();
                }
            }
        }
Exemplo n.º 8
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);
    }
Exemplo n.º 9
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();
                }
            }
        }
        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);
        }
Exemplo n.º 11
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();
            }
        }
    }
Exemplo n.º 12
0
        public List <OutlookCalendarItem> GetAbsenceInfo(string TargetEmail, int NumDays)
        {
            ConnectToServer();
            if (service == null)
            {
                return(new List <OutlookCalendarItem>());
            }

            //start collecting from today
            DateTime StartDate = DateTime.Now;
            DateTime EndDate   = StartDate.AddDays(NumDays);

            List <OutlookCalendarItem> ret = new List <OutlookCalendarItem>();

            var options = new AvailabilityOptions
            {
                RequestedFreeBusyView = FreeBusyViewType.DetailedMerged
            };

            var attendees = new List <AttendeeInfo>();

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

            var results = service.GetUserAvailability(attendees, new TimeWindow(StartDate, EndDate), AvailabilityData.FreeBusy, options);

            foreach (AttendeeAvailability avail in results.AttendeesAvailability)
            {
                foreach (CalendarEvent item in avail.CalendarEvents)
                {
                    OutlookCalendarItem ci = new OutlookCalendarItem();
                    ci.Start        = item.StartTime;
                    ci.Duration     = (int)item.EndTime.Subtract(item.StartTime).TotalMinutes;
                    ci.ResponseType = (OutlookResponseStatus)item.FreeBusyStatus;
                    ret.Add(ci);
                }
            }
            return(ret);
        }
Exemplo n.º 13
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);
                    }
                }
            }
        }
Exemplo n.º 14
0
        public GetUserAvailabilityResults LoadRoomSchedule(List <Room> rooms, DateTime startDate, DateTime endDate)
        {
            //TimeWindow timeWindow = new TimeWindow(DateTime.Now.ToUniversalTime().Date, DateTime.Now.ToUniversalTime().Date.AddDays(1));
            TimeWindow timeWindow = new TimeWindow(startDate.ToUniversalTime().Date, startDate.ToUniversalTime().Date.AddDays(1));

            // We want to know if the room is free or busy.
            AvailabilityData    availabilityData    = AvailabilityData.FreeBusy;
            AvailabilityOptions availabilityOptions = new AvailabilityOptions();

            availabilityOptions.RequestedFreeBusyView    = FreeBusyViewType.FreeBusy;
            availabilityOptions.MaximumSuggestionsPerDay = 0;

            // Get the availability of the room.
            var result = service.GetUserAvailability(from n in rooms
                                                     select n.AttendeeInfo,
                                                     timeWindow,
                                                     availabilityData,
                                                     availabilityOptions);

            // Use the schedule to determine if a room is available for the next
            DetermineRoomAvailability(rooms, result, startDate, endDate);
            return(result);
        }
Exemplo n.º 15
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;
                    }
                }
            }
        }
Exemplo n.º 16
0
        private IEnumerable <RoomAvailabilityInfo> GetAvaialilityInternal(IEnumerable <RoomInfo> rooms)
        {
            var roomsArray = rooms.ToArray();
            var attendees  =
                roomsArray.Select(
                    r => new AttendeeInfo {
                AttendeeType = MeetingAttendeeType.Room, ExcludeConflicts = false, SmtpAddress = r.RoomId
            }).ToList();
            var timeWindow = new TimeWindow(DateTime.Now, DateTime.Now.AddDays(1));

            AvailabilityOptions options = new AvailabilityOptions
            {
                MeetingDuration       = 30,
                RequestedFreeBusyView = FreeBusyViewType.FreeBusy
            };
            var availabilities = _service.GetUserAvailability(attendees, timeWindow, AvailabilityData.FreeBusy, options);

            Debug.Assert(roomsArray.Length == availabilities.AttendeesAvailability.Count, "Invalid server response");
            return(roomsArray.Zip(availabilities.AttendeesAvailability, (room, availability) =>
            {
                var info = Helper.CollapseCalendar(availability.CalendarEvents.Select(x => new TimeInterval(x.StartTime, x.EndTime)));
                return new RoomAvailabilityInfo(info, room);
            }));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Get meeting schedule for each room for current day
        /// </summary>
        /// <param name="rooms"></param>
        /// <returns></returns>
        private GetUserAvailabilityResults GetRoomsSchedule(Collection <EmailAddress> rooms, DateTime date)
        {
            List <AttendeeInfo> attendees      = new List <AttendeeInfo>();
            AvailabilityOptions meetingOptions = new AvailabilityOptions();

            meetingOptions.MeetingDuration = 30;
            meetingOptions.MaximumNonWorkHoursSuggestionsPerDay = 0;
            meetingOptions.CurrentMeetingTime = date;

            foreach (EmailAddress room in rooms)
            {
                attendees.Add(new AttendeeInfo()
                {
                    SmtpAddress  = room.Address,
                    AttendeeType = MeetingAttendeeType.Room
                });
            }

            return(service.GetUserAvailability(
                       attendees,
                       new TimeWindow(date, date.AddDays(1)),
                       AvailabilityData.FreeBusyAndSuggestions,                                                                  // TODO: maybe Suggestions not required
                       meetingOptions));
        }
Exemplo n.º 18
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;
            }
        }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
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;
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Get exchange status
        /// </summary>
        void GetExchangeStatus()
        {
            try
            {
                if (ReadSetting("username") != null || ReadSetting("username") == "" && ReadSetting("exchangeHost") != null || ReadSetting("exchangeHost") == "")
                {
                    exchangeService = new ExchangeService(ExchangeVersion.Exchange2013);
                    AvailabilityOptions myOptions = new AvailabilityOptions();
                    myOptions.MeetingDuration       = 2;
                    myOptions.RequestedFreeBusyView = FreeBusyViewType.FreeBusy;

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

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

                    // TODO: get url for webservice
                    exchangeService.Url         = new Uri(ReadSetting("exchangeHost"));
                    exchangeService.Credentials = new WebCredentials(ReadSetting("username"), StringCipher.Decrypt(ReadSetting("password")));
                    var userStatus = exchangeService.GetUserAvailability(attendees, new TimeWindow(DateTime.Now, DateTime.Now.AddDays(1)),
                                                                         AvailabilityData.FreeBusy,
                                                                         myOptions);

                    var userDetailedStatus = userStatus.AttendeesAvailability.First();

                    // initial green
                    PushGreen();

                    foreach (var calendarItem in userDetailedStatus.CalendarEvents)
                    {
                        Console.WriteLine("User status for: " + ReadSetting("username"));
                        Console.WriteLine("  Free/busy status: " + calendarItem.FreeBusyStatus);
                        Console.WriteLine("  Start time: " + calendarItem.StartTime);
                        Console.WriteLine("  End time: " + calendarItem.EndTime);

                        if (calendarItem.StartTime <= DateTime.Now && DateTime.Now <= calendarItem.EndTime &&
                            calendarItem.FreeBusyStatus == LegacyFreeBusyStatus.Busy)
                        {
                            PushRed();
                        }
                        else if (calendarItem.StartTime <= DateTime.Now && DateTime.Now <= calendarItem.EndTime &&
                                 calendarItem.FreeBusyStatus == LegacyFreeBusyStatus.Free)
                        {
                            PushGreen();
                        }
                        else if (calendarItem.StartTime <= DateTime.Now && DateTime.Now <= calendarItem.EndTime &&
                                 calendarItem.FreeBusyStatus == LegacyFreeBusyStatus.OOF || calendarItem.FreeBusyStatus == LegacyFreeBusyStatus.Tentative || calendarItem.FreeBusyStatus == LegacyFreeBusyStatus.WorkingElsewhere)
                        {
                            PushYellow();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //statusbar.Text = "Error: Problemer med exchange tilkobling...";

                setStatusText("Error: Problems with Exchange connection...");
            }
        }
Exemplo n.º 22
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();
             * }
             */
        }
Exemplo n.º 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);
        }
Exemplo n.º 24
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
        }