/// <summary> /// Returns a set of appointments from a GoogleApps Feed /// </summary> /// <param name="user">The exchange user to get apointments for</param> /// <param name="srcTimeZone">The time zone to use</param> /// <param name="googleAppsFeed">Source feed to create array from</param> /// <returns></returns> private IntervalTree <Appointment> CreateAppointments( ExchangeUser user, OlsonTimeZone srcTimeZone, EventFeed googleAppsFeed) { IntervalTree <Appointment> result = new IntervalTree <Appointment>(); foreach (EventEntry eventEntry in googleAppsFeed.Entries) { try { CreateAppointment(result, user, srcTimeZone, eventEntry); } catch (GCalExchangeException ex) { if (ex.ErrorCode == GCalExchangeErrorCode.OlsonTZError) { log.Error("Error creating appointment (TimeZone issue)", ex); } else { throw; } } } return(result); }
/// <summary> /// Convert a time from UTC to a timezone /// </summary> /// <param name="srcTime">Time to convert</param> /// <param name="dstZone">Timezone to convert the datetime to</param> /// <returns>DateTime in the timezone</returns> public static DateTime ConvertFromUTC(DateTime srcTime, OlsonTimeZone dstZone) { TimeCheckResult srcCheckRes = dstZone.Check(srcTime); switch (srcCheckRes) { case TimeCheckResult.Valid: { DateTime dstTime = dstZone.ToLocalTime(srcTime); return dstTime; } case TimeCheckResult.InSpringForwardGap: case TimeCheckResult.InFallBackRange: _log.ErrorFormat("Source time in transition period - retry. [date={0}, tz={1}]", srcTime, dstZone.Name); return ConvertFromUTC(srcTime.AddHours(1), dstZone); default: { string errorMessage = string.Format( "Source time out of range. [date={0}, tz={1}]", srcTime, dstZone.Name ); throw new GCalExchangeException( GCalExchangeErrorCode.OlsonTZError, errorMessage ); } } }
/// <summary> /// Convert a time from UTC to a timezone /// </summary> /// <param name="srcTime">Time to convert</param> /// <param name="dstZone">Timezone to convert the datetime to</param> /// <returns>DateTime in the timezone</returns> public static DateTime ConvertFromUTC(DateTime srcTime, OlsonTimeZone dstZone) { TimeCheckResult srcCheckRes = dstZone.Check(srcTime); switch (srcCheckRes) { case TimeCheckResult.Valid: { DateTime dstTime = dstZone.ToLocalTime(srcTime); return(dstTime); } case TimeCheckResult.InSpringForwardGap: case TimeCheckResult.InFallBackRange: _log.ErrorFormat("Source time in transition period - retry. [date={0}, tz={1}]", srcTime, dstZone.Name); return(ConvertFromUTC(srcTime.AddHours(1), dstZone)); default: { string errorMessage = string.Format( "Source time out of range. [date={0}, tz={1}]", srcTime, dstZone.Name); throw new GCalExchangeException( GCalExchangeErrorCode.OlsonTZError, errorMessage); } } }
public static OlsonTimeZone GetInstanceFromOlsonName(string sTZ) { lock (OlsonTimeZone.SyncRoot) { return(OlsonTimeZone.GetInstanceFromOlsonName(sTZ)); } }
private static void Main(string[] args) { options = new ZmanimOptions(); p = new OptionSet { {"d|date=", "Set date. <mm/dd/yyyy>", x => options.Date = DateTime.ParseExact(x, "MM/dd/yyyy", CultureInfo.InvariantCulture)}, {"lat|latitude=", "Set location's latitude", (double x) => options.Latitude = x}, {"lon|longitude=", "Set location's longitude", (double x) => options.Longitude = x}, {"e|elevation=", "Set location's elevation; Positive only", (double x) => options.Elevation = x}, {"tz|timezone=", "Set location's TimeZone", x => options.TimeZone = x}, {"tf|timeformat=", "Set the way the application formats a DateTime object.", x => options.DateTimeFormat = x}, {"h|?|help", "Shows this help message", v => ShowHelp()} }; List<string> extraArgs; try { extraArgs = p.Parse(args); } catch (OptionException) { ShowHelp(); return; } var timeZone = new OlsonTimeZone(options.TimeZone); var location = new GeoLocation(string.Empty, options.Latitude, options.Longitude, options.Elevation, timeZone); var czc = new ComplexZmanimCalendar(new DateTime(options.Date.Year, options.Date.Month, options.Date.Day), location); var methods = GetDateTimeAndLongMethods(); foreach (var first in extraArgs.Select(extraArg => methods.Where( f => f.Name.Remove(0, 3).ToLowerInvariant() == extraArg.ToLowerInvariant()).First()) ) { object invoke = first.Invoke(czc, null); if (extraArgs.Count > 1) Console.Write(first.Name.Remove(0, 3) + ": "); if (invoke.GetType() == typeof(DateTime)) { var time = (DateTime)invoke; Console.Write(time.ToString(options.DateTimeFormat)); } else if (invoke.GetType() == typeof(long)) { Console.WriteLine((long)invoke); } if (extraArgs.Count > 1) Console.WriteLine(); } //Console.Read(); }
/// <summary> /// Convert a date time from one timezone to another. /// </summary> /// <param name="src">The datetime to convert</param> /// <param name="srcZone">The timezone to convert from</param> /// <param name="dstZone">The timezone to convert to</param> /// <returns>The Datetime in the new timezone</returns> public static DateTime ConvertToTimeZone(DateTime src, OlsonTimeZone srcZone, OlsonTimeZone dstZone) { DateTime ret = ConvertToUTC(src, srcZone); ret = ConvertFromUTC(ret, dstZone); return(ret); }
private void CreateAppointment( IntervalTree <Appointment> result, ExchangeUser user, OlsonTimeZone srcTimeZone, EventEntry googleAppsEvent) { Appointment appt = new Appointment(); if (googleAppsEvent.Times != null && googleAppsEvent.Times.Count > 0) { When eventTime = googleAppsEvent.Times[0]; appt.StartDate = DateTime.SpecifyKind(eventTime.StartTime.ToUniversalTime(), DateTimeKind.Unspecified); appt.EndDate = DateTime.SpecifyKind(eventTime.EndTime.ToUniversalTime(), DateTimeKind.Unspecified); log.DebugFormat("Create - [{0}] {1}", appt.Range, appt.Range.Start.Kind); appt.AllDayEvent = googleAppsEvent.Times[0].AllDay; } if (ConfigCache.SyncAppointmentDetails && googleAppsEvent.Locations != null && googleAppsEvent.Locations.Count > 0) { appt.Location = googleAppsEvent.Locations[0].ValueString ?? string.Empty; } else { appt.Location = String.Empty; } string subject = ConfigCache.PlaceHolderMessage; if (ConfigCache.SyncAppointmentDetails) { subject += ": " + ConversionsUtil.SafeGetText(googleAppsEvent.Title); if (subject.Length > 255) { subject = subject.Remove(255); } } appt.Subject = subject; if (ConfigCache.SyncAppointmentDetails) { appt.Body = ConversionsUtil.SafeGetContent(googleAppsEvent.Content); } appt.MeetingStatus = ConversionsUtil.ConvertGoogleEventStatus(googleAppsEvent.Status); appt.BusyStatus = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent); appt.Created = DateUtil.NowUtc; appt.InstanceType = InstanceType.Single; AssignOwnership(appt); result.Insert(appt.Range, appt); }
public static ComplexZmanimCalendar GetComplexZmanimCalendar(Location location, DateTime date) { ITimeZone timeZone = new OlsonTimeZone(location.TimeZone); var geoLocation = new GeoLocation(location.LocationName, location.Latitude, location.Longitude, location.Elevation, timeZone); return(new ComplexZmanimCalendar(new DateTime(date.Year, date.Month, date.Day), geoLocation)); }
public void LocalTimeConversion_should_correctly_use_time_for_daylight_saving_day_of_transition() { ITimeZone timeZone = new OlsonTimeZone("America/New_York"); var location = new GeoLocation("Lakewood, NJ", 40.09596, -74.22213, 0, timeZone); var czc = new ComplexZmanimCalendar(DateTime.Parse("11/3/2019"), location); var sunrise = czc.GetSunrise(); Assert.That(sunrise.Value.Hour, Is.EqualTo(6)); }
/// <summary> /// Convert a timezone name into a time zone object /// </summary> /// <param name="name">The timezone name</param> /// <returns>The OlsonTimeZone for the time zone</returns> public static OlsonTimeZone GetTimeZone(string name) { if (OlsonTimeZone.LookupName(name) == null) { throw new GCalExchangeException(GCalExchangeErrorCode.OlsonTZError, "Unknown destintation timezone name."); } OlsonTimeZone tz = OlsonTimeZone.GetInstance(name); return(tz); }
public void Setup() { String locationName = "Lakewood, NJ"; double latitude = 40.09596; //Lakewood, NJ double longitude = -74.22213; //Lakewood, NJ double elevation = 0; //optional elevation ITimeZone timeZone = new OlsonTimeZone("America/New_York"); GeoLocation location = new GeoLocation(locationName, latitude, longitude, elevation, timeZone); ComplexZmanimCalendar czc = new ComplexZmanimCalendar(new DateTime(2010, 4, 2), location); calendar = czc; }
public static OlsonTimeZone GetInstanceFromWin32Id(string sTZ) { lock (OlsonTimeZone.SyncRoot) { try { return(OlsonTimeZone.GetInstanceFromWin32Id(sTZ)); } catch (ArgumentException) { return(OlsonTimeZone.CurrentTimeZone); } } }
static void Main(string[] args) { string locationName = "Lakewood, NJ"; double latitude = 40.09596; //Lakewood, NJ double longitude = -74.22213; //Lakewood, NJ double elevation = 0; //optional elevation ITimeZone timeZone = new OlsonTimeZone("America/New_York"); GeoLocation location = new GeoLocation(locationName, latitude, longitude, elevation, timeZone); ComplexZmanimCalendar zc = new ComplexZmanimCalendar(location); System.Console.WriteLine("Today's Zmanim for " + locationName); System.Console.WriteLine("Sunrise: " + zc.GetSunrise()); //output sunrise System.Console.WriteLine("Sof Zman Shema MGA: " + zc.GetSofZmanShmaMGA()); //output Sof Zman Shema MGA System.Console.WriteLine("Sof Zman Shema GRA: " + zc.GetSofZmanShmaGRA()); //output Sof Zman Shema GRA System.Console.WriteLine("Sunset: " + zc.GetSunset()); //output sunset System.Console.WriteLine("Press enter to exit."); System.Console.ReadLine(); }
public void TestSunset() { var calculator = new NOAACalculator(); string locationName = "Lakewood, NJ"; double latitude = 40.09596; //Lakewood, NJ double longitude = -74.22213; //Lakewood, NJ double elevation = 0; //optional elevation ITimeZone timeZone = new OlsonTimeZone("America/New_York"); var location = new GeoLocation(locationName, latitude, longitude, elevation, timeZone); var calendar = new ComplexZmanimCalendar(new DateTime(2010, 4, 2), location); calendar.AstronomicalCalculator = calculator; var zman = calendar.GetSunrise(); Assert.That(zman, Is.EqualTo( new DateTime(2010, 4, 2, 6, 39, 17, 482) )); }
public ComplexZmanimCalendar GetCalendar() { String locationName = "Lakewood, NJ"; double latitude = 40.09596; //Lakewood, NJ double longitude = -74.22213; //Lakewood, NJ double elevation = 0; //optional elevation ITimeZone timeZone = new OlsonTimeZone("America/New_York"); GeoLocation location = new GeoLocation(locationName, latitude, longitude, elevation, timeZone); ComplexZmanimCalendar czc = new ComplexZmanimCalendar(new DateTime(2010, 4, 2), location); /* string locationName = "Brooklyn, NY"; double latitude = 40.618851; //Brooklyn, NY double longitude = -73.985921; //Brooklyn, NY double elevation = 0; //optional elevation TimeZone timeZone = TimeZone.getTimeZone("America/New_York"); var location = new GeoLocation(locationName, latitude, longitude, elevation, timeZone); var czc = new ComplexZmanimCalendar(location); czc.setCalendar(new GregorianCalendar(2010, 3, 2)); */ return czc; }
public ComplexZmanimCalendar GetCalendar() { String locationName = "Lakewood, NJ"; double latitude = 40.09596; //Lakewood, NJ double longitude = -74.22213; //Lakewood, NJ double elevation = 0; //optional elevation ITimeZone timeZone = new OlsonTimeZone("America/New_York"); GeoLocation location = new GeoLocation(locationName, latitude, longitude, elevation, timeZone); ComplexZmanimCalendar czc = new ComplexZmanimCalendar(new DateTime(2010, 4, 2), location); /* * string locationName = "Brooklyn, NY"; * double latitude = 40.618851; //Brooklyn, NY * double longitude = -73.985921; //Brooklyn, NY * double elevation = 0; //optional elevation * TimeZone timeZone = TimeZone.getTimeZone("America/New_York"); * var location = new GeoLocation(locationName, latitude, longitude, elevation, timeZone); * var czc = new ComplexZmanimCalendar(location); * czc.setCalendar(new GregorianCalendar(2010, 3, 2)); */ return(czc); }
/// <summary> /// show Times Based of Geo location /// </summary> public void LocationTimes() { string locationName; double latitude; double longitude; double elevation; XmlDocument xmlDoc = new XmlDocument(); if (!File.Exists("GeoLocation.xml")) { GeoLocationTimes glt = new GeoLocationTimes(); glt.CreateFirstGeoLocationXML(); //glt.SetGeoLocation(); } else { xmlDoc.Load("GeoLocation.xml"); XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("/Table/Geo"); string GeoID = "", GeoLocationName = "", Geolatitude = "", Geolongitude = "", Geoelevation = ""; foreach (XmlNode node in nodeList) { GeoID = node.SelectSingleNode("Geo_Id").InnerText; GeoLocationName = node.SelectSingleNode("Geo_Location_Name").InnerText; Geolatitude = node.SelectSingleNode("Latitude").InnerText; Geolongitude = node.SelectSingleNode("Longitude").InnerText; Geoelevation = node.SelectSingleNode("Elevation").InnerText; } locationName = GeoLocationName; latitude = Convert.ToDouble(Geolatitude); longitude = Convert.ToDouble(Geolongitude); elevation = Convert.ToDouble(Geoelevation); //ITimeZone timeZone = new OlsonTimeZone(PublicDomain.TzTimeZone.CurrentTimeZone); ITimeZone timeZone = new OlsonTimeZone("Asia/Jerusalem"); GeoLocation location = new GeoLocation(locationName, latitude, longitude, elevation, timeZone); ComplexZmanimCalendar zc = new ComplexZmanimCalendar(DateTime.Now, location); string TimeFormat = "HH:mm:ss"; DateTime d1, d2, d3, d4, d5, d6, d7, d8, d9; { lblTi1.Text = (locationName); d1 = (zc.GetAlosHashachar().Value); d2 = (zc.GetBeginNauticalTwilight().Value); d3 = (zc.GetSunrise().Value); d4 = (zc.GetSofZmanShmaMGA().Value); d5 = (zc.GetSofZmanShmaGRA().Value); d6 = (zc.GetMinchaGedola72Minutes().Value); d7 = (zc.GetSeaLevelSunset().Value); d8 = (zc.GetTzaisGeonim4Point37Degrees().Value); d9 = (zc.GetCandleLighting().Value); lblTi2.Text = d1.ToString(TimeFormat); lblTi3.Text = d2.ToString(TimeFormat); lblTi4.Text = d3.ToString(TimeFormat); lblTi5.Text = d4.ToString(TimeFormat); lblTi6.Text = d5.ToString(TimeFormat); lblTi7.Text = d6.ToString(TimeFormat); lblTi8.Text = d7.ToString(TimeFormat); //lblTi9.Text = (zc.GetTzaisGeonim8Point5Degrees().ToString()); //lblTi9.Text = (zc.GetTzaisGeonim3Point65Degrees().ToString()); lblTi9.Text = d8.ToString(TimeFormat); lblCandles.Text = d9.ToString(TimeFormat); } } }
/// <summary> /// Convert a time in a timezone to UTC /// </summary> /// <param name="srcTime">Time to convert</param> /// <param name="srcName">Timezone of the DateTime</param> /// <returns>DateTime in UTC</returns> public static DateTime ConvertToUTC(DateTime srcTime, string srcName) { OlsonTimeZone srcZone = GetTimeZone(srcName); return(ConvertToUTC(srcTime, srcZone)); }
/// <summary> /// Convert a date time from one timezone to another. /// </summary> /// <param name="src">The datetime to convert</param> /// <param name="srcZone">The timezone to convert from</param> /// <param name="dstZone">The timezone to convert to</param> /// <returns>The Datetime in the new timezone</returns> public static DateTime ConvertToTimeZone(DateTime src, OlsonTimeZone srcZone, OlsonTimeZone dstZone) { DateTime ret = ConvertToUTC(src, srcZone); ret = ConvertFromUTC(ret, dstZone); return ret; }
/// <summary> /// Convert a time from UTC to a timezone /// </summary> /// <param name="srcTime">Time to convert</param> /// <param name="dstName">Timezone to convert the datetime to</param> /// <returns>DateTime in the timezone</returns> public static DateTime ConvertFromUTC(DateTime srcTime, string dstName) { OlsonTimeZone dstZone = GetTimeZone(dstName); return(ConvertFromUTC(srcTime, dstZone)); }
/// <summary> /// Parses the incoming Exchange request from GCal. The requests are of the form: /// [ version #, ID, [list of emails], startdate/enddate, sincedata, timezone] /// /// </summary> /// <param name="rawInput">The incoming GCal request string</param> private void Parse(string rawInput) { if (rawInput != null) { rawInput = rawInput.Trim(); } /* Test that the request is not null or empty */ if (string.IsNullOrEmpty(rawInput)) { throw new GCalExchangeException(GCalExchangeErrorCode.MalformedRequest, "GCalRequest is null or empty."); } log.InfoFormat("Request received from GCal. [body={0}]", rawInput); /* Test that the request has starting and ending brackets */ if (!rawInput.StartsWith("[") || !rawInput.EndsWith("]")) { throw new GCalExchangeException(GCalExchangeErrorCode.MalformedRequest, String.Format("GCalRequest does start and end in brackets: [rawInput:{0}]", rawInput)); } /* Remove the start and end brackets */ string requestContent = rawInput.Remove(0, 1); requestContent = requestContent.Remove(requestContent.Length - 1, 1); /* Request is cleaned to have no ending brackets */ /* Test that the request has an inner bracket pair which (should) contains the usernames */ if (!(requestContent.Contains("[") && requestContent.IndexOf("]") > requestContent.IndexOf("["))) { throw new GCalExchangeException(GCalExchangeErrorCode.MalformedRequest, string.Format("GCalRequest exchange users section is not properly formatted: [rawInput:{0}]", rawInput)); } /* Get the indexes of the start and end username brackets */ int usersStartIndex = requestContent.IndexOf("["); int usersEndIndex = requestContent.IndexOf("]"); int usersLength = usersEndIndex - usersStartIndex + 1; /* Get the usernames string from the request */ string usersString = requestContent.Substring(usersStartIndex, usersLength); /* Remove it from the rest of the request */ requestContent = requestContent.Remove(usersStartIndex, usersLength); /* Remove the brackets from the start and end of the username string */ usersString = usersString.Remove(0, 1); usersString = usersString.Remove(usersString.Length - 1, 1); /* Split the usernames by comma, store them in the request object */ exchangeUsers = usersString.Split(','); // Apply any domain mappings to the user names for (int i = 0; i < exchangeUsers.Length; i++) { string user = exchangeUsers[i].Trim(); exchangeUsers[i] = ConfigCache.MapToLocalDomain(user); } /* Split up the rest of the request */ string[] requestItems = requestContent.Split(','); /* Test that the proper amount of variables remain in the string */ if (requestItems.Length != expectedRequestItems) { throw new GCalExchangeException(GCalExchangeErrorCode.MalformedRequest, String.Format("GCalRequest does not contain the proper amount of variables; Supplied - {0}, Expected - {1}", requestItems.Length, expectedRequestItems)); } /* Retrieve the version and message ids */ versionNumber = requestItems[0].Trim(); messageId = requestItems[1].Trim(); /* Get the start and end date from the request, the two dates are separated by '/' */ string dateString = requestItems[3].Trim(); string[] dateArray = dateString.Split('/'); if (dateArray.Length != 2) { throw new GCalExchangeException(GCalExchangeErrorCode.MalformedRequest, "GCalRequest does not contain sufficient date information, both a start and end date must be supplied"); } startDate = DateUtil.ParseGoogleDate(dateArray[0].Trim()); endDate = DateUtil.ParseGoogleDate(dateArray[1].Trim()); string requestItemSince = requestItems[4].Trim(); /* Get the since field from the request */ try { since = DateUtil.ParseGoogleDate(requestItemSince); } catch (GCalExchangeException ex) { // We don't really use this param anyway and in some cases // we've seen an invalid date log.Warn(String.Format("Ignoring incorrect since request parameter {0}", requestItemSince), ex); since = new DateTime(); } /* Get the current time zone name */ timeZone = OlsonUtil.GetTimeZone(requestItems[5].Trim()); utcStartDate = OlsonUtil.ConvertToUTC(startDate, timeZone); utcEndDate = OlsonUtil.ConvertToUTC(endDate, timeZone); }
private void CreateAppointment( IntervalTree<Appointment> result, ExchangeUser user, OlsonTimeZone srcTimeZone, EventEntry googleAppsEvent) { Appointment appt = new Appointment(); if ( googleAppsEvent.Times != null && googleAppsEvent.Times.Count > 0 ) { When eventTime = googleAppsEvent.Times[0]; appt.StartDate = DateTime.SpecifyKind(eventTime.StartTime.ToUniversalTime(), DateTimeKind.Unspecified); appt.EndDate = DateTime.SpecifyKind(eventTime.EndTime.ToUniversalTime(), DateTimeKind.Unspecified); log.DebugFormat("Create - [{0}] {1}", appt.Range, appt.Range.Start.Kind); appt.AllDayEvent = googleAppsEvent.Times[0].AllDay; } if (ConfigCache.SyncAppointmentDetails && googleAppsEvent.Locations != null && googleAppsEvent.Locations.Count > 0 ) { appt.Location = googleAppsEvent.Locations[0].ValueString ?? string.Empty; } else { appt.Location = String.Empty; } string subject = ConfigCache.PlaceHolderMessage; if (ConfigCache.SyncAppointmentDetails) { subject += ": " + ConversionsUtil.SafeGetText(googleAppsEvent.Title); if (subject.Length > 255) { subject = subject.Remove(255); } } appt.Subject = subject; if (ConfigCache.SyncAppointmentDetails) { appt.Body = ConversionsUtil.SafeGetContent(googleAppsEvent.Content); } appt.MeetingStatus = ConversionsUtil.ConvertGoogleEventStatus(googleAppsEvent.Status); appt.BusyStatus = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent); appt.Created = DateUtil.NowUtc; appt.InstanceType = InstanceType.Single; AssignOwnership( appt ); result.Insert(appt.Range, appt); }
/// <summary> /// Merges a users appointment schedule from with appointments generated from a /// GoogleApps feed /// </summary> /// <param name="user">User to update with Google Apps information</param> /// <param name="googleAppsFeed">Source feed to generate appointment information</param> /// <param name="exchangeGateway">Gateway to sync Appointments with</param> /// <param name="window">DateRange to sync for</param> public void SyncUser( ExchangeUser user, EventFeed googleAppsFeed, ExchangeService exchangeGateway, DateTimeRange window) { exchangeGateway.GetCalendarInfoForUser(user, window); if (!user.HaveAppointmentDetail) { // Cannot sync if there is no appointment detail log.InfoFormat("Skipped Sync of {0} due to missing appointment lookup failure", user.Email); return; } List <Appointment> toUpdate = new List <Appointment>(); List <Appointment> toDelete = new List <Appointment>(); List <Appointment> toCreate = new List <Appointment>(); OlsonTimeZone feedTimeZone = OlsonUtil.GetTimeZone(googleAppsFeed.TimeZone.Value); IntervalTree <Appointment> gcalApptTree = CreateAppointments(user, feedTimeZone, googleAppsFeed); /* Iterate through each Free/Busy time block for the user */ foreach (FreeBusyTimeBlock fbtb in user.BusyTimes.Values) { /* Iterate through each appointment for the Free/Busy time block */ foreach (Appointment appt in fbtb.Appointments) { log.Debug(String.Format("Exchange @ '{0} {1}'", appt.Range, ValidateOwnership(appt))); /* Validate that this is a GCalender appoint */ if (ValidateOwnership(appt)) { /* If the GCalender appointments do not contain an * appointment for this period, add it for deletion */ if (gcalApptTree.FindExact(appt.Range) == null) { toDelete.Add(appt); } } } } /* Iterate through each Google Apps appointment */ AppointmentCollection appointments = user.BusyTimes.Appointments; List <Appointment> gcalApptList = gcalApptTree.GetNodeList(); foreach (Appointment newAppt in gcalApptList) { // If the meeting was cancelled log.DebugFormat("Looking @ {0} {1}", newAppt.Range, newAppt.Range.Start.Kind); if (newAppt.MeetingStatus == MeetingStatus.Cancelled) { // Check if there is an existing appointment that matches List <Appointment> matches = appointments.Get(newAppt.Range); foreach (Appointment a in matches) { if (ValidateOwnership(a)) { toDelete.Add(a); } } // Work is done for this appointment, continue to next entry continue; } bool updatedAppointment = false; List <Appointment> apptList = appointments.Get(newAppt.Range); log.DebugFormat("Looking up preexisting event: {0} {1}", newAppt.Range, newAppt.Range.Start.Kind); log.DebugFormat("Found {0} matching items", apptList.Count); // Check that there is a free busy block that correlates with this appointment foreach (Appointment existingAppt in apptList) { if (ValidateOwnership(existingAppt) && !updatedAppointment) { UpdateAppointmentInfo(existingAppt, newAppt); toUpdate.Add(existingAppt); updatedAppointment = true; } } if (!updatedAppointment) { toCreate.Add(newAppt); log.DebugFormat("ADDING '{0}' - Not an update", newAppt.Range); } } if (log.IsInfoEnabled) { log.InfoFormat( "AppointmentWriter for '{0}'. [{1} deleted, {2} updated, {3} new]", user.Email, toDelete.Count, toUpdate.Count, toCreate.Count); } exchangeGateway.Appointments.DeleteAppointments(user, toDelete); // TODO: Updates are not currently published // exchangeGateway.Appointments.UpdateAppointments( user, updateAppointments ); exchangeGateway.Appointments.WriteAppointments(user, toCreate); }
private static void Main(string[] args) { options = new ZmanimOptions(); p = new OptionSet { { "d|date=", "Set date. <mm/dd/yyyy>", x => options.Date = DateTime.ParseExact(x, "MM/dd/yyyy", CultureInfo.InvariantCulture) }, { "lat|latitude=", "Set location's latitude", (double x) => options.Latitude = x }, { "lon|longitude=", "Set location's longitude", (double x) => options.Longitude = x }, { "e|elevation=", "Set location's elevation; Positive only", (double x) => options.Elevation = x }, { "tz|timezone=", "Set location's TimeZone", x => options.TimeZone = x }, { "tf|timeformat=", "Set the way the application formats a DateTime object.", x => options.DateTimeFormat = x }, { "h|?|help", "Shows this help message", v => ShowHelp() } }; List <string> extraArgs; try { extraArgs = p.Parse(args); } catch (OptionException) { ShowHelp(); return; } var timeZone = new OlsonTimeZone(options.TimeZone); var location = new GeoLocation(string.Empty, options.Latitude, options.Longitude, options.Elevation, timeZone); var czc = new ComplexZmanimCalendar(new DateTime(options.Date.Year, options.Date.Month, options.Date.Day), location); var methods = GetDateTimeAndLongMethods(); foreach (var first in extraArgs.Select(extraArg => methods.Where( f => f.Name.Remove(0, 3).ToLowerInvariant() == extraArg.ToLowerInvariant()).First()) ) { object invoke = first.Invoke(czc, null); if (extraArgs.Count > 1) { Console.Write(first.Name.Remove(0, 3) + ": "); } if (invoke.GetType() == typeof(DateTime)) { var time = (DateTime)invoke; Console.Write(time.ToString(options.DateTimeFormat)); } else if (invoke.GetType() == typeof(long)) { Console.WriteLine((long)invoke); } if (extraArgs.Count > 1) { Console.WriteLine(); } } //Console.Read(); }
/// <summary> /// Returns a set of appointments from a GoogleApps Feed /// </summary> /// <param name="user">The exchange user to get apointments for</param> /// <param name="srcTimeZone">The time zone to use</param> /// <param name="googleAppsFeed">Source feed to create array from</param> /// <returns></returns> private IntervalTree<Appointment> CreateAppointments( ExchangeUser user, OlsonTimeZone srcTimeZone, EventFeed googleAppsFeed) { IntervalTree<Appointment> result = new IntervalTree<Appointment>(); foreach ( EventEntry eventEntry in googleAppsFeed.Entries ) { try { CreateAppointment(result, user, srcTimeZone, eventEntry); } catch ( GCalExchangeException ex ) { if ( ex.ErrorCode == GCalExchangeErrorCode.OlsonTZError ) { log.Error( "Error creating appointment (TimeZone issue)", ex ); } else { throw; } } } return result; }