public static string FixTimeZoneComponentOrderNoThrow (string iCalendarData)
{
if (string.IsNullOrEmpty (iCalendarData))
return iCalendarData;
try
{
var newCalendarData = iCalendarData;
for (
var timeZoneMatch = Regex.Match (iCalendarData, "BEGIN:VTIMEZONE\r?\n(.|\n)*?END:VTIMEZONE\r?\n", RegexOptions.RightToLeft);
timeZoneMatch.Success;
timeZoneMatch = timeZoneMatch.NextMatch())
{
var sections = new List<Tuple<Match, DateTime>>();
for (
var sectionMatch = Regex.Match (timeZoneMatch.Value, "BEGIN:STANDARD\r?\n(.|\n)*?END:STANDARD\r?\n", RegexOptions.RightToLeft);
sectionMatch.Success;
sectionMatch = sectionMatch.NextMatch())
{
var startMatch = Regex.Match (sectionMatch.Value, "DTSTART:(.*?)\r?\n");
if (startMatch.Success)
{
DateTime date;
if (DateTime.TryParseExact (startMatch.Groups[1].Value, "yyyyMMdd'T'HHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
sections.Add (Tuple.Create (sectionMatch, date));
}
}
}
for (
var sectionMatch = Regex.Match (timeZoneMatch.Value, "BEGIN:DAYLIGHT\r?\n(.|\n)*?END:DAYLIGHT\r?\n", RegexOptions.RightToLeft);
sectionMatch.Success;
sectionMatch = sectionMatch.NextMatch())
{
var startMatch = Regex.Match (sectionMatch.Value, "DTSTART:(.*?)\r?\n");
if (startMatch.Success)
{
DateTime date;
if (DateTime.TryParseExact (startMatch.Groups[1].Value, "yyyyMMdd'T'HHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
sections.Add (Tuple.Create (sectionMatch, date));
}
}
}
if (sections.Count > 0)
{
Match firstSection = null;
var newTimeZoneData = timeZoneMatch.Value;
foreach (var section in sections.OrderByDescending (s => s.Item1.Index))
{
newTimeZoneData = newTimeZoneData.Remove (section.Item1.Index, section.Item1.Length);
firstSection = section.Item1;
}
foreach (var section in sections.OrderByDescending (s => s.Item2))
{
newTimeZoneData = newTimeZoneData.Insert (firstSection.Index, section.Item1.Value);
}
newCalendarData = newCalendarData.Remove (timeZoneMatch.Index, timeZoneMatch.Length);
newCalendarData = newCalendarData.Insert (timeZoneMatch.Index, newTimeZoneData);
}
}
return newCalendarData;
}
catch (Exception x)
{
s_logger.Error ("Could not process calender data. Using original data", x);
return iCalendarData;
}
}