public void HideShorterThan10Minutes() { VCalendarParser calendar = new VCalendarParser(); calendar.ParseFile("SampleCalendar.ics"); EWSoftware.PDI.Objects.VEvent ev_5minutes = calendar.VCalendar.Events.AddNew(); ev_5minutes.UniqueId.Value = Guid.NewGuid().ToString(); ev_5minutes.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01); ev_5minutes.EndDateTime.DateTimeValue = ev_5minutes.StartDateTime.DateTimeValue.AddMinutes(5); EWSoftware.PDI.Objects.VEvent ev_10minutes = calendar.VCalendar.Events.AddNew(); ev_10minutes.UniqueId.Value = Guid.NewGuid().ToString(); ev_10minutes.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01); ev_10minutes.EndDateTime.DateTimeValue = ev_10minutes.StartDateTime.DateTimeValue.AddMinutes(10); EWSoftware.PDI.Objects.VEvent ev_15minutes = calendar.VCalendar.Events.AddNew(); ev_15minutes.UniqueId.Value = Guid.NewGuid().ToString(); ev_15minutes.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01).AddHours(2); ev_15minutes.EndDateTime.DateTimeValue = ev_15minutes.StartDateTime.DateTimeValue.AddMinutes(15); Assert.AreEqual(1, calendar.VCalendar.Events.Count(ev => ev.UniqueId == ev_5minutes.UniqueId)); Assert.AreEqual(1, calendar.VCalendar.Events.Count(ev => ev.UniqueId == ev_10minutes.UniqueId)); Assert.AreEqual(1, calendar.VCalendar.Events.Count(ev => ev.UniqueId == ev_15minutes.UniqueId)); // filter out all-day events EventManager em = new EventManager(calendar); em.Filter(new FilteringOptions("min=10")); System.Collections.Generic.IList <EWSoftware.PDI.Objects.VEvent> eventsAfterFiltering = em.GetEventList(); Assert.AreEqual(0, eventsAfterFiltering.Count(ev => ev.UniqueId == ev_5minutes.UniqueId)); Assert.AreEqual(1, eventsAfterFiltering.Count(ev => ev.UniqueId == ev_10minutes.UniqueId)); Assert.AreEqual(1, eventsAfterFiltering.Count(ev => ev.UniqueId == ev_15minutes.UniqueId)); }
public void ShortenEvents() { VCalendarParser calendar = new VCalendarParser(); calendar.ParseFile("SampleCalendar.ics"); EWSoftware.PDI.Objects.VEvent ev_1h = calendar.VCalendar.Events.AddNew(); ev_1h.UniqueId.Value = Guid.NewGuid().ToString(); ev_1h.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01); ev_1h.EndDateTime.DateTimeValue = ev_1h.StartDateTime.DateTimeValue.AddHours(1); EWSoftware.PDI.Objects.VEvent ev_2h = calendar.VCalendar.Events.AddNew(); ev_2h.UniqueId.Value = Guid.NewGuid().ToString(); ev_2h.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01); ev_2h.EndDateTime.DateTimeValue = ev_2h.StartDateTime.DateTimeValue.AddHours(2); EWSoftware.PDI.Objects.VEvent ev_3h = calendar.VCalendar.Events.AddNew(); ev_3h.UniqueId.Value = Guid.NewGuid().ToString(); ev_3h.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01).AddHours(2); ev_3h.EndDateTime.DateTimeValue = ev_3h.StartDateTime.DateTimeValue.AddHours(3); Assert.AreEqual(1, calendar.VCalendar.Events.First(ev => ev.UniqueId == ev_1h.UniqueId).DurationBasedOnDates().TotalHours); Assert.AreEqual(2, calendar.VCalendar.Events.First(ev => ev.UniqueId == ev_2h.UniqueId).DurationBasedOnDates().TotalHours); Assert.AreEqual(3, calendar.VCalendar.Events.First(ev => ev.UniqueId == ev_3h.UniqueId).DurationBasedOnDates().TotalHours); // filter out all-day events EventManager em = new EventManager(calendar); em.Filter(new FilteringOptions("lt=60&mt=60")); IList <EWSoftware.PDI.Objects.VEvent> eventsAfterFiltering = em.GetEventList(); Assert.AreEqual(1, eventsAfterFiltering.First(ev => ev.UniqueId == ev_1h.UniqueId).DurationBasedOnDates().TotalHours); Assert.AreEqual(1, eventsAfterFiltering.First(ev => ev.UniqueId == ev_2h.UniqueId).DurationBasedOnDates().TotalHours); Assert.AreEqual(1, eventsAfterFiltering.First(ev => ev.UniqueId == ev_3h.UniqueId).DurationBasedOnDates().TotalHours); }
public void FilterAllDayEvents1() { VCalendarParser calendar = new VCalendarParser(); calendar.ParseFile("SampleCalendar.ics"); EWSoftware.PDI.Objects.VEvent ev_allday = calendar.VCalendar.Events.AddNew(); ev_allday.UniqueId.Value = Guid.NewGuid().ToString(); ev_allday.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01); ev_allday.EndDateTime.DateTimeValue = ev_allday.StartDateTime.DateTimeValue.AddDays(1); EWSoftware.PDI.Objects.VEvent ev_notallday = calendar.VCalendar.Events.AddNew(); ev_notallday.UniqueId.Value = Guid.NewGuid().ToString(); ev_notallday.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01).AddHours(2); ev_notallday.EndDateTime.DateTimeValue = ev_notallday.StartDateTime.DateTimeValue.AddDays(1).AddHours(-2); Assert.AreEqual(1, calendar.VCalendar.Events.Count(ev => Equals(ev.UniqueId, ev_allday.UniqueId))); Assert.AreEqual(1, calendar.VCalendar.Events.Count(ev => Equals(ev.UniqueId, ev_notallday.UniqueId))); // filter out all-day events EventManager em = new EventManager(calendar); em.Filter(new FilteringOptions("h=true")); IList <EWSoftware.PDI.Objects.VEvent> eventsAfterFiltering = em.GetEventList(); Assert.AreEqual(0, eventsAfterFiltering.Count(ev => Equals(ev.UniqueId, ev_allday.UniqueId))); Assert.AreEqual(1, eventsAfterFiltering.Count(ev => Equals(ev.UniqueId, ev_notallday.UniqueId))); }
protected void Page_Load(object sender, EventArgs e) { this.Page.Title = "vCalendar/iCalendar Browser"; lblMsg.Text = String.Empty; VCalendar vc = (VCalendar)Session["VCalendar"]; // Load a default calendar on first use and store it in the session if not already there and bind it // to the data grids. if (!Page.IsPostBack || vc == null) { if (vc == null) { if (Page.IsPostBack) { lblMsg.Text = "Session appears to have timed out. Default calendar loaded."; } vc = VCalendarParser.ParseFromFile(Server.MapPath("RFC2445.ics")); vc.Events.Sort(CalendarSorter); vc.ToDos.Sort(CalendarSorter); vc.Journals.Sort(CalendarSorter); vc.FreeBusys.Sort(CalendarSorter); Session["VCalendar"] = vc; } dgEvents.DataSource = vc.Events; dgToDos.DataSource = vc.ToDos; dgJournals.DataSource = vc.Journals; dgFreeBusys.DataSource = vc.FreeBusys; dgEvents.DataBind(); dgToDos.DataBind(); dgJournals.DataBind(); dgFreeBusys.DataBind(); if (vc.Version == SpecificationVersions.vCalendar10) { lblVersion.Text = "vCalendar 1.0"; dgJournals.Visible = dgFreeBusys.Visible = false; } else { lblVersion.Text = "iCalendar 2.0"; dgJournals.Visible = dgFreeBusys.Visible = true; } } }
/// <summary> /// Initialize the time zone and recurrence information at start up /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> protected void Application_Start(object sender, EventArgs e) { // Load the time zones if not already done. The collection is static so it only needs to be loaded // once. if (VCalendar.TimeZones.Count == 0) { // Since it is static, we will use the Lock property to synchronize access to it in the web app // as multiple sessions may try to access it at the same time. The parser will acquire a write // lock if it needs to merge a time zone component but since we are loading many time zones at // once, we'll lock it now. VCalendar.TimeZones.AcquireWriterLock(250); try { // If still zero, load the file if (VCalendar.TimeZones.Count == 0) { VCalendarParser.ParseFromFile(Server.MapPath("TimeZoneDB.ics")); VCalendar.TimeZones.Sort(true); } } finally { VCalendar.TimeZones.ReleaseWriterLock(); } } // Load a default set of holidays into the recurrence holiday collection. It too is static, but // since it probably won't change after being set, it uses a simple SyncRoot property to lock the // collection. if (Recurrence.Holidays.Count == 0) { lock (((ICollection)Recurrence.Holidays).SyncRoot) { if (Recurrence.Holidays.Count == 0) { Recurrence.Holidays.AddStandardHolidays(); } } } }
public void SkipEventsFromProjectX() { VCalendarParser calendar = new VCalendarParser(); calendar.ParseFile("SampleCalendar.ics"); EWSoftware.PDI.Objects.VEvent ev_projectX = calendar.VCalendar.Events.AddNew(); ev_projectX.UniqueId.Value = Guid.NewGuid().ToString(); ev_projectX.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01); ev_projectX.EndDateTime.DateTimeValue = ev_projectX.StartDateTime.DateTimeValue.AddDays(1); ev_projectX.Description.Value = @"Proyecto: Project X\n\nCompletar este elemento: \nhttp://todoist.com/#project/999999999"; EWSoftware.PDI.Objects.VEvent ev_projectY = calendar.VCalendar.Events.AddNew(); ev_projectY.UniqueId.Value = Guid.NewGuid().ToString(); ev_projectY.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01).AddHours(2); ev_projectY.EndDateTime.DateTimeValue = ev_projectY.StartDateTime.DateTimeValue.AddDays(1).AddHours(-2); ev_projectY.Description.Value = @"Proyecto: Project Y\n\nCompletar este elemento: \nhttp://todoist.com/#project/999999999"; EWSoftware.PDI.Objects.VEvent ev_projectZ = calendar.VCalendar.Events.AddNew(); ev_projectZ.UniqueId.Value = Guid.NewGuid().ToString(); ev_projectZ.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01).AddHours(2); ev_projectZ.EndDateTime.DateTimeValue = ev_projectZ.StartDateTime.DateTimeValue.AddDays(1).AddHours(-2); ev_projectZ.Description.Value = @"Proyecto: Project\n\nCompletar este elemento: \nhttp://todoist.com/#project/999999999"; Assert.AreEqual(1, calendar.VCalendar.Events.Count(ev => ev.UniqueId == ev_projectX.UniqueId)); Assert.AreEqual(1, calendar.VCalendar.Events.Count(ev => ev.UniqueId == ev_projectY.UniqueId)); Assert.AreEqual(1, calendar.VCalendar.Events.Count(ev => ev.UniqueId == ev_projectZ.UniqueId)); // filter out all-day events EventManager em = new EventManager(calendar); em.Filter(new FilteringOptions("&pr=Project X")); System.Collections.Generic.IList <EWSoftware.PDI.Objects.VEvent> eventsAfterFiltering = em.GetEventList(); Assert.AreEqual(0, eventsAfterFiltering.Where(ev => ev.UniqueId == ev_projectX.UniqueId).Count()); Assert.AreEqual(1, eventsAfterFiltering.Where(ev => ev.UniqueId == ev_projectY.UniqueId).Count()); Assert.AreEqual(1, eventsAfterFiltering.Where(ev => ev.UniqueId == ev_projectZ.UniqueId).Count()); }
public void HideIfTitleContainsString() { VCalendarParser calendar = new VCalendarParser(); calendar.ParseFile("SampleCalendar.ics"); EWSoftware.PDI.Objects.VEvent ev_str1 = calendar.VCalendar.Events.AddNew(); ev_str1.UniqueId.Value = Guid.NewGuid().ToString(); ev_str1.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01); ev_str1.EndDateTime.DateTimeValue = ev_str1.StartDateTime.DateTimeValue.AddDays(1); ev_str1.Summary.Value = "this is a [hidden] event"; EWSoftware.PDI.Objects.VEvent ev_str2 = calendar.VCalendar.Events.AddNew(); ev_str2.UniqueId.Value = Guid.NewGuid().ToString(); ev_str2.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01); ev_str2.EndDateTime.DateTimeValue = ev_str2.StartDateTime.DateTimeValue.AddDays(1); ev_str2.Summary.Value = "[hidden] event too"; EWSoftware.PDI.Objects.VEvent ev_nostr = calendar.VCalendar.Events.AddNew(); ev_nostr.UniqueId.Value = Guid.NewGuid().ToString(); ev_nostr.StartDateTime.DateTimeValue = new DateTime(2015, 01, 01).AddHours(2); ev_nostr.EndDateTime.DateTimeValue = ev_nostr.StartDateTime.DateTimeValue.AddDays(1).AddHours(-2); ev_nostr.Summary.Value = "this is not hidden"; Assert.AreEqual(1, calendar.VCalendar.Events.Count(ev => Equals(ev.UniqueId, ev_str1.UniqueId))); Assert.AreEqual(1, calendar.VCalendar.Events.Count(ev => Equals(ev.UniqueId, ev_str2.UniqueId))); Assert.AreEqual(1, calendar.VCalendar.Events.Count(ev => Equals(ev.UniqueId, ev_nostr.UniqueId))); // filter out all-day events EventManager em = new EventManager(calendar); em.Filter(new FilteringOptions("st=[hidden]")); System.Collections.Generic.IList <EWSoftware.PDI.Objects.VEvent> eventsAfterFiltering = em.GetEventList(); Assert.AreEqual(0, eventsAfterFiltering.Count(ev => ev.UniqueId == ev_str1.UniqueId)); Assert.AreEqual(0, eventsAfterFiltering.Count(ev => ev.UniqueId == ev_str2.UniqueId)); Assert.AreEqual(1, eventsAfterFiltering.Count(ev => ev.UniqueId == ev_nostr.UniqueId)); }
static void Main(string[] args) { string outputFolder, outputFile; if (args.GetUpperBound(0) < 1) { Console.WriteLine("Specify a folder name containing PDI files and a different one for the " + "output files."); return; } try { // Set the default encoding to iso-8859-1 (Western European) as several of the files are encoded // that way. PDIParser.DefaultEncoding = BaseProperty.DefaultEncoding = Encoding.GetEncoding("iso-8859-1"); outputFolder = args[1]; if (!outputFolder.EndsWith(@"\", StringComparison.Ordinal)) { outputFolder += @"\"; } if (!Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); } Console.WriteLine("Parsing vCard files..."); // Since we'll be parsing multiple files, we'll create an instance of the parser and re-use it // rather than using the static parsing methods. VCardParser vcardp = new VCardParser(); foreach (string file in Directory.EnumerateFiles(args[0], "*.vcf")) { Console.WriteLine("\n{0}", file); vcardp.ParseFile(file); Console.WriteLine(vcardp.VCards.ToString()); // Write it to a stream outputFile = outputFolder + Path.GetFileName(file); // NOTE: We must use the same encoding method when writing the file back out using (var sw = new StreamWriter(outputFile, false, PDIParser.DefaultEncoding)) { vcardp.VCards.WriteToStream(sw); } // Clear the collection ready for the next run vcardp.VCards.Clear(); } Console.WriteLine("\nParsing vCalendar files..."); // Since we'll be parsing multiple files, we'll create an instance of the parser and re-use it // rather than using the static parser methods. VCalendarParser vcalp = new VCalendarParser(); foreach (string file in Directory.EnumerateFiles(args[0], "*.vcs")) { Console.WriteLine("\n{0}", file); vcalp.ParseFile(file); Console.WriteLine(vcalp.VCalendar.ToString()); // Write it to a stream outputFile = outputFolder + Path.GetFileName(file); // NOTE: We must use the same encoding method when writing the file back out using (var sw = new StreamWriter(outputFile, false, PDIParser.DefaultEncoding)) { vcalp.VCalendar.WriteToStream(sw); } // Clear the calendar ready for the next run vcalp.VCalendar.ClearProperties(); } Console.WriteLine("\nParsing iCalendar files..."); // Get a list of iCalendar files to parse. It uses the same parser as the vCalendar files foreach (string file in Directory.EnumerateFiles(args[0], "*.ics")) { Console.WriteLine("\n{0}", file); vcalp.ParseFile(file); Console.WriteLine(vcalp.VCalendar.ToString()); // Write it to a stream outputFile = outputFolder + Path.GetFileName(file); // NOTE: We must use the same encoding method when writing the file back out using (var sw = new StreamWriter(outputFile, false, PDIParser.DefaultEncoding)) { vcalp.VCalendar.WriteToStream(sw); } // Clear the calendar ready for the next run vcalp.VCalendar.ClearProperties(); } Console.WriteLine("\nParsing vNote files..."); // Since we'll be parsing multiple files, we'll create an instance of the parser and re-use it // rather than using the static parser methods. VNoteParser vnp = new VNoteParser(); foreach (string file in Directory.EnumerateFiles(args[0], "*.vnt")) { Console.WriteLine("\n{0}", file); vnp.ParseFile(file); Console.WriteLine(vnp.VNotes.ToString()); // Write it to a stream outputFile = outputFolder + Path.GetFileName(file); // NOTE: We must use the same encoding method when writing the file back out using (var sw = new StreamWriter(outputFile, false, PDIParser.DefaultEncoding)) { vnp.VNotes.WriteToStream(sw); } // Clear the collection ready for the next run vnp.VNotes.Clear(); } } catch (PDIParserException pe) { Console.WriteLine("\n\nError at line #{0}\n\n{1}", pe.LineNumber, pe.ToString()); } catch (Exception ex) { Console.WriteLine("Unexpected failure:\n{0}", ex.ToString()); } }
/// <summary> /// Load a calendar file uploaded by the user. It can be a vCalendar or an iCalendar file /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> protected void btnUpload_Click(object sender, EventArgs e) { VCalendar vc = (VCalendar)Session["VCalendar"]; if (hifUpload.Value == null || hifUpload.Value.Length == 0) { lblMsg.Text = "Specify a filename to upload"; return; } // Get the file data from the uploaded stream try { // Dispose of the old calendar vc.Dispose(); // Set the file and property encodings to use. Since we are opening the stream, we have to pass // the encoding to the StreamReader rather than using PDIParser.DefaultEncoding. Encoding fileEnc; switch (cboFileEncoding.SelectedIndex) { case 0: fileEnc = new UTF8Encoding(false, false); break; case 1: fileEnc = Encoding.GetEncoding("iso-8859-1"); break; default: fileEnc = new ASCIIEncoding(); break; } // This is only applicable for vCalendar 1.0 switch (cboPropEncoding.SelectedIndex) { case 0: BaseProperty.DefaultEncoding = new UTF8Encoding(false, false); break; case 1: BaseProperty.DefaultEncoding = Encoding.GetEncoding("iso-8859-1"); break; default: BaseProperty.DefaultEncoding = new ASCIIEncoding(); break; } using (var sr = new StreamReader(hifUpload.PostedFile.InputStream, fileEnc)) { vc = VCalendarParser.ParseFromStream(sr); vc.Events.Sort(CalendarSorter); vc.ToDos.Sort(CalendarSorter); vc.Journals.Sort(CalendarSorter); vc.FreeBusys.Sort(CalendarSorter); Session["VCalendar"] = vc; dgEvents.DataSource = vc.Events; dgToDos.DataSource = vc.ToDos; dgJournals.DataSource = vc.Journals; dgFreeBusys.DataSource = vc.FreeBusys; dgEvents.DataBind(); dgToDos.DataBind(); dgJournals.DataBind(); dgFreeBusys.DataBind(); if (vc.Version == SpecificationVersions.vCalendar10) { lblVersion.Text = "vCalendar 1.0"; dgJournals.Visible = dgFreeBusys.Visible = false; } else { lblVersion.Text = "iCalendar 2.0"; dgJournals.Visible = dgFreeBusys.Visible = true; } } lblMsg.Text = "The file was loaded successfully"; } catch (PDIParserException pex) { System.Diagnostics.Debug.WriteLine(pex.ToString()); lblMsg.Text = "Unable to parse file: " + pex.Message; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); lblMsg.Text = "Unable to load file: " + ex.Message; } }
/// <summary> /// Alternative constructor that initialises object based on given calendar object, without parsing anything /// </summary> /// <param name="calendar"></param> public EventManager(VCalendarParser calendar) { this.calendar = calendar; }
/// <summary> /// Constructor. Parses given VCalendar string and stores internally as VCalendar object. /// </summary> /// <param name="icalContent"></param> public EventManager(string icalContent) { calendar = new VCalendarParser(); calendar.ParseString(icalContent); }
/// <summary> /// Generate instances for the specified component /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event parameters</param> protected void btnTest_Click(object sender, EventArgs e) { RecurringObject ro = null; DateTimeInstanceCollection instances; string calendar; int start; double elapsed; DateTime startDate, endDate; try { lblCount.Text = String.Empty; if (!DateTime.TryParse(txtStartDate.Text, CultureInfo.CurrentCulture, DateTimeStyles.None, out startDate) || !DateTime.TryParse(txtEndDate.Text, CultureInfo.CurrentCulture, DateTimeStyles.None, out endDate)) { lblCount.Text = "Invalid start or end date/time format"; return; } // Wrap it in VCALENDAR tags and parse it calendar = String.Format("BEGIN:VCALENDAR\nVERSION:2.0\n{0}\nEND:VCALENDAR", txtCalendar.Text); VCalendar cal = VCalendarParser.ParseFromString(calendar); // Get the first event, to-do, or journal item if (cal.Events.Count > 0) { ro = cal.Events[0]; } else if (cal.ToDos.Count > 0) { ro = cal.ToDos[0]; } else if (cal.Journals.Count > 0) { ro = cal.Journals[0]; } if (ro == null) { lblCount.Text = "No event, to-do, or journal item found"; return; } // Apply the time zone to the calendar. If "None" is selected, the time zone will be cleared on // all items. if (cboTimeZone.SelectedIndex < 1) { cal.ApplyTimeZone(null); } else { cal.ApplyTimeZone(VCalendar.TimeZones[cboTimeZone.SelectedIndex - 1]); } foreach (RRuleProperty rrule in ro.RecurrenceRules) { ApplyLimits(ro, rrule.Recurrence); } foreach (ExRuleProperty exrule in ro.ExceptionRules) { ApplyLimits(ro, exrule.Recurrence); } txtCalendar.Text = ro.ToString(); start = System.Environment.TickCount; instances = ro.InstancesBetween(startDate, endDate, chkInLocalTime.Checked); elapsed = (System.Environment.TickCount - start) / 1000.0; cal.Dispose(); // The date instance contains the start and end date/times, the duration, and time zone // information. The duration is based on the duration of the calendar component. The time zone // information is based on the "In Local Time" parameter of the InstancesBetween() method and // whether or not the component has a Time Zone ID specified. dlDates.DataSource = instances; dlDates.DataBind(); // If nothing was found remind the user that they may need to adjust the start and end date range // to find stuff within the item. if (instances.Count == 0) { lblCount.Text = "Nothing found. If this was unexpected, check the limiting date range " + "in the two date/time text boxes at the top of the form and the calendar item date/time " + "properties to make sure that they do overlap<br/><br/>"; } lblCount.Text += String.Format("Found {0:N0} instances in {1:N2} seconds ({2:N2} instances/second)", instances.Count, elapsed, instances.Count / elapsed); } catch (Exception ex) { lblCount.Text = ex.Message; } }
/// <summary> /// Open a vCalendar or iCalendar file /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void miOpen_Click(object sender, EventArgs e) { if (wasModified && MessageBox.Show("Do you want to discard your changes to the current calendar?", "Discard Changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No) { return; } using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "Load Calendar File"; dlg.Filter = "ICS files (*.ics)|*.ics|VCS files (*.vcs)|*.vcs|All files (*.*)|*.*"; if (vCal.Version == SpecificationVersions.vCalendar10) { dlg.DefaultExt = "vcs"; dlg.FilterIndex = 2; } else { dlg.DefaultExt = "ics"; dlg.FilterIndex = 1; } dlg.InitialDirectory = Path.GetFullPath(Path.Combine( Environment.CurrentDirectory, @"..\..\..\..\..\PDIFiles")); if (dlg.ShowDialog() == DialogResult.OK) { try { this.Cursor = Cursors.WaitCursor; // Parse the calendar information from the file and load the data grid with some basic // information about the items in it. vCal.Dispose(); vCal = VCalendarParser.ParseFromFile(dlg.FileName); LoadComponentList(); // Find the first collection with items if (vCal.Events.Count != 0) { cboComponents.SelectedIndex = 0; } else if (vCal.ToDos.Count != 0) { cboComponents.SelectedIndex = 1; } else if (vCal.Journals.Count != 0) { cboComponents.SelectedIndex = 2; } else if (vCal.FreeBusys.Count != 0) { cboComponents.SelectedIndex = 3; } else { cboComponents.SelectedIndex = 0; } LoadGridWithItems(true); lblFilename.Text = dlg.FileName; } catch (Exception ex) { string error = String.Format("Unable to load calendar:\n{0}", ex.Message); if (ex.InnerException != null) { error += ex.InnerException.Message + "\n"; if (ex.InnerException.InnerException != null) { error += ex.InnerException.InnerException.Message; } } System.Diagnostics.Debug.Write(ex); MessageBox.Show(error, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { this.Cursor = Cursors.Default; } } } }
/// <summary> /// Test the recurrence within the specified iCalendar component /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnTest_Click(object sender, EventArgs e) { RecurringObject ro = null; DateTimeInstanceCollection instances; string calendar; int start; double elapsed; try { lblCount.Text = null; // Wrap it in VCALENDAR tags and parse it calendar = String.Format("BEGIN:VCALENDAR\nVERSION:2.0\n{0}\nEND:VCALENDAR", txtCalendar.Text); VCalendar cal = VCalendarParser.ParseFromString(calendar); // Get the first event, to-do, or journal item if (cal.Events.Count > 0) { ro = cal.Events[0]; } else if (cal.ToDos.Count > 0) { ro = cal.ToDos[0]; } else if (cal.Journals.Count > 0) { ro = cal.Journals[0]; } if (ro == null) { lblCount.Text = "No event, to-do, or journal item found"; return; } // Apply the time zone to the calendar. If "None" is selected, the time zone will be cleared on // all items. if (cboTimeZone.SelectedIndex < 1) { cal.ApplyTimeZone(null); } else { cal.ApplyTimeZone(VCalendar.TimeZones[cboTimeZone.SelectedIndex - 1]); } txtCalendar.Text = ro.ToString(); lbDates.Items.Clear(); this.Cursor = Cursors.WaitCursor; start = System.Environment.TickCount; instances = ro.InstancesBetween(dtpStartDate.Value, dtpEndDate.Value, chkInLocalTime.Checked); elapsed = (System.Environment.TickCount - start) / 1000.0; cal.Dispose(); // The date instance contains the start and end date/times, the duration, and time zone // information. The duration is based on the duration of the calendar component. The time // zone information is based on the "In Local Time" parameter of the InstancesBetween() method // and whether or not the component has a Time Zone ID specified. foreach (DateTimeInstance dti in instances) { lbDates.Items.Add(String.Format("{0:G} {1} to {2:G} {3} ({4})", dti.StartDateTime, dti.AbbreviatedStartTimeZoneName, dti.EndDateTime, dti.AbbreviatedEndTimeZoneName, dti.Duration.ToDescription())); if (lbDates.Items.Count > 5000) { lblCount.Text += "A large number of instances were returned. Only the first 5000 " + "have been loaded into the list box.\r\n"; break; } } // If nothing was found remind the user that they may need to adjust the start and end date range // to find stuff within the item. if (instances.Count == 0) { MessageBox.Show("Nothing found. If this was unexpected, check the limiting date range in " + "the two date/time text boxes at the top of the form and the calendar item date/time " + "properties to make sure that they do overlap"); } lblCount.Text += String.Format("Found {0:N0} instances in {1:N2} seconds ({2:N2} instances/second)", instances.Count, elapsed, instances.Count / elapsed); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { this.Cursor = Cursors.Default; } }