Example #1
0
 /// <summary>
 /// Returns all appointments for period from <paramref name="folder"/>. Recurring apointments included.
 /// </summary>
 /// <param name="context"><see cref="SyncContext"/> instance.</param>
 /// <param name="folder"><see cref=" Exchange.Folder"/> instance.</param>
 /// <returns><see cref="Exchange.Item"/> collection.</returns>
 protected IEnumerable <Exchange.Item> GetAppointmentsForPeriod(SyncContext context, Exchange.Folder folder)
 {
     if (GetExchangeRecurringAppointmentsSupported(context.UserConnection))
     {
         var type     = LoadFromDateType.GetInstance(context.UserConnection);
         var starDate = type.GetLoadFromDate(UserSettings.ActivitySyncPeriod);
         var endDate  = type.GetLoadFromDate(UserSettings.ActivitySyncPeriod, true);
         context?.LogInfo(SyncAction.None, SyncDirection.Download, "GetAppointmentsForPeriod with: starDate {0}, endDate {1}.",
                          starDate, endDate);
         var currentStartDate = starDate;
         while (currentStartDate < endDate)
         {
             var calendarItemView = new Exchange.CalendarView(currentStartDate, currentStartDate.AddDays(1), 150);
             context?.LogInfo(SyncAction.None, SyncDirection.Download, "GetAppointmentsForPeriod with: currentStartDate {0}.",
                              currentStartDate);
             Exchange.FindItemsResults <Exchange.Appointment> calendarItemCollection;
             calendarItemCollection = Service.FindAppointments(folder.Id, calendarItemView);
             context?.LogInfo(SyncAction.None, SyncDirection.Download,
                              "GetAppointmentsForPeriod - Service found {0} items.",
                              calendarItemCollection.Count());
             foreach (var item in calendarItemCollection)
             {
                 yield return(item);
             }
             currentStartDate = currentStartDate.AddDays(1);
         }
         context?.LogInfo(SyncAction.None, SyncDirection.Download, "GetAppointmentsForPeriod - End method.");
     }
 }
        /// <summary>
        /// Returns a list of events given the start and end time, inclusive.
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public IEnumerable<ICalendarEvent> GetCalendarEvents(DateTimeOffset startDate, DateTimeOffset endDate)
        {
            // Initialize the calendar folder object with only the folder ID.
            var propertiesToGet = new PropertySet(PropertySet.IdOnly);
            propertiesToGet.RequestedBodyType = BodyType.Text;

            var calendar = CalendarFolder.Bind(_exchangeService, WellKnownFolderName.Calendar, propertiesToGet);
            
            // Set the start and end time and number of appointments to retrieve.
            var calendarView = new CalendarView(
                startDate.ToOffset(_exchangeService.TimeZone.BaseUtcOffset).DateTime,
                endDate.ToOffset(_exchangeService.TimeZone.BaseUtcOffset).DateTime,
                MAX_EVENTS_TO_RETRIEVE);

            // Retrieve a collection of appointments by using the calendar view.
            var appointments = calendar.FindAppointments(calendarView);

            // Get specific properties.
            var appointmentSpecificPropertiesToGet = new PropertySet(PropertySet.FirstClassProperties);
            appointmentSpecificPropertiesToGet.AddRange(NonFirstClassAppointmentProperties);
            appointmentSpecificPropertiesToGet.RequestedBodyType = BodyType.Text;
            _exchangeService.LoadPropertiesForItems(appointments, appointmentSpecificPropertiesToGet);

            return TransformExchangeAppointmentsToGenericEvents(appointments);
        }
        // URI like http://127.0.0.1:81/Schedule/ThisMonthItems?MailAddress=...&Password=...
        public ActionResult ThisMonthItems(O365AccountModel model)
        {
            // Exchange Online に接続 (今回はデモなので、Address は決めうち !)
            string emailAddress = model.MailAddress;
            string password = model.Password;
            ExchangeVersion ver = new ExchangeVersion();
            ver = ExchangeVersion.Exchange2010_SP1;
            ExchangeService sv = new ExchangeService(ver, TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time"));
            //sv.TraceEnabled = true; // デバッグ用
            sv.Credentials = new System.Net.NetworkCredential(emailAddress, password);
            //sv.EnableScpLookup = false;
            //sv.AutodiscoverUrl(emailAddress, AutodiscoverCallback);
            //sv.Url = new Uri(@"https://hknprd0202.outlook.com/EWS/Exchange.asmx");
            sv.Url = new Uri(model.Url);

            // 今月の予定 (Appointment) を取得
            //DateTime nowDate = DateTime.Now;
            DateTime nowDate = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now.ToUniversalTime(), "Tokyo Standard Time");
            DateTime firstDate = new DateTime(nowDate.Year, nowDate.Month, 1);
            DateTime lastDate = firstDate.AddDays(DateTime.DaysInMonth(nowDate.Year, nowDate.Month) - 1);
            CalendarView thisMonthView = new CalendarView(firstDate, lastDate);
            FindItemsResults<Appointment> appointRes = sv.FindAppointments(WellKnownFolderName.Calendar, thisMonthView);

            // 結果 (Json 値) を作成
            IList<object> resList = new List<object>();
            foreach (Appointment appointItem in appointRes.Items)
            {
                // (注意 : Json では、Date は扱えない !)
                resList.Add(new
                {
                    Subject = appointItem.Subject,
                    StartYear = appointItem.Start.Year,
                    StartMonth = appointItem.Start.Month,
                    StartDate = appointItem.Start.Day,
                    StartHour = appointItem.Start.Hour,
                    StartMinute = appointItem.Start.Minute,
                    StartSecond = appointItem.Start.Second
                });
            }
            return new JsonResult()
            {
                Data = resList,
                ContentEncoding = System.Text.Encoding.UTF8,
                ContentType = @"application/json",
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
Example #4
0
        public List <OutlookAppointment> GetCalendarEntriesInRange()
        {
            List <OutlookAppointment> appointments = new List <OutlookAppointment>();
            var service = new Microsoft.Exchange.WebServices.Data.ExchangeService(Microsoft.Exchange.WebServices.Data.ExchangeVersion.Exchange2010_SP1);

            service.Credentials = new Microsoft.Exchange.WebServices.Data.WebCredentials(Settings.Instance.ExchageUser, Settings.Instance.ExchagePassword);

            if (string.IsNullOrWhiteSpace(Settings.Instance.ExchageServerAddress))
            {
                service.AutodiscoverUrl(Settings.Instance.ExchageUser, ValidateRedirectionUrlCallback);
            }
            else
            {
                service.Url = new Uri(Settings.Instance.ExchageServerAddress + "/EWS/Exchange.asmx");
            }

            DateTime min = DateTime.Now.AddDays(-Settings.Instance.DaysInThePast);
            DateTime max = DateTime.Now.AddDays(+Settings.Instance.DaysInTheFuture + 1);

            var calView = new Microsoft.Exchange.WebServices.Data.CalendarView(min, max);

            calView.PropertySet = new PropertySet(
                BasePropertySet.IdOnly,
                AppointmentSchema.Subject,
                AppointmentSchema.Start,
                AppointmentSchema.IsRecurring,
                AppointmentSchema.AppointmentType,
                AppointmentSchema.End,
                AppointmentSchema.IsAllDayEvent,
                AppointmentSchema.Location,
                AppointmentSchema.Organizer,
                AppointmentSchema.ReminderMinutesBeforeStart,
                AppointmentSchema.IsReminderSet
                );

            FindItemsResults <Appointment> findResults = service.FindAppointments(WellKnownFolderName.Calendar, calView);

            foreach (Appointment appointment in findResults.Items)
            {
                OutlookAppointment newAppointment = GetOutlookAppointment(appointment, service);
                appointments.Add(newAppointment);
            }

            return(appointments);
        }
Example #5
0
        public List<OutlookAppointment> GetCalendarEntriesInRange()
        {
            List<OutlookAppointment> appointments = new List<OutlookAppointment>();
            var service = new Microsoft.Exchange.WebServices.Data.ExchangeService(Microsoft.Exchange.WebServices.Data.ExchangeVersion.Exchange2010_SP1);
            service.Credentials = new Microsoft.Exchange.WebServices.Data.WebCredentials(Settings.Instance.ExchageUser, Settings.Instance.ExchagePassword);

            if (string.IsNullOrWhiteSpace(Settings.Instance.ExchageServerAddress))
            {
                service.AutodiscoverUrl(Settings.Instance.ExchageUser, ValidateRedirectionUrlCallback);
            }
            else
            {
                service.Url = new Uri(Settings.Instance.ExchageServerAddress + "/EWS/Exchange.asmx");
            }

            DateTime min = DateTime.Now.AddDays(-Settings.Instance.DaysInThePast);
            DateTime max = DateTime.Now.AddDays(+Settings.Instance.DaysInTheFuture + 1);

            var calView = new Microsoft.Exchange.WebServices.Data.CalendarView(min, max);
            calView.PropertySet = new PropertySet(
                BasePropertySet.IdOnly,
                AppointmentSchema.Subject,
                AppointmentSchema.Start,
                AppointmentSchema.IsRecurring,
                AppointmentSchema.AppointmentType,
                AppointmentSchema.End,
                AppointmentSchema.IsAllDayEvent,
                AppointmentSchema.Location,
                AppointmentSchema.Organizer,
                AppointmentSchema.ReminderMinutesBeforeStart,
                AppointmentSchema.IsReminderSet
                );

            FindItemsResults<Appointment> findResults = service.FindAppointments(WellKnownFolderName.Calendar, calView);

            foreach (Appointment appointment in findResults.Items)
            {
                OutlookAppointment newAppointment = GetOutlookAppointment(appointment, service);
                appointments.Add(newAppointment);
            }

            return appointments;
        }
        public List<Meeting> MeetingStatistics(DateTime startDate, DateTime endDate)
        {
            var allMeetings = new List<Meeting>();

            while (startDate.DayOfWeek != DayOfWeek.Monday)
            {
                startDate -= TimeSpan.FromDays(1);
            }

            while (startDate < endDate)
            {
                System.Console.WriteLine("Retrieving for {0}", startDate);

                var calendar = CalendarFolder.Bind(m_ExchangeService, WellKnownFolderName.Calendar, new PropertySet());

                // Set the start and end time and number of appointments to retrieve.
                var cView = new CalendarView(startDate, startDate + TimeSpan.FromDays(28))
                {
                    PropertySet = new PropertySet(
                        ItemSchema.Subject,
                        AppointmentSchema.Start,
                        AppointmentSchema.Duration,
                        AppointmentSchema.MyResponseType,
                        AppointmentSchema.IsAllDayEvent
                        )
                };

                // Retrieve a collection of appointments by using the calendar view.
                var meetings = calendar.FindAppointments(cView);

                

                allMeetings.AddRange(
                    meetings.Where(x => x.MyResponseType == MeetingResponseType.Accept).Select(meeting => 
                        new Meeting(meeting.Start, meeting.Duration > TimeSpan.FromHours(8) ? TimeSpan.FromHours(8) : meeting.Duration, meeting.Subject)
                        )
                    );

                startDate += TimeSpan.FromDays(28);
            }

            return allMeetings;
        }
        private string FreeRoom(string roomName)
        {
            // ToDo: error stategy to be implemented
            // log into Officee 365

            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
            //service.Credentials = new WebCredentials("*****@*****.**", "Passw0rd!");
            service.Credentials = new WebCredentials("*****@*****.**", "Passw0rd!");
            //service.Credentials = new WebCredentials("*****@*****.**", "");
            service.UseDefaultCredentials = false;
            service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback);
            //EmailMessage email = new EmailMessage(service);
            //email.ToRecipients.Add("*****@*****.**");
            //email.Subject = "HelloWorld";
            //email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API.");
            //email.Send();

            // GetRoomLists
            EmailAddressCollection roomGroup = service.GetRoomLists();

            // GetRooms(roomGroup)
            Collection<EmailAddress> rooms = service.GetRooms(roomGroup[0]);

            string response = "No meeting room found";
            //if the room.Address matchaes the one you are looking for then
            foreach (EmailAddress room in rooms)
            {
                if (room.Name == roomName)
                {
                    Mailbox mailBox = new Mailbox(room.Address, "Mailbox");

                    //Mailbox mailBox = new Mailbox("*****@*****.**", "Mailbox");
                    // Create a FolderId instance of type WellKnownFolderName.Calendar and a new mailbox with the room's address and routing type
                    FolderId folderID = new FolderId(WellKnownFolderName.Calendar, mailBox);
                    // Create a CalendarView with from and to dates
                    DateTime start = DateTime.Now.ToUniversalTime().AddHours(-8);

                    DateTime end = DateTime.Now.ToUniversalTime().AddHours(5);
                    //end.AddHours(3);
                    CalendarView calendarView = new CalendarView(start, end);

                    // Call findAppointments on FolderId populating CalendarView
                    FindItemsResults<Appointment> appointments = service.FindAppointments(folderID, calendarView);

                    // Iterate the appointments

                    if (appointments.Items.Count == 0)
                        response = "The room is free";
                    else
                    {
                        DateTime appt = appointments.Items[0].Start;
                        TimeSpan test = DateTime.Now.Subtract(appt);
                        int t = (int)Math.Round(Convert.ToDecimal(test.TotalMinutes.ToString()));

                        if (test.TotalMinutes < 0)
                            response = "a meeting is booked at this time";
                        else
                            response = "the room is free for " + t.ToString() + "minutes";
                    }
                    Console.WriteLine(response);
                }
            }
            return response;
        }
Example #8
0
 // Method for creating appointments filter by range date
 private static CalendarView Appointment_Filter()
 {
     DateTime date_from = new DateTime(2012, 1, 1);
     DateTime date_to = new DateTime(2013, 12, 31);
     //DateTime date_from = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
     //DateTime date_to = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(1);
     CalendarView cvCalendarView = new CalendarView(date_from, date_to, 1000); // limits to first 1000 appointments in selected date range
     return cvCalendarView;
 }
        private static webServiceData.Appointment searchAppointment(SchedulingInfo schedulingInfo, webServiceData.ExchangeService service)
        {
            RvLogger.DebugWrite("enter searchAppointment==============");
            webServiceData.Mailbox mailBox = new webServiceData.Mailbox(schedulingInfo.delegatorEmailAddr);
            webServiceData.FolderId folderID = new webServiceData.FolderId(webServiceData.WellKnownFolderName.Calendar, mailBox);
            webServiceData.CalendarFolder folder = webServiceData.CalendarFolder.Bind(service, folderID);
            webServiceData.CalendarView view = new webServiceData.CalendarView(schedulingInfo.startDate, schedulingInfo.endDate);
            webServiceData.PropertySet propertySet = new webServiceData.PropertySet(webServiceData.BasePropertySet.FirstClassProperties);
            view.PropertySet = propertySet;
            webServiceData.FindItemsResults<webServiceData.Appointment> results = folder.FindAppointments(view);

            RvLogger.DebugWrite("results==============" + (null == results.Items ? "0" : "" + results.Items.Count));

            foreach (webServiceData.Item item in results)
            {
                try
                {
                    webServiceData.Appointment appointment = (webServiceData.Appointment)item;
                    if (string.IsNullOrEmpty(schedulingInfo.location)) schedulingInfo.location = "";
                    if (string.IsNullOrEmpty(appointment.Location)) appointment.Location = "";
                    if (string.IsNullOrEmpty(schedulingInfo.subject)) schedulingInfo.subject = "";
                    if (string.IsNullOrEmpty(appointment.Subject)) appointment.Subject = "";
                    if (schedulingInfo.location == appointment.Location 
                        && appointment.Subject == schedulingInfo.subject
                        && 0 == appointment.Start.ToUniversalTime().CompareTo(schedulingInfo.startDate.ToUniversalTime())
                        && 0 == appointment.End.ToUniversalTime().CompareTo(schedulingInfo.endDate.ToUniversalTime()))
                    {
                        return appointment;
                    }
                }
                catch (ScopiaMeetingAddInException ex)
                {
                    throw ex;
                }
            }

            return null;
        }
        public IHttpActionResult GetDetails(GetAppointmentsRequest request)
        {
            var startDate = DateTime.Parse(request.Start);
            var endDate = DateTime.Parse(request.End);
            // Assuming 8 max per day * 5 (days/week) * 4 (weeks/month)
            const int NUM_APPTS = 160;
            var calendar = CalendarFolder.Bind(ExchangeServer.Open(), WellKnownFolderName.Calendar, new PropertySet());
            var cView = new CalendarView(startDate, endDate, NUM_APPTS);
            cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.TimeZone);



            FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);

            var response = new GetAppointmentsResponse();
            var list = new List<Interview>();
            foreach(var app in appointments)
            {
                var appointment = Appointment.Bind(ExchangeServer.Open(), app.Id);

                var attendees = new List<RequiredAttendees>();
                foreach (var required in appointment.RequiredAttendees)
                {
                    attendees.Add(new RequiredAttendees
                    {
                        Name = required.Name,
                        Email = required.Address,
                        Response = required.ResponseType.ToString()
                    });


                }

                list.Add(new Interview { Start = app.Start, End = app.End, TimeZone = app.TimeZone, Attendees = attendees, Subject = app.Subject});

            }
            response.Appointments = list;
            return Ok(response);
        }
        public static List<CalendarEvent> GetAllEvents(String exchangeurl, String user, String pass)
        {
            List<CalendarEvent> events = new List<CalendarEvent>();

            ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
            service.Credentials = new WebCredentials(user, pass);

            service.TraceEnabled = true;
            service.TraceFlags = TraceFlags.All;
            service.TraceListener = new TraceListener();

            //When attempting to connect to EWS, it is much quicker to just use the url directly
            //rather than using the auto-resolve.  So we will first attempt the url, if that works
            //then we are golden otherwise we will go for the auto-resolve.
            CalendarFolder calendar = null;
            if (exchangeurl != "")
            {
                service.Url = new Uri(exchangeurl);

                try
                {
                    // Try to initialize the calendar folder object with only the folder ID.
                    calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
                }
                catch (Exception exp)
                {
                    service.TraceListener.Trace("ExchangeUrlBindFail", exp.Message);
                }
            }

            //calendar will still be null if we still have not bound correctly
            if (calendar == null)
            {
                service.AutodiscoverUrl(user, RedirectionUrlValidationCallback);
                // Try to initialize the calendar folder object with only the folder ID.
                calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
            }

            CalendarEvent cEvent = null;

            // Initialize values for the start and end times, and the number of appointments to retrieve.
            const int NUM_APPTS = 1000;

            // Set the start and end time and number of appointments to retrieve.
            CalendarView cView = new CalendarView(CalendarGlobals.StartDate, CalendarGlobals.EndDate, NUM_APPTS);

            // Limit the properties returned to the appointment's subject, start time, and end time. (Body cannot be loaded with FindAppointments, we need to do that later)
            cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.IsRecurring, AppointmentSchema.Id, AppointmentSchema.Location);
            cView.PropertySet.RequestedBodyType = BodyType.Text;

            // Retrieve a collection of appointments by using the calendar view.
            FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);

            Console.WriteLine("\nThe first " + NUM_APPTS + " appointments on your calendar from " + CalendarGlobals.StartDate.Date.ToShortDateString() +
                              " to " + CalendarGlobals.EndDate.Date.ToShortDateString() + " are: \n");

            //Now that we have found the appointments that we want, we will be able to load the body
            cView.PropertySet.Add(AppointmentSchema.Body);
            service.LoadPropertiesForItems(appointments, cView.PropertySet);
            foreach (Appointment a in appointments)
            {
                cEvent = new CalendarEvent(a.Id.ToString(), a.Start, a.End, a.Location, a.Subject, a.Body);
                events.Add(cEvent);
            }

            return events;
        }
        public async Task<AppointmentsWrapper> GetCalendarEventsInRangeAsync(DateTime startDate, DateTime endDate,
            IDictionary<string, object> calendarSpecificData)
        {
            CheckCalendarSpecificData(calendarSpecificData);


            var service = GetExchangeService(ExchangeServerSettings);

            var calendarview = new CalendarView(startDate, endDate);

            // Get Default Calendar
            var outlookAppointments = new AppointmentsWrapper();
            var exchangeAppointments = service.FindAppointments(_ewsCalendar.EntryId,
                calendarview);


            service.LoadPropertiesForItems(
                from Item item in exchangeAppointments select item,
                new PropertySet(BasePropertySet.FirstClassProperties) {RequestedBodyType = BodyType.Text});

            if (exchangeAppointments != null)
            {
                foreach (var exchangeAppointment in exchangeAppointments)
                {
                    var appointment = new Appointment(exchangeAppointment.Body, exchangeAppointment.Location,
                        exchangeAppointment.Subject, exchangeAppointment.Start, exchangeAppointment.Start)
                    {
                        AppointmentId = exchangeAppointment.Id.UniqueId,
                        AllDayEvent = exchangeAppointment.IsAllDayEvent,
                        OptionalAttendees = GetAttendees(exchangeAppointment.OptionalAttendees),
                        ReminderMinutesBeforeStart = exchangeAppointment.ReminderMinutesBeforeStart,
                        Organizer =
                            new Attendee
                            {
                                Name = exchangeAppointment.Organizer.Name,
                                Email = exchangeAppointment.Organizer.Address
                            },
                        ReminderSet = exchangeAppointment.IsReminderSet,
                        RequiredAttendees = GetAttendees(exchangeAppointment.RequiredAttendees)
                    };
                    outlookAppointments.Add(appointment);
                }
            }
            return outlookAppointments;
        }
Example #13
0
        private void bindTasks(DateTime fromDate, DateTime toDate)
        {
            List<LeadTask> tasks = null;

            Expression<Func<CRM.Data.Entities.Task, bool>> predicate = PredicateBuilder.True<CRM.Data.Entities.Task>();

            if (roleID == (int)UserRole.Administrator) {
            }
            else if ((roleID == (int)UserRole.Client || roleID == (int)UserRole.SiteAdministrator) && clientID > 0) {
                // load all tasks for client (sort of admin)

                predicate = predicate.And(LeadTask => LeadTask.creator_id == clientID);

                predicate = predicate.And(LeadTask => LeadTask.start_date >= fromDate && LeadTask.end_date <= toDate);

                // get overdue task for client
                predicate = predicate.Or(LeadTask => LeadTask.status_id == 1 && LeadTask.end_date <= toDate && LeadTask.creator_id == clientID);
            }
            else {
                // regular users

                predicate = predicate.And(LeadTask => LeadTask.start_date >= fromDate && LeadTask.end_date <= toDate);

                predicate = predicate.And(LeadTask => LeadTask.owner_id == userID);
            }

            tasks = TasksManager.GetLeadTask(predicate, fromDate, toDate);

            if (rbOn.Checked)
            {
                userID = SessionHelper.getUserId();

                CRM.Data.Entities.SecUser secUser = SecUserManager.GetByUserId(userID);
                string emailaddress = secUser.Email;
                string password = SecurityManager.Decrypt(secUser.emailPassword);
                string url = "https://" + secUser.emailHost + "/EWS/Exchange.asmx";

                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.Credentials = new WebCredentials(emailaddress, password);
                service.Url = new Uri(url);

                try
                {
                    TasksFolder tasksfolder = TasksFolder.Bind(service, WellKnownFolderName.Tasks);

                    ItemView view = new ItemView(int.MaxValue);
                    FindItemsResults<Item> OutlookTasks = tasksfolder.FindItems(view);

                    CalendarView calView = new CalendarView(fromDate, toDate);

                    FindItemsResults<Item> instanceResults = service.FindItems(WellKnownFolderName.Calendar, calView);

                    foreach (var item in instanceResults)
                    {
                        LeadTask newTask = new LeadTask();
                        Microsoft.Exchange.WebServices.Data.Appointment appointment = item as Microsoft.Exchange.WebServices.Data.Appointment;

                        newTask.creator_id = userID;
                        newTask.details = appointment.Subject;
                        newTask.end_date = appointment.End;
                        newTask.isAllDay = appointment.IsRecurring;
                        newTask.text = appointment.Subject;

                        newTask.priorityName = appointment.Importance.ToString();
                        newTask.owner_name = appointment.Organizer.Name;
                        newTask.start_date = appointment.Start;

                        tasks.Add(newTask);
                    }

                    foreach (var task in OutlookTasks)
                    {
                        task.Load();
                        Microsoft.Exchange.WebServices.Data.Task myTask = task as Microsoft.Exchange.WebServices.Data.Task;

                        LeadTask newTask = new LeadTask();
                        newTask.creator_id = userID;
                        newTask.details = ExtractHtmlInnerText(myTask.Body.Text);
                        newTask.end_date = myTask.DueDate;
                        newTask.isAllDay = myTask.IsRecurring;
                        newTask.text = myTask.Subject;
                        newTask.statusName = myTask.Status.ToString();
                        newTask.priorityName = myTask.Importance.ToString();
                        newTask.owner_name = myTask.Owner;
                        if (myTask.StartDate == null)
                            newTask.start_date = myTask.DueDate;
                        else
                            newTask.start_date = myTask.StartDate;

                        tasks.Add(newTask);
                    }

                }
                catch (Exception ex)
                {

                }
            }
            // show tasks
            gvTasks.DataSource = tasks;
            gvTasks.DataBind();
        }
        public IEnumerable<ApiCalendarModels> Get()
        {
            try
            {
                // Initialize values for the start and end times, and the number of appointments to retrieve.
                DateTime startDate = DateTime.Now;
                DateTime endDate = startDate.AddDays(30);
                const int NUM_APPTS = 1000;

                // Initialize the calendar folder object with only the folder ID. 
                ExchangeService service = new ExchangeService();

                #region Authentication

                // Set specific credentials.
                service.Credentials = new NetworkCredential("*****@*****.**", "HuyHung0912");
                #endregion

                #region Endpoint management

                // Look up the user's EWS endpoint by using Autodiscover.
                service.AutodiscoverUrl("*****@*****.**", RedirectionCallback);

                Console.WriteLine("EWS Endpoint: {0}", service.Url);
                #endregion

                CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());

                // Set the start and end time and number of appointments to retrieve.
                CalendarView cView = new CalendarView(startDate, endDate, NUM_APPTS);

                // Limit the properties returned to the appointment's subject, start time, and end time.
                cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End);

                // Retrieve a collection of appointments by using the calendar view.
                FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);

             

                var res = service.LoadPropertiesForItems(
                    from Microsoft.Exchange.WebServices.Data.Item item in appointments select item,
                    PropertySet.FirstClassProperties);

                var result = res.ToList();

                List<ApiCalendarModels> data = new List<ApiCalendarModels>();

                foreach (var item in result)
                {
                    var itemResponse = (GetItemResponse)item;

                    var appt = (Appointment)itemResponse.Item;

                   var model = new ApiCalendarModels()
                    {
                        Id = itemResponse.Item.Id.UniqueId,
                        Subject = itemResponse.Item.Subject,
                        Date = appt.Start,
                        End = appt.End,
                        Body = itemResponse.Item.Body == null ? string.Empty : itemResponse.Item.Body.Text,
                        Attendee = itemResponse.Item.DisplayTo == null ? string.Empty : itemResponse.Item.DisplayTo
                    };
                    data.Add(model);
                }
                return data;
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }

            return null;
        }
        public GetCalendarItemsResponse Execute(GetCalendarItemsRequest request)
        {
            var response = new GetCalendarItemsResponse();

            try {
                var service = ExchangeServiceConnector.GetService(request.MailboxEmail);

                //service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, request.MailboxEmail);
                service.HttpHeaders.Add("X-AnchorMailbox", request.MailboxEmail);

                // Initialize values for the start and end times, and the number of appointments to retrieve.
                DateTime startDate = DateTime.Today;
                DateTime endDate = startDate.AddDays(request.DaysToLoad);
                const int NUM_APPTS = 20;

                var mbx = new Mailbox(request.MailboxEmail);
                FolderId fid = new FolderId(WellKnownFolderName.Calendar, mbx);
                //FolderId fid = new FolderId(WellKnownFolderName.Calendar, request.MailboxEmail);
                //FolderId fid = new FolderId(WellKnownFolderName.Calendar);

                // Initialize the calendar folder object with only the folder ID.
                //CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
                CalendarFolder calendar = CalendarFolder.Bind(service, fid, new PropertySet(FolderSchema.ManagedFolderInformation, FolderSchema.ParentFolderId, FolderSchema.ExtendedProperties));
                //CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet(FolderSchema.ManagedFolderInformation, FolderSchema.ParentFolderId, FolderSchema.ExtendedProperties));

                // Set the start and end time and number of appointments to retrieve.
                CalendarView cView = new CalendarView(startDate, endDate, NUM_APPTS);

                // Limit the properties returned to the appointment's subject, start time, and end time.
                cView.PropertySet = new PropertySet(
                    AppointmentSchema.Subject,
                    AppointmentSchema.Start,
                    AppointmentSchema.End,
                    AppointmentSchema.Organizer);

                // Retrieve a collection of appointments by using the calendar view.
                FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);

                var items = new List<Models.AppointmentItem>();
                foreach (var a in appointments)
                {
                    //find appointments will only give basic properties.
                    //in order to get more properties (such as BODY), we need to call EWS again
                    //Appointment appointmentDetailed = Appointment.Bind(service, a.Id, new PropertySet(BasePropertySet.FirstClassProperties) { RequestedBodyType = BodyType.Text });

                    items.Add(new Models.AppointmentItem
                    {
                        Start = a.Start,
                        End = a.End,
                        Subject = a.Subject,
                        Organizer = a.Organizer.Name
                    });
                }

                response.StartDate = startDate;
                response.EndDate = endDate;
                response.Appointments = items;
                response.Success = true;
            }
            catch (Exception e)
            {
                response.ErrorMessage = e.ToString();
            }

            return response;
        }
        /// <summary>
        /// Obtains a list of appointments by searching the contents of this folder and performing recurrence expansion
        /// for recurring appointments. Calling this method results in a call to EWS.
        /// </summary>
        /// <param name="view">The view controlling the range of appointments returned.</param>
        /// <returns>An object representing the results of the search operation.</returns>
        public FindItemsResults<Appointment> FindAppointments(CalendarView view)
        {
            EwsUtilities.ValidateParam(view, "view");

            ServiceResponseCollection<FindItemResponse<Appointment>> responses = this.InternalFindItems<Appointment>(
                (SearchFilter)null,
                view,
                null /* groupBy */);

            return responses[0].Results;
        }