/// <summary> /// 获取当前用户指定时间段的会议列表 /// </summary> /// <param name="start">开始时间</param> /// <param name="end">结束时间</param> /// <param name="config"></param> /// <returns>会议列表</returns> public static List <AppointmentProperty> GetAppointment(DateTime start, DateTime end, ExchangeAdminConfig config) { InitializeEws(config); //要返回的会议列表 List <AppointmentProperty> appointments = new List <AppointmentProperty>(); //要获取的时间段 CalendarView cv = new CalendarView(start, end); FindItemsResults <Appointment> aps = Service.FindAppointments(WellKnownFolderName.Calendar, cv); foreach (Appointment ap in aps) { //定义需要的会议属性 PropertyDefinitionBase[] bas = new PropertyDefinitionBase[] { ItemSchema.Id, AppointmentSchema.Start, AppointmentSchema.End, ItemSchema.Subject, ItemSchema.Body, AppointmentSchema.RequiredAttendees, AppointmentSchema.Location }; PropertySet props = new PropertySet(bas); Appointment email = Appointment.Bind(Service, ap.Id, props); AppointmentProperty appointment = new AppointmentProperty(); appointment.Start = email.Start; appointment.End = email.End; appointment.Body = email.Body; appointment.Subject = email.Subject; appointment.Location = email.Location; appointment.Attendees = email.RequiredAttendees.Select(p => p.Address).ToList(); appointment.ID = email.Id; appointments.Add(appointment); } return(appointments); }
public AppointmentGroup GetNextAppointments() { try { var newAppointments = new AppointmentGroup(); var service = new ExchangeService(); service.UseDefaultCredentials = true; service.AutodiscoverUrl(UserPrincipal.Current.EmailAddress); DateTime from = DateTime.Now.AddMinutes(-5); DateTime to = DateTime.Today.AddDays(1); IEnumerable<Appointment> appointments = service.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(from, to)) .Select(MakeAppointment); newAppointments.Next = appointments.Where(o => o != null && o.Start >= DateTime.Now) .OrderBy(o => o.Start).ToList(); nextAppointments = newAppointments; return newAppointments; } catch (Exception e) { Trace.WriteLine(e.ToString()); return nextAppointments; } }
public AppointmentGroup GetNextAppointments() { try { var newAppointments = new AppointmentGroup(); var service = new ExchangeService(); service.UseDefaultCredentials = true; service.AutodiscoverUrl(UserPrincipal.Current.EmailAddress); DateTime from = DateTime.Now.AddMinutes(-5); DateTime to = DateTime.Today.AddDays(1); IEnumerable <Appointment> appointments = service.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(from, to)) .Select(MakeAppointment); newAppointments.Next = appointments.Where(o => o != null && o.Start >= DateTime.Now) .OrderBy(o => o.Start).ToList(); nextAppointments = newAppointments; return(newAppointments); } catch (Exception e) { Trace.WriteLine(e.ToString()); return(nextAppointments); } }
public Collection <Appointment> FindRecurringCalendarItems(ExchangeService service, DateTime startSearchDate, DateTime endSearchDate) { // Instantiate a collection to hold occurrences and exception calendar items. Collection <Appointment> foundAppointments = new Collection <Appointment>(); // Create a calendar view to search the calendar folder and specify the properties to return. CalendarView calView = new CalendarView(startSearchDate, endSearchDate, 50); calView.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.IsRecurring, AppointmentSchema.AppointmentType); // Retrieve a collection of calendar items. FindItemsResults <Appointment> findResults = service.FindAppointments(WellKnownFolderName.Calendar, calView); // Add all calendar items in your view that are occurrences or exceptions to your collection. foreach (Appointment appt in findResults.Items) { if (appt.AppointmentType == AppointmentType.Occurrence || appt.AppointmentType == AppointmentType.Exception) { foundAppointments.Add(appt); } else { Console.WriteLine("Discarding calendar item of type {0}.", appt.AppointmentType); } } return(foundAppointments); }
public static Appointment[] Appointments(DateTime From, DateTime To, string mailbox) { ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // Replace this line with code to validate server certificate. return(true); }; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange)) { service.AutodiscoverUrl(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, (string redirectionUrl) => { return(true); }); } else { service.Url = new Uri("https://" + HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange + "/ews/exchange.asmx"); } service.Credentials = new NetworkCredential(HAP.Web.Configuration.hapConfig.Current.AD.User, HAP.Web.Configuration.hapConfig.Current.AD.Password, HAP.Web.Configuration.hapConfig.Current.AD.UPN); FolderId fid = new FolderId(WellKnownFolderName.Calendar, new Mailbox(mailbox)); return(service.FindAppointments(fid, new CalendarView(From, To.AddDays(1))).ToArray()); }
// // GET: /Calendario/ public ActionResult VistaCalendario() { //ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); //service.Credentials = new WebCredentials("*****@*****.**", "Cr1ter14_2015"); //service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback); ExchangeService service = (ExchangeService)Session["Office365"]; FindItemsResults <Appointment> foundAppointments = service.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(DateTime.Now, DateTime.Now.AddYears(1), 5)); Calendario calendario = new Calendario(); List <ItemCalendario> icalendario = new List <ItemCalendario>(); foreach (Appointment app in foundAppointments) { ItemCalendario i = new ItemCalendario(); i.Asunto = app.Subject; i.FechaHoraDesde = app.Start; i.FechaHoraHasta = app.End; i.Ubicacion = app.Location; icalendario.Add(i); } calendario.ListaItemCalendario = icalendario; return(PartialView("_VistaCalendario", calendario)); }
public void PopulateLVRelatedExceptions(ExchangeService service, Appointment recurrMaster ) { Collection <Appointment> foundAppointments = new Collection <Appointment>(); CalendarView calView = new CalendarView(recurrMaster.Start, recurrMaster.End); calView.PropertySet = InstanceCalProps; FindItemsResults <Appointment> findResults = service.FindAppointments(recurrMaster.ParentFolderId, calView); ListViewItem oListItem = null; Appointment oAppt = null; // Add all calendar items in your view that are occurrences or exceptions to your collection. foreach (Appointment appt in findResults.Items) { if (appt.AppointmentType == AppointmentType.Exception) { service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. oAppt = Appointment.Bind(service, appt.Id, BasicCalProps); oListItem = new ListViewItem(oAppt.Id.UniqueId, 0); oListItem.SubItems.Add(oAppt.ItemClass); oListItem.SubItems.Add(oAppt.AppointmentType.ToString()); oListItem.SubItems.Add(oAppt.Subject); oListItem.SubItems.Add(oAppt.Start.ToString()); oListItem.SubItems.Add(oAppt.End.ToString()); oListItem.Tag = oAppt.Id.UniqueId; lvItems.Items.AddRange(new ListViewItem[] { oListItem }); oListItem = null; } } }
public bool CheckExchangeServiceForProvidedUserDetails(string userEmail, string userPassword) { try { ExchangeService service = new ExchangeService(); // Set specific credentials. service.Credentials = new NetworkCredential(userEmail, userPassword); // Look up the user's EWS endpoint by using Autodiscover. //service.AutodiscoverUrl(userEmailAddress, RedirectionCallback); service.Url = new Uri("https://mail.civica.com/ews/exchange.asmx"); FolderId CalendarFolderId = new FolderId(WellKnownFolderName.Calendar, userEmail); CalendarView cv = new CalendarView(DateTime.Now, DateTime.Now.AddHours(1)); service.FindAppointments(CalendarFolderId, cv); return(true); } catch (Microsoft.Exchange.WebServices.Data.ServiceRequestException ex) { return(false); } }
public static Appointment[] Appointments(DateTime From, DateTime To) { ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // Replace this line with code to validate server certificate. return(true); }; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange)) { service.AutodiscoverUrl(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, (string redirectionUrl) => { return(true); }); } else { service.Url = new Uri("https://" + HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange + "/ews/exchange.asmx"); } HAP.AD.User u = ((HAP.AD.User)Membership.GetUser()); if (HAP.Web.Configuration.hapConfig.Current.AD.AuthenticationMode == Configuration.AuthMode.Forms && string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser)) { HttpCookie token = HttpContext.Current.Request.Cookies["token"]; if (token == null) { throw new AccessViolationException("Token Cookie Missing, user not logged in correctly"); } service.Credentials = new NetworkCredential((hapConfig.Current.SMTP.EWSUseEmailoverAN ? u.Email : u.UserName), TokenGenerator.ConvertToPlain(token.Value), HAP.Web.Configuration.hapConfig.Current.AD.UPN); } else { if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser)) { u.ImpersonateContained(); service.UseDefaultCredentials = true; //service.Credentials = CredentialCache.DefaultNetworkCredentials; } else { if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain)) { service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword); } else { service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain); } service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, u.Email); } } Appointment[] app = service.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(From, To.AddDays(1))).ToArray(); if (HAP.Web.Configuration.hapConfig.Current.AD.AuthenticationMode == Configuration.AuthMode.Windows || !string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser)) { u.EndContainedImpersonate(); } return(app); }
/// <summary> /// 获取exchange 会议室记录 /// </summary> public static List <MeetRoomEntity> GetRoomList(ExchangeAdminConfig config, DateTime startTime, DateTime endDateTime) { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); service.Credentials = new NetworkCredential(config.AdminAccount, config.AdminPwd); service.Url = new Uri($"http://{config.ServerIpOrDomain}/ews/exchange.asmx"); service.UseDefaultCredentials = false; List <MeetRoomEntity> result = new List <MeetRoomEntity>(); EmailAddressCollection listOfRoomList = service.GetRoomLists(); foreach (EmailAddress address in listOfRoomList) { var roomAddresses = service.GetRooms(address); foreach (EmailAddress roomAddress in roomAddresses) { MeetRoomEntity roomEntity = new MeetRoomEntity() { StartDate = startTime, EndDate = endDateTime, MeetEmail = roomAddress.Address, Name = roomAddress.Name }; CalendarView calendarView = new CalendarView(startTime, endDateTime); FolderId folderId = new FolderId(WellKnownFolderName.Calendar, roomAddress.Address); var roomAppts = service.FindAppointments(folderId, calendarView); List <MeetInfoEntity> meets = new List <MeetInfoEntity>(); if (roomAppts.Items.Count > 0) { foreach (Appointment appt in roomAppts) { meets.Add(new MeetInfoEntity { StartDate = appt.Start, EndDate = appt.End, Subject = appt.Subject }); } roomEntity.Meetings = meets; } result.Add(roomEntity); } } return(result); // listOfRoomList==0 执行下面语句 把会议室归类 // $members=Get-Mailbox -Filter {(RecipientTypeDetails -eq "RoomMailbox")} //New - DistributionGroup - Name "Poole-Rooms" - RoomList - Members $Members // 最好可能还需要设置权限 // Add-MailboxFolderPermission -Identity [email protected]:\Calendar -AccessRights Owner -User [email protected] }
public bool ActivityExists(string uniqueId, DateTime startDate, DateTime endDate) { bool result = false; CalendarView c = new CalendarView(startDate, endDate); List <Appointment> appts = _service.FindAppointments(WellKnownFolderName.Calendar, c).ToList <Appointment>(); foreach (Appointment a in appts) { a.Load(); if (a.Body.Text.Contains(uniqueId)) { // Match Found result = true; break; } } return(result); }
public Appointments(string mail, ExchangeService service) { try { CalendarView calView = new CalendarView( DateTime.Now, // von Global.LetzterTagDesSchuljahres) // bis { PropertySet = new PropertySet( BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.IsRecurring, AppointmentSchema.AppointmentType, AppointmentSchema.Categories) }; FindItemsResults <Appointment> findResults = service.FindAppointments( WellKnownFolderName.Calendar, calView); List <Appointment> relevanteAppointments = new List <Appointment>(); Console.WriteLine("Existierende Appointments für " + mail + ":"); foreach (var appointment in findResults.Items) { // Alle relevanten Appointments für diese Zielperson werden in eine Liste geladen, ... appointment.Load(); // ... um die Eigenschaften von Appointment und Termin vergleichen zu können. if (appointment.Categories.Contains("ZulassungskonferenzenBC")) { // Wenn Subject oder Body null sind, werden sie durch "" ersetzt. appointment.Subject = appointment.Subject ?? ""; appointment.Body = appointment.Body ?? ""; this.Add(appointment); Console.WriteLine("[Ist ] " + appointment.Subject.PadRight(30) + appointment.Start + "-" + appointment.End.ToShortTimeString()); } } } catch (Exception ex) { Console.WriteLine("Fehler beim Lehrer mit der Adresse " + mail + "\n" + ex.ToString()); throw new Exception("Fehler beim Lehrer mit der Adresse " + mail + "\n" + ex.ToString()); } }
//gavdcodeend 02 //gavdcodebegin 03 static void FindAppointmentsByDate(ExchangeService ExService) { FindItemsResults <Appointment> allAppointments = ExService.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(DateTime.Now, DateTime.Now.AddDays(7))); foreach (Appointment oneAppointment in allAppointments) { Console.WriteLine("Subject: " + oneAppointment.Subject); Console.WriteLine("Start: " + oneAppointment.Start); Console.WriteLine("Duration: " + oneAppointment.Duration); } }
// URI like http://.../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")); ExchangeService sv = new ExchangeService(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 }); }
private static FindItemsResults <Appointment> LoadExistingAppointments(Season season, ExchangeService service, FolderId dynamoFolderId) { var calendarView = new CalendarView(new DateTime(season.StartYear, 1, 1), new DateTime(season.EndYear, 12, 31)); var existingAppointments = service.FindAppointments(dynamoFolderId, calendarView); foreach (var existingAppointment in existingAppointments) { existingAppointment.Load(); } return(existingAppointments); }
private static List <Appointment> GetAllMeetings(List <AttendeeInfo> rooms, ExchangeService service, TimeWindow timeWindow) { List <Appointment> appointments = new List <Appointment>(); List <AttendeeInfo> attend = new List <AttendeeInfo>(); foreach (AttendeeInfo inf in rooms) { FolderId folderid = new FolderId(WellKnownFolderName.Calendar, new Mailbox(inf.SmtpAddress)); FindItemsResults <Appointment> aps = service.FindAppointments(folderid, new CalendarView(timeWindow.StartTime, timeWindow.EndTime)).Result; appointments.AddRange(aps.Items.ToList()); } return(appointments); }
private List <Appointment> GetAppointments(ExchangeService service, List <AttendeeInfo> rooms, DateTime from, DateTime to) { List <Appointment> appointments = new List <Appointment>(); List <AttendeeInfo> attend = new List <AttendeeInfo>(); foreach (AttendeeInfo inf in rooms) { FolderId folderid = new FolderId(WellKnownFolderName.Calendar, new Mailbox(inf.SmtpAddress)); FindItemsResults <Appointment> aps = service.FindAppointments(folderid, new CalendarView(from, to)).Result; appointments.AddRange(aps.Items.ToList()); } return(appointments); }
public static EWSAppointmentInfo[] AppointmentsInfoWeek(string mailbox) { ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // Replace this line with code to validate server certificate. return(true); }; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange)) { service.AutodiscoverUrl(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, (string redirectionUrl) => { return(true); }); } else { service.Url = new Uri("https://" + HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange + "/ews/exchange.asmx"); } if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain)) { service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword); } else { service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain); } FolderId fid = new FolderId(WellKnownFolderName.Calendar, new Mailbox(mailbox)); List <EWSAppointmentInfo> s = new List <EWSAppointmentInfo>(); foreach (Appointment a in service.FindAppointments(fid, new CalendarView(DateTime.Now, DateTime.Now.AddDays(14)))) { s.Add(new EWSAppointmentInfo { Start = a.Start.ToString(), End = a.End.ToString(), Location = a.Location, Subject = a.Subject }); try { a.Load(); string b = a.Body.Text; Regex r = new Regex("<html>(?:.|\n|\r)+?<body>", RegexOptions.IgnoreCase); b = r.Replace(b, ""); b = new Regex("</body>(?:.|\n|\r)+?</html>(?:.|\n|\r)+?", RegexOptions.IgnoreCase).Replace(b, ""); s.Last().Body = b; } catch { } } return(s.ToArray()); }
// 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 }; }
public void PopulateLVRelatedOccurrences(ExchangeService service, Appointment recurrMaster ) { Collection <Appointment> foundAppointments = new Collection <Appointment>(); //DateTime oEnd = null; //DateTime oStart = recurrMaster.Recurrence.StartDate; //if (recurrMaster.Recurrence.EndDate != null) // oEnd = recurrMaster.Recurrence.EndDate; // // string sInfo = "Recurring Master: " + appt.Subject + "(" + appt.Recurrence.StartDate.ToString() + " - " ; //if (appt.Recurrence.NumberOfOccurrences == null && appt.Recurrence.EndDate == null) // sInfo += "Warning - This pattern has no end."; //if (appt.Recurrence.NumberOfOccurrences != null) // sInfo += "This has a fixed number of " + appt.Recurrence.NumberOfOccurrences.ToString() + " instances."; // CalendarView calView = new CalendarView(recurrMaster.Start, recurrMaster.End); calView.PropertySet = InstanceCalProps; FindItemsResults <Appointment> findResults = service.FindAppointments(recurrMaster.ParentFolderId, calView); ListViewItem oListItem = null; Appointment oAppt = null; // Add all calendar items in your view that are occurrences or exceptions to your collection. foreach (Appointment appt in findResults.Items) { if (appt.AppointmentType == AppointmentType.Occurrence) { service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. oAppt = Appointment.Bind(service, appt.Id, BasicCalProps); oListItem = new ListViewItem(oAppt.Id.UniqueId, 0); oListItem.SubItems.Add(oAppt.ItemClass); oListItem.SubItems.Add(oAppt.AppointmentType.ToString()); oListItem.SubItems.Add(oAppt.Subject); oListItem.SubItems.Add(oAppt.Start.ToString()); oListItem.SubItems.Add(oAppt.End.ToString()); oListItem.Tag = oAppt.Id.UniqueId; lvItems.Items.AddRange(new ListViewItem[] { oListItem }); oListItem = null; } } }
private IList <IRoom> FillRoom(string room, CalendarView cv) { IList <IRoom> roomList = FillCalendarDay(); String mailboxToAccess = room; FolderId calendarFolderId = new FolderId(WellKnownFolderName.Calendar, mailboxToAccess); IList <Appointment> appointments = _exchangeService.FindAppointments(calendarFolderId, cv).ToList(); foreach (var appointment in appointments) { IRoom result = new Room(); result.Organizer = appointment.Organizer.Name; result.Subject = string.IsNullOrEmpty(appointment.Subject) ? "No subject" : appointment.Subject; result.Start = appointment.Start.ToShortTimeString(); result.End = appointment.End.ToShortTimeString(); result.IsFree = false; roomList.Add(result); } return(roomList); }
public static string[] Appointments(string mailbox) { ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // Replace this line with code to validate server certificate. return(true); }; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange)) { service.AutodiscoverUrl(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, (string redirectionUrl) => { return(true); }); } else { service.Url = new Uri("https://" + HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange + "/ews/exchange.asmx"); } if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain)) { service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword); } else { service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain); } FolderId fid = new FolderId(WellKnownFolderName.Calendar, new Mailbox(mailbox)); List <string> s = new List <string>(); foreach (Appointment a in service.FindAppointments(fid, new CalendarView(DateTime.Now, DateTime.Now.AddDays(1)))) { s.Add(a.Subject + "<br />" + (a.Start.Date > DateTime.Now.Date ? "Tomorrow: " : "") + ((a.Start.AddDays(1) == a.End) ? "All Day" : a.Start.AddDays(5) == a.End ? "All Week" : (a.Start.ToShortTimeString() + " - " + a.End.ToShortTimeString()))); } return(s.ToArray()); }
private void FillAllRoomsAvailability(ExchangeService service, IList <Room> rooms, DateTime startDate, DateTime endtDate, ref Dictionary <string, FindItemsResults <Appointment> > fapts) { if (fapts == null) { fapts = new Dictionary <string, FindItemsResults <Appointment> >(); } foreach (Room room in rooms) { string key = room.Email + startDate.ToString("ddMMyyyy") + endtDate.ToString("ddMMyyyy"); FolderId CalendarFolderId = new FolderId(WellKnownFolderName.Calendar, room.Email); CalendarView cv = new CalendarView(startDate, endtDate); try { FindItemsResults <Appointment> fapt = service.FindAppointments(CalendarFolderId, cv); fapts.Add(key, fapt); } catch (Exception ex) { fapts.Add(key, null); } } }
internal static FindItemsResults <Appointment> LoadCallendar() { ExchangeService service = ExchangeHelper.GetExchangeServiceConnection(); DateTime DateForImport = String.IsNullOrEmpty(WebConfigurationManager.AppSettings["DateForImport"]) ? DateTime.Today : DateTime.Parse(WebConfigurationManager.AppSettings["DateForImport"]); // Берем с часу ночи, чтобы не попадали мероприятия предидущего дня DateTime startDate = DateForImport.AddHours(1); DateTime endDate = startDate.AddDays(1); const int NUM_APPTS = 25; // FindItem results should be requested in batches of 25. // Initialize the calendar folder object with only the folder ID. //CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar); // 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(BasePropertySet.IdOnly); // Retrieve a collection of appointments by using the calendar view. // FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView); FindItemsResults <Appointment> findResults = service.FindAppointments(WellKnownFolderName.Calendar, cView); if (findResults != null && findResults.TotalCount > 0) { service.LoadPropertiesForItems(from Item item in findResults select item, new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.Location, AppointmentSchema.Subject, AppointmentSchema.Categories)); } return(findResults); }
private async Task <CalendarModel> InternalGetCalendar(string id, DateTime start, DateTime end) { start = start.Date; end = end.Date; var credentials = credentialProvider.GetCredentials(id); if (credentials == null) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "")); } var calendarModel = new CalendarModel { Owner = id, }; switch (credentials.Type) { case "EWS": var ewsService = new ExchangeService { Credentials = new WebCredentials(credentials.Username, credentials.Password, credentials.Domain), Url = new Uri(credentials.ServiceUrl) }; var week = ewsService.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(start, end.AddDays(1))); calendarModel.Appointments = week.Select(a => new AppointmentModel { Subject = a.Subject, StartTime = a.Start.ToUniversalTime(), EndTime = a.End.ToUniversalTime(), Duration = a.Duration, IsPrivate = a.Sensitivity == Sensitivity.Private || a.Sensitivity == Sensitivity.Confidential }); break; case "ICS": var cache = calendarCache.GetCalendar(id); if (cache != null) { var icsServiceResponse = await icsService.GetIcsContent(credentials.ServiceUrl, cache.ETag); if (icsServiceResponse.NotModified) { calendarModel.Appointments = cache.CalendarModel.Appointments; } else { calendarModel.Appointments = icsServiceResponse.Appointments; calendarCache.PutCalendar(id, new CalendarCacheEntry(id) { CalendarModel = calendarModel, ETag = icsServiceResponse.ETag }); } } else { var icsResponse = await icsService.GetIcsContent(credentials.ServiceUrl, string.Empty); calendarModel.Appointments = icsResponse.Appointments; calendarCache.PutCalendar(id, new CalendarCacheEntry(id) { CalendarModel = calendarModel, ETag = icsResponse.ETag }); } break; default: throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "")); } // Now only return the appointments in the requested range return(new CalendarModel { Owner = calendarModel.Owner, Appointments = calendarModel.Appointments .Where(a => a != null && a.StartTime.Date >= start && a.StartTime.Date <= end) .OrderBy(a => a.StartTime) }); }
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; }
static void Main(string[] args) { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); // service.UseDefaultCredentials = true; //service.Credentials = new WebCredentials(CredentialCache.DefaultNetworkCredentials); //service.TraceEnabled = true; service.Credentials = new WebCredentials("*****@*****.**", "denim@123"); service.Url = new Uri("https://exchange-server.exchange.bluejeansdev.com/EWS/Exchange.asmx"); //Certification bypass ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; DateTime startDate = DateTime.Now; DateTime endDate = startDate.AddDays(30); //Specify number of meetings to see const int NUM_APPTS = 5; /* Code to show all calendars of a user */ Folder rootfolder = Folder.Bind(service, WellKnownFolderName.Calendar); Console.WriteLine("The " + rootfolder.DisplayName + " has " + rootfolder.ChildFolderCount + " child folders."); // A GetFolder operation has been performed. // Now do something with the folder, such as display each child folder's name and ID. rootfolder.Load(); foreach (Folder folder in rootfolder.FindFolders(new FolderView(100))) { Console.WriteLine("\nName: " + folder.DisplayName + "\n Id: " + folder.Id); // Initialize the calendar folder object with only the folder ID. CalendarFolder calendar = CalendarFolder.Bind(service, folder.Id, 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); Console.WriteLine("\nThe first " + NUM_APPTS + " appointments on your calendar from " + startDate.Date.ToShortDateString() + " to " + endDate.Date.ToShortDateString() + " are: \n"); Console.WriteLine(appointments.TotalCount); foreach (Appointment a in appointments) { Console.Write("Subject: " + a.Subject.ToString() + " "); Console.Write("Start: " + a.Start.ToString() + " "); Console.Write("End: " + a.End.ToString()); Console.WriteLine(); } } Console.WriteLine("Get all shared calendars"); /*Code to get meetings from all rooms*/ Dictionary <string, string> result = GetSharedCalendarFolders(service, "*****@*****.**"); foreach (KeyValuePair <string, string> kvp in result) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); FolderId te = new FolderId(WellKnownFolderName.Calendar, kvp.Value); DateTime start = DateTime.Now; DateTime end = DateTime.Now.AddDays(30); CalendarView view = new CalendarView(start, end); foreach (Appointment a in service.FindAppointments(te, view)) { Console.Write("Subject: " + a.Subject.ToString() + " "); Console.Write("Start: " + a.Start.ToString() + " "); Console.Write("End: " + a.End.ToString()); Console.WriteLine(); } } Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
public static bool LoadCalendarInstances(ExchangeService oExchangeService, FolderId oFolder, ref ListView oListView, DateTime oFromDateTime, DateTime oToDateTime) { bool bRet = false; // Configure ListView before adding data. oListView.Clear(); oListView.View = View.Details; oListView.GridLines = true; oListView.Columns.Add("Subject", 200, HorizontalAlignment.Left); oListView.Columns.Add("Location", 100, HorizontalAlignment.Left); oListView.Columns.Add("From", 150, HorizontalAlignment.Left); oListView.Columns.Add("To", 150, HorizontalAlignment.Left); oListView.Columns.Add("IsRecurring", 80, HorizontalAlignment.Left); oListView.Columns.Add("AppointmentType", 100, HorizontalAlignment.Left); oListView.Columns.Add("Id", 100, HorizontalAlignment.Left); oListView.Columns.Add("UniqueId", 250, HorizontalAlignment.Left); oListView.Columns.Add("ChangeKey", 250, HorizontalAlignment.Left); try { // http://msdn.microsoft.com/en-us/library/dd633700(EXCHG.80).aspx try { //http://msdn.microsoft.com/en-us/library/dd633700(EXCHG.80).aspx //SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection(); //searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, new DateTime(2009, 1, 1))); CalendarView oCalendarView = new CalendarView(oFromDateTime, oToDateTime); oCalendarView.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Location, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.IsRecurring, AppointmentSchema.AppointmentType, AppointmentSchema.ItemClass ); //oView.OrderBy.Add(AppointmentSchema.Start, SortDirection.Descending); FindItemsResults <Appointment> findResults = oExchangeService.FindAppointments(oFolder, oCalendarView); ListViewItem oListItem = null; foreach (Appointment oApointment in findResults) { oListItem = new ListViewItem(oApointment.Subject, 0); oListItem.SubItems.Add(oApointment.Location); oListItem.SubItems.Add(oApointment.Start.ToString()); oListItem.SubItems.Add(oApointment.End.ToString()); oListItem.SubItems.Add(oApointment.IsRecurring.ToString()); oListItem.SubItems.Add(oApointment.AppointmentType.ToString()); oListItem.SubItems.Add(oApointment.Id.UniqueId); oListItem.SubItems.Add(oApointment.Id.ChangeKey); oListItem.Tag = new ItemTag(oApointment.Id, oApointment.ItemClass); oListView.Items.AddRange(new ListViewItem[] { oListItem }); oListItem = null; } bRet = true; } catch (Exception ex1) { MessageBox.Show("Error while doing FindItems: " + ex1.ToString()); bRet = false; } } catch (Exception ex2) { MessageBox.Show("Error while binding to folder prior to calling FindItems: " + ex2.ToString()); bRet = false; } return(bRet); }
/// <summary> /// /// </summary> /// <returns></returns> public static ObservableCollection <ExchangeData> GetUserAppointments() { ObservableCollection <ExchangeData> lstData = new ObservableCollection <ExchangeData>(); try { if (_globalService == null) { _globalService = GetExchangeServiceObject(new TraceListner()); } if (!_globalService.HttpHeaders.ContainsKey("X-AnchorMailbox")) { _globalService.HttpHeaders.Add("X-AnchorMailbox", User); } else { _globalService.HttpHeaders["X-AnchorMailbox"] = User; } _globalService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, User); // AppointmentSchema.Id PropertySet basicProps = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Start, AppointmentSchema.ICalUid, ItemSchema.Subject, ItemSchema.Id, AppointmentSchema.Organizer, ItemSchema.Categories); DateTime dtStart = DateTime.Now.AddDays(BackDays); CalendarView calView = new CalendarView(dtStart, dtStart.AddYears(2)) { Traversal = ItemTraversal.Shallow, PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Start), MaxItemsReturned = 500 }; List <Appointment> appointments = new List <Appointment>(); FindItemsResults <Appointment> userAppointments = _globalService.FindAppointments(WellKnownFolderName.Calendar, calView); if ((userAppointments != null) && (userAppointments.Any())) { appointments.AddRange(userAppointments); while (userAppointments.MoreAvailable) { calView.StartDate = appointments.Last().Start; userAppointments = _globalService.FindAppointments(WellKnownFolderName.Calendar, calView); appointments.AddRange(userAppointments); } ServiceResponseCollection <ServiceResponse> response = _globalService.LoadPropertiesForItems(appointments, basicProps); if (response.OverallResult != ServiceResult.Success) // property load not success { return(null); } if (appointments?.Count > 0) { foreach (Appointment item in appointments) { lstData.Add(new ExchangeData { UniqueId = item.Id.UniqueId, StartDate = item.Start.ToString("dd-MM-yyyy HH:mm"), Subject = item.Subject, Organizer = item.Organizer.Address, Categories = item.Categories.ToString(), IsSelected = (item.Subject.StartsWith("Canceled:", StringComparison.OrdinalIgnoreCase) || item.Subject.StartsWith("Abgesagt:", StringComparison.OrdinalIgnoreCase)) }); } //group by with Subject, start date var duplicates = from p in lstData.Where(p => !p.IsSelected) group p by new { p.Subject, p.StartDate } into q where q.Count() > 1 select new ExchangeData() { Subject = q.Key.Subject, StartDate = q.Key.StartDate }; var exchangeDatas = duplicates as ExchangeData[] ?? duplicates.ToArray(); if (exchangeDatas?.Length > 0) { foreach (var item in lstData.Where(p => !p.IsSelected)) { if (exchangeDatas.Any(p => string.Equals(p.Subject, item.Subject) && string.Equals(p.StartDate, item.StartDate))) { item.IsSelected = true; } } } } } } catch (Exception e) { WriteLog(e.Message); } return(lstData); }
public static string[] Appointments() { ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // Replace this line with code to validate server certificate. return(true); }; System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange)) { service.AutodiscoverUrl(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, (string redirectionUrl) => { return(true); }); } else { service.Url = new Uri("https://" + HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange + "/ews/exchange.asmx"); } HAP.AD.User u = ((HAP.AD.User)Membership.GetUser()); if (HAP.Web.Configuration.hapConfig.Current.AD.AuthenticationMode == Configuration.AuthMode.Forms && string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser)) { HttpCookie token = HttpContext.Current.Request.Cookies["token"]; if (token == null) { throw new AccessViolationException("Token Cookie Missing, user not logged in correctly"); } service.Credentials = new NetworkCredential((hapConfig.Current.SMTP.EWSUseEmailoverAN ? u.Email : u.UserName), TokenGenerator.ConvertToPlain(token.Value), HAP.Web.Configuration.hapConfig.Current.AD.UPN); } else { if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser)) { u.ImpersonateContained(); service.UseDefaultCredentials = true; //service.Credentials = CredentialCache.DefaultNetworkCredentials; } else { if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain)) { service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword); } else { service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain); } service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, u.Email); } } List <string> s = new List <string>(); foreach (Appointment a in service.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(DateTime.Now, DateTime.Now.AddDays(1)))) { s.Add(a.Subject + "<br />" + (a.Start.Date > DateTime.Now.Date ? "Tomorrow: " : "") + ((a.Start.AddDays(1) == a.End) ? "All Day" : a.Start.AddDays(5) == a.End ? "All Week" : (a.Start.ToShortTimeString() + " - " + a.End.ToShortTimeString()))); } if (HAP.Web.Configuration.hapConfig.Current.AD.AuthenticationMode == Configuration.AuthMode.Windows || !string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser)) { u.EndContainedImpersonate(); } return(s.ToArray()); }
private IEnumerable <appointment> getAppointment(ExchangeService service) { if (AppointmentID.Equals(String.Empty)) { FolderId fid = new FolderId(WellKnownFolderName.Calendar); if (!Calendar.Equals(String.Empty)) { FindFoldersResults results = service.FindFolders(WellKnownFolderName.Root, new FolderView(int.MaxValue)); foreach (Folder f in results) { if (f.DisplayName.Equals(Calendar)) { fid = f.Id; } } } FindItemsResults <Appointment> appResults = service.FindAppointments(fid, new CalendarView(Convert.ToDateTime(StartDate), Convert.ToDateTime(EndDate))); foreach (Appointment app in appResults) { String OptionalAttendees = String.Empty; foreach (Attendee person in app.OptionalAttendees) { if (OptionalAttendees.Equals(String.Empty)) { OptionalAttendees = person.ToString(); } else { OptionalAttendees += "," + person.ToString(); } } String RequiredAttendees = String.Empty; foreach (Attendee person in app.OptionalAttendees) { if (RequiredAttendees.Equals(String.Empty)) { RequiredAttendees = person.ToString(); } else { RequiredAttendees += "," + person.ToString(); } } String Subject = String.Empty; String Body = String.Empty; String Start = String.Empty; String End = String.Empty; String location = String.Empty; String Id = String.Empty; String ParentFolderId = String.Empty; try { Subject = app.Subject.ToString(); } catch { } try { Body = app.Body.ToString(); } catch { } try { Start = app.Start.ToString(); } catch { } try { End = app.End.ToString(); } catch { } try { location = app.Location; } catch { } try { Id = app.Id.ToString(); } catch { } try { ParentFolderId = app.ParentFolderId.ToString(); } catch { } yield return(new appointment(Subject, Body, Start, End, location, RequiredAttendees, OptionalAttendees, Id, ParentFolderId)); } } else { Appointment app = Appointment.Bind(service, AppointmentID); String OptionalAttendees = String.Empty; foreach (Attendee person in app.OptionalAttendees) { if (OptionalAttendees.Equals(String.Empty)) { OptionalAttendees = person.ToString(); } else { OptionalAttendees += "," + person.ToString(); } } String RequiredAttendees = String.Empty; foreach (Attendee person in app.OptionalAttendees) { if (RequiredAttendees.Equals(String.Empty)) { RequiredAttendees = person.ToString(); } else { RequiredAttendees += "," + person.ToString(); } } String Subject = String.Empty; String Body = String.Empty; String Start = String.Empty; String End = String.Empty; String location = String.Empty; String Id = String.Empty; String ParentFolderId = String.Empty; try { Subject = app.Subject.ToString(); } catch { } try { Body = app.Body.ToString(); } catch { } try { Start = app.Start.ToString(); } catch { } try { End = app.End.ToString(); } catch { } try { location = app.Location; } catch { } try { Id = app.Id.ToString(); } catch { } try { ParentFolderId = app.ParentFolderId.ToString(); } catch { } yield return(new appointment(Subject, Body, Start, End, location, RequiredAttendees, OptionalAttendees, Id, ParentFolderId)); } }
private async Task<CalendarModel> InternalGetCalendar(string id, DateTime start, DateTime end) { start = start.Date; end = end.Date; var credentials = credentialProvider.GetCredentials(id); if (credentials == null) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "")); var calendarModel = new CalendarModel { Owner = id, }; switch (credentials.Type) { case "EWS": var ewsService = new ExchangeService { Credentials = new WebCredentials(credentials.Username, credentials.Password, credentials.Domain), Url = new Uri(credentials.ServiceUrl) }; var week = ewsService.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(start, end.AddDays(1))); calendarModel.Appointments = week.Select(a => new AppointmentModel { Subject = a.Subject, StartTime = a.Start.ToUniversalTime(), EndTime = a.End.ToUniversalTime(), Duration = a.Duration, IsPrivate = a.Sensitivity == Sensitivity.Private || a.Sensitivity == Sensitivity.Confidential }); break; case "ICS": var cache = calendarCache.GetCalendar(id); if (cache != null) { var icsServiceResponse = await icsService.GetIcsContent(credentials.ServiceUrl, cache.ETag); if (icsServiceResponse.NotModified) { calendarModel.Appointments = cache.CalendarModel.Appointments; } else { calendarModel.Appointments = icsServiceResponse.Appointments; calendarCache.PutCalendar(id, new CalendarCacheEntry(id) { CalendarModel = calendarModel, ETag = icsServiceResponse.ETag }); } } else { var icsResponse = await icsService.GetIcsContent(credentials.ServiceUrl, string.Empty); calendarModel.Appointments = icsResponse.Appointments; calendarCache.PutCalendar(id, new CalendarCacheEntry(id) { CalendarModel = calendarModel, ETag = icsResponse.ETag }); } break; default: throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "")); } // Now only return the appointments in the requested range return new CalendarModel { Owner = calendarModel.Owner, Appointments = calendarModel.Appointments .Where(a => a != null && a.StartTime.Date >= start && a.StartTime.Date <= end) .OrderBy(a => a.StartTime) }; }
/// <summary> /// Renders the specified context. /// </summary> /// <param name="context">The context.</param> /// <param name="result">The result.</param> public override void Render( Context context, TextWriter result ) { var rockContext = new RockContext(); // Get enabled security commands if ( context.Registers.ContainsKey( "EnabledCommands" ) ) { _enabledSecurityCommands = context.Registers["EnabledCommands"].ToString(); } using ( TextWriter writer = new StringWriter() ) { var now = RockDateTime.Now; base.Render( context, writer ); var parms = ParseMarkup( _markup, context ); string username; string password; var rawUsername = username = parms[EWS_USERNAME]; var rawPassword = password = parms[EWS_PASSWORD]; var decryptedUn = Encryption.DecryptString( rawUsername ); var decryptedPw = Encryption.DecryptString( rawPassword ); if ( !string.IsNullOrWhiteSpace( decryptedUn ) ) { username = decryptedUn; } if ( !string.IsNullOrWhiteSpace( decryptedPw ) ) { password = decryptedPw; } var order = parms[ORDER]; var mailbox = parms[CALENDAR_MAILBOX]; var url = parms[SERVER_URL]; var daysBack = parms[DAYS_BACK].AsIntegerOrNull(); var daysForward = parms[DAYS_FORWARD].AsIntegerOrNull(); var startDate = now.Date; var endDate = now.Date.AddDays( 8 ).AddMilliseconds( -1 ); if ( daysBack.HasValue ) { startDate = startDate.AddDays( -daysBack.Value ); } if ( daysForward.HasValue ) { endDate = now.Date.AddDays( daysForward.Value + 1 ).AddMilliseconds( -1 ); } if ( string.IsNullOrWhiteSpace( username ) || string.IsNullOrWhiteSpace( password ) || string.IsNullOrWhiteSpace( mailbox ) ) { return; } var calendarItems = new List<CalendarItemResult>(); var service = new ExchangeService(); try { service.Credentials = new WebCredentials( username, password ); service.TraceEnabled = true; service.TraceFlags = TraceFlags.All; service.Url = new Uri( url ); var folderId = new FolderId( WellKnownFolderName.Calendar, mailbox ); CalendarView calView = new CalendarView( startDate, endDate ); calView.PropertySet = new PropertySet( PropertySet.IdOnly ); var addlPropSet = new PropertySet( AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.Location, AppointmentSchema.Body, AppointmentSchema.TextBody, AppointmentSchema.IsRecurring, AppointmentSchema.AppointmentType, AppointmentSchema.DisplayTo, AppointmentSchema.DisplayCc ); var appointments = service.FindAppointments( folderId, calView ); if ( appointments.Items.Count > 0 ) { service.LoadPropertiesForItems( appointments.Items, addlPropSet ); calendarItems.AddRange( appointments.Where( a => a.AppointmentType != AppointmentType.RecurringMaster ) .OrderBy( a => a.Start ) .Select( a => new CalendarItemResult { Subject = a.Subject, Body = a.Body, TextBody = a.TextBody, Start = a.Start, End = a.End, Location = a.Location, DisplayTo = a.DisplayTo, DisplayCc = a.DisplayCc, IsRecurring = a.IsRecurring } ) ); } } catch ( Exception ex ) { ExceptionLogService.LogException( ex, HttpContext.Current ); result.Write( string.Format( "<div class='alert alert-warning'>{0}</div>", ex.Message ) ); return; } if ( calendarItems.Count() == 0 ) { return; } if ( order.ToLower() == "desc" ) { calendarItems = calendarItems.OrderByDescending( ci => ci.Start ).ToList(); } var mergeFields = LoadBlockMergeFields( context ); mergeFields.Add( "CalendarItems", calendarItems ); var results = _blockMarkup.ToString().ResolveMergeFields( mergeFields, _enabledSecurityCommands ); result.Write( results.Trim() ); base.Render( context, result ); } }
public void GetItemsFromFolder(ExchangeService service, object folder, bool isRoot) { ItemView itemView = new ItemView(1000) { Traversal = ItemTraversal.Shallow }; CalendarView calendarView = new CalendarView(StartDate, EndDate); FindItemsResults <Item> results = null; FindItemsResults <Appointment> calendarResults = null; do { // Query items via EWS. results = service.FindItems(isRoot ? (FolderId)folder : ((Folder)folder).Id, QueryString, itemView); foreach (var item in results.Items) { // Bind an email message and pull the specified set of properties. OItem oItem = new OItem() { Item = Item.Bind(service, item.Id, Fields), Attachments = new List <ItemAttachment>() }; var attachments = string.Empty; // Extract attachments from each message item if found. if (!String.IsNullOrEmpty(AttachmentPath)) { oItem.Attachments = GetAttachmentsFromItem(oItem.Item); } _oItems.Add(oItem); } itemView.Offset += results.Items.Count; }while (results.MoreAvailable); if (Folder == WellKnownFolderName.Calendar && IncludeRecurringEvents) { do { // Query calendar items via EWS. calendarResults = service.FindAppointments(isRoot ? (FolderId)folder : ((Folder)folder).Id, calendarView); foreach (var item in calendarResults.Items) { // Bind a calendar item and pull the specified set of properties. OItem oItem = new OItem() { Item = Item.Bind(service, item.Id, Fields), Attachments = new List <ItemAttachment>() }; var attachments = string.Empty; // Extract attachments from each calendar item if found. if (!String.IsNullOrEmpty(AttachmentPath)) { oItem.Attachments = GetAttachmentsFromItem(oItem.Item); } _oItems.Add(oItem); } itemView.Offset += calendarResults.Items.Count; }while (calendarResults.MoreAvailable); } }