public override string SerializeToString(object obj) { IPeriodList rdt = obj as IPeriodList; ISerializerFactory factory = GetService <ISerializerFactory>(); if (rdt != null && factory != null) { IStringSerializer dtSerializer = factory.Build(typeof(IDateTime), SerializationContext) as IStringSerializer; IStringSerializer periodSerializer = factory.Build(typeof(IPeriod), SerializationContext) as IStringSerializer; if (dtSerializer != null && periodSerializer != null) { List <string> parts = new List <string>(); foreach (IPeriod p in rdt) { if (p.EndTime != null) { parts.Add(periodSerializer.SerializeToString(p)); } else if (p.StartTime != null) { parts.Add(dtSerializer.SerializeToString(p.StartTime)); } } return(Encode(rdt, string.Join(",", parts.ToArray()))); } } return(null); }
public override string SerializeToString(object obj) { ICalendarComponent c = obj as ICalendarComponent; if (c != null) { StringBuilder sb = new StringBuilder(); sb.Append(TextUtil.WrapLines("BEGIN:" + c.Name.ToUpper())); // Get a serializer factory ISerializerFactory sf = GetService <ISerializerFactory>(); // Sort the calendar properties in alphabetical order before // serializing them! List <ICalendarProperty> properties = new List <ICalendarProperty>(c.Properties); // FIXME: remove this try/catch try { properties.Sort(PropertySorter); } catch (Exception e) { throw; } // Serialize properties foreach (ICalendarProperty p in properties) { // Get a serializer for each property. IStringSerializer serializer = sf.Build(p.GetType(), SerializationContext) as IStringSerializer; if (serializer != null) { sb.Append(serializer.SerializeToString(p)); } } // Serialize child objects if (sf != null) { foreach (ICalendarObject child in c.Children) { // Get a serializer for each child object. IStringSerializer serializer = sf.Build(child.GetType(), SerializationContext) as IStringSerializer; if (serializer != null) { sb.Append(serializer.SerializeToString(child)); } } } sb.Append(TextUtil.WrapLines("END:" + c.Name.ToUpper())); return(sb.ToString()); } return(null); }
protected void SerializeValue(ISerializerFactory sf, ICalendarProperty prop, Type valueType, object v, StringBuilder result) { // Get a serializer to serialize the property's value. // If we can't serialize the property's value, the next step is worthless anyway. IStringSerializer valueSerializer = sf.Build(valueType, SerializationContext) as IStringSerializer; if (valueSerializer != null) { // Iterate through each value to be serialized, // and give it a property (with parameters). // FIXME: this isn't always the way this is accomplished. // Multiple values can often be serialized within the // same property. How should we fix this? // NOTE: // We Serialize the property's value first, as during // serialization it may modify our parameters. // FIXME: the "parameter modification" operation should // be separated from serialization. Perhaps something // like PreSerialize(), etc. string value = valueSerializer.SerializeToString(v); // Get the list of parameters we'll be serializing ICalendarParameterCollection parameterList = prop.Parameters; if (v is ICalendarDataType) { parameterList = ((ICalendarDataType)v).Parameters; } StringBuilder sb = new StringBuilder(prop.Name); if (parameterList.Any()) { // Get a serializer for parameters IStringSerializer parameterSerializer = sf.Build(typeof(ICalendarParameter), SerializationContext) as IStringSerializer; if (parameterSerializer != null) { // Serialize each parameter List <string> parameters = new List <string>(); foreach (ICalendarParameter param in parameterList) { parameters.Add(parameterSerializer.SerializeToString(param)); } // Separate parameters with semicolons sb.Append(";"); sb.Append(string.Join(";", parameters.ToArray())); } } sb.Append(":"); sb.Append(value); result.Append(TextUtil.WrapLines(sb.ToString())); } }
protected void SerializeValue(ISerializerFactory sf, ICalendarProperty prop, Type valueType, object v, StringBuilder result) { // Get a serializer to serialize the property's value. // If we can't serialize the property's value, the next step is worthless anyway. IStringSerializer valueSerializer = sf.Build(valueType, SerializationContext) as IStringSerializer; if (valueSerializer != null) { // Iterate through each value to be serialized, // and give it a property (with parameters). // FIXME: this isn't always the way this is accomplished. // Multiple values can often be serialized within the // same property. How should we fix this? // NOTE: // We Serialize the property's value first, as during // serialization it may modify our parameters. // FIXME: the "parameter modification" operation should // be separated from serialization. Perhaps something // like PreSerialize(), etc. string value = valueSerializer.SerializeToString(v); // Get the list of parameters we'll be serializing ICalendarParameterCollection parameterList = prop.Parameters; if (v is ICalendarDataType) parameterList = ((ICalendarDataType)v).Parameters; StringBuilder sb = new StringBuilder(prop.Name); if (parameterList.Any()) { // Get a serializer for parameters IStringSerializer parameterSerializer = sf.Build(typeof(ICalendarParameter), SerializationContext) as IStringSerializer; if (parameterSerializer != null) { // Serialize each parameter List<string> parameters = new List<string>(); foreach (ICalendarParameter param in parameterList) { parameters.Add(parameterSerializer.SerializeToString(param)); } // Separate parameters with semicolons sb.Append(";"); sb.Append(string.Join(";", parameters.ToArray())); } } sb.Append(":"); sb.Append(value); result.Append(TextUtil.WrapLines(sb.ToString())); } }
/// <summary> /// Returns a serializer that can be used to serialize and object /// of type <paramref name="objectType"/>. /// <note> /// TODO: Add support for caching. /// </note> /// </summary> /// <param name="objectType">The type of object to be serialized.</param> /// <param name="ctx">The serialization context.</param> public virtual ISerializer Build(Type objectType, SerializationContext ctx) { if (objectType == null) { return(null); } ISerializer s; if (typeof(Calendar).IsAssignableFrom(objectType)) { s = new CalendarSerializer(ctx); } else if (typeof(ICalendarComponent).IsAssignableFrom(objectType)) { s = typeof(CalendarEvent).IsAssignableFrom(objectType) ? new EventSerializer(ctx) : new ComponentSerializer(ctx); } else if (typeof(ICalendarProperty).IsAssignableFrom(objectType)) { s = new PropertySerializer(ctx); } else if (typeof(CalendarParameter).IsAssignableFrom(objectType)) { s = new ParameterSerializer(ctx); } else if (typeof(string).IsAssignableFrom(objectType)) { s = new StringSerializer(ctx); } else if (objectType.GetTypeInfo().IsEnum) { s = new EnumSerializer(objectType, ctx); } else if (typeof(TimeSpan).IsAssignableFrom(objectType)) { s = new TimeSpanSerializer(ctx); } else if (typeof(int).IsAssignableFrom(objectType)) { s = new IntegerSerializer(ctx); } else if (typeof(Uri).IsAssignableFrom(objectType)) { s = new UriSerializer(ctx); } else if (typeof(ICalendarDataType).IsAssignableFrom(objectType)) { s = _mDataTypeSerializerFactory.Build(objectType, ctx); } // Default to a string serializer, which simply calls // ToString() on the value to serialize it. else { s = new StringSerializer(ctx); } return(s); }
public override object Deserialize(TextReader tr) { string value = tr.ReadToEnd(); IPeriod p = CreateAndAssociate() as IPeriod; ISerializerFactory factory = GetService <ISerializerFactory>(); if (p != null && factory != null) { IStringSerializer dtSerializer = factory.Build(typeof(IDateTime), SerializationContext) as IStringSerializer; IStringSerializer durationSerializer = factory.Build(typeof(TimeSpan), SerializationContext) as IStringSerializer; if (dtSerializer != null && durationSerializer != null) { // Decode the value as necessary value = Decode(p, value); string[] values = value.Split('/'); if (values.Length != 2) { return(false); } StringReader reader = new StringReader(values[0]); p.StartTime = dtSerializer.Deserialize(reader) as IDateTime; reader.Dispose(); reader = new StringReader(values[1]); p.EndTime = dtSerializer.Deserialize(reader) as IDateTime; reader.Dispose(); if (p.EndTime == null) { reader = new StringReader(values[1]); p.Duration = (TimeSpan)durationSerializer.Deserialize(reader); reader.Dispose(); } // Only return an object if it has been deserialized correctly. if (p.StartTime != null && p.Duration != null) { return(p); } } } return(null); }
public override object Deserialize(TextReader tr) { string value = tr.ReadToEnd(); ITrigger t = CreateAndAssociate() as ITrigger; if (t != null) { // Push the trigger onto the serialization stack SerializationContext.Push(t); try { // Decode the value as needed value = Decode(t, value); // Set the trigger relation if (t.Parameters.ContainsKey("RELATED") && t.Parameters.Get("RELATED").Equals("END")) { t.Related = TriggerRelation.End; } ISerializerFactory factory = GetService <ISerializerFactory>(); if (factory != null) { Type valueType = t.GetValueType() ?? typeof(TimeSpan); IStringSerializer serializer = factory.Build(valueType, SerializationContext) as IStringSerializer; if (serializer != null) { StringReader reader = new StringReader(value); object obj = serializer.Deserialize(reader); reader.Dispose(); if (obj != null) { if (obj is IDateTime) { t.DateTime = (IDateTime)obj; } else { t.Duration = (TimeSpan)obj; } return(t); } } } } finally { // Pop the trigger off the serialization stack SerializationContext.Pop(); } } return(null); }
public override object Deserialize(TextReader tr) { string value = tr.ReadToEnd(); // Create the day specifier and associate it with a calendar object IPeriodList rdt = CreateAndAssociate() as IPeriodList; ISerializerFactory factory = GetService <ISerializerFactory>(); if (rdt != null && factory != null) { // Decode the value, if necessary value = Decode(rdt, value); IStringSerializer dtSerializer = factory.Build(typeof(IDateTime), SerializationContext) as IStringSerializer; IStringSerializer periodSerializer = factory.Build(typeof(IPeriod), SerializationContext) as IStringSerializer; if (dtSerializer != null && periodSerializer != null) { string[] values = value.Split(','); foreach (string v in values) { StringReader reader = new StringReader(v); IDateTime dt = dtSerializer.Deserialize(reader) as IDateTime; reader.Dispose(); reader = new StringReader(v); IPeriod p = periodSerializer.Deserialize(reader) as IPeriod; reader.Dispose(); if (dt != null) { dt.AssociatedObject = rdt.AssociatedObject; rdt.Add(dt); } else if (p != null) { p.AssociatedObject = rdt.AssociatedObject; rdt.Add(p); } } return(rdt); } } return(null); }
public override object Deserialize(TextReader tr) { string value = tr.ReadToEnd(); IRequestStatus rs = CreateAndAssociate() as IRequestStatus; if (rs != null) { // Decode the value as needed value = Decode(rs, value); // Push the object onto the serialization stack SerializationContext.Push(rs); try { ISerializerFactory factory = GetService <ISerializerFactory>(); if (factory != null) { Match match = Regex.Match(value, @"(.*?[^\\]);(.*?[^\\]);(.+)"); if (!match.Success) { match = Regex.Match(value, @"(.*?[^\\]);(.+)"); } if (match.Success) { IStringSerializer serializer = factory.Build(typeof(IStatusCode), SerializationContext) as IStringSerializer; if (serializer != null) { StringReader reader = new StringReader(Unescape(match.Groups[1].Value)); rs.StatusCode = serializer.Deserialize(reader) as IStatusCode; reader.Dispose(); rs.Description = Unescape(match.Groups[2].Value); if (match.Groups.Count == 4) { rs.ExtraData = Unescape(match.Groups[3].Value); } return(rs); } } } } finally { // Pop the object off the serialization stack SerializationContext.Pop(); } } return(null); }
private void WriteObject(ICalendarObject calendarObject) { // Get a serializer for each child object. var serializer = _serializerFactory.Build( calendarObject.GetType(), SerializationContext) as IStringSerializer; if (serializer != null) { _writer.Write(serializer.SerializeToString(calendarObject)); } }
public override string SerializeToString(object obj) { IPeriod p = obj as IPeriod; ISerializerFactory factory = GetService <ISerializerFactory>(); if (p != null && factory != null) { // Push the period onto the serialization context stack SerializationContext.Push(p); try { IStringSerializer dtSerializer = factory.Build(typeof(IDateTime), SerializationContext) as IStringSerializer; IStringSerializer timeSpanSerializer = factory.Build(typeof(TimeSpan), SerializationContext) as IStringSerializer; if (dtSerializer != null && timeSpanSerializer != null) { StringBuilder sb = new StringBuilder(); // Serialize the start time sb.Append(dtSerializer.SerializeToString(p.StartTime)); // Serialize the duration if (p.Duration != null) { sb.Append("/"); sb.Append(timeSpanSerializer.SerializeToString(p.Duration)); } // Encode the value as necessary return(Encode(p, sb.ToString())); } } finally { // Pop the period off the serialization context stack SerializationContext.Pop(); } } return(null); }
public override string SerializeToString(object obj) { try { IRequestStatus rs = obj as IRequestStatus; if (rs != null) { // Push the object onto the serialization stack SerializationContext.Push(rs); try { ISerializerFactory factory = GetService <ISerializerFactory>(); if (factory != null) { IStringSerializer serializer = factory.Build(typeof(IStatusCode), SerializationContext) as IStringSerializer; if (serializer != null) { string value = Escape(serializer.SerializeToString(rs.StatusCode)); value += ";" + Escape(rs.Description); if (!string.IsNullOrEmpty(rs.ExtraData)) { value += ";" + Escape(rs.ExtraData); } return(Encode(rs, value)); } } } finally { // Pop the object off the serialization stack SerializationContext.Pop(); } } return(null); } catch { return(null); } }
public ISerializer Build(Type objectType, ISerializationContext ctx) { if (objectType != null) { ISerializer serializer = null; if (typeof(IAttendee).IsAssignableFrom(objectType)) { serializer = new CustomAttendeeSerializer(); } if (serializer != null) { serializer.SerializationContext = ctx; return(serializer); } } return(_decorated.Build(objectType, ctx)); }
private void SetPropertyValue(SerializationContext context, CalendarProperty property, string value) { var type = _dataTypeMapper.GetPropertyMapping(property) ?? typeof(string); var serializer = (SerializerBase)_serializerFactory.Build(type, context); using (var valueReader = new StringReader(value)) { var propertyValue = serializer.Deserialize(valueReader); var propertyValues = propertyValue as IEnumerable <string>; if (propertyValues != null) { foreach (var singlePropertyValue in propertyValues) { property.AddValue(singlePropertyValue); } } else { property.AddValue(propertyValue); } } }
public override string SerializeToString(object obj) { try { ITrigger t = obj as ITrigger; if (t != null) { // Push the trigger onto the serialization stack SerializationContext.Push(t); try { ISerializerFactory factory = GetService <ISerializerFactory>(); if (factory != null) { Type valueType = t.GetValueType() ?? typeof(TimeSpan); IStringSerializer serializer = factory.Build(valueType, SerializationContext) as IStringSerializer; if (serializer != null) { object value = (valueType == typeof(IDateTime)) ? (object)t.DateTime : (object)t.Duration; return(serializer.SerializeToString(value)); } } } finally { // Pop the trigger off the serialization stack SerializationContext.Pop(); } } return(null); } catch { return(null); } }
protected IStringSerializer GetMappedSerializer() { ISerializerFactory sf = GetService <ISerializerFactory>(); IDataTypeMapper mapper = GetService <IDataTypeMapper>(); if (sf != null && mapper != null) { object obj = SerializationContext.Peek(); // Get the data type for this object Type type = mapper.GetPropertyMapping(obj); if (type != null) { return(sf.Build(type, SerializationContext) as IStringSerializer); } else { return(new StringSerializer(SerializationContext)); } } return(null); }
public override string SerializeToString(object obj) { IRecurrencePattern recur = obj as IRecurrencePattern; ISerializerFactory factory = GetService<ISerializerFactory>(); if (recur != null && factory != null) { // Push the recurrence pattern onto the serialization stack SerializationContext.Push(recur); List<string> values = new List<string>(); values.Add("FREQ=" + Enum.GetName(typeof(FrequencyType), recur.Frequency).ToUpper()); //-- FROM RFC2445 -- //The INTERVAL rule part contains a positive integer representing how //often the recurrence rule repeats. The default value is "1", meaning //every second for a SECONDLY rule, or every minute for a MINUTELY //rule, every hour for an HOURLY rule, every day for a DAILY rule, //every week for a WEEKLY rule, every month for a MONTHLY rule and //every year for a YEARLY rule. int interval = recur.Interval; if (interval == int.MinValue) interval = 1; if (interval != 1) values.Add("INTERVAL=" + interval); if (recur.Until != DateTime.MinValue) { IStringSerializer serializer = factory.Build(typeof(IDateTime), SerializationContext) as IStringSerializer; if (serializer != null) { IDateTime until = new iCalDateTime(recur.Until); until.HasTime = true; values.Add("UNTIL=" + serializer.SerializeToString(until)); } } if (recur.FirstDayOfWeek != DayOfWeek.Monday) values.Add("WKST=" + Enum.GetName(typeof(DayOfWeek), recur.FirstDayOfWeek).ToUpper().Substring(0, 2)); if (recur.Count != int.MinValue) values.Add("COUNT=" + recur.Count); if (recur.ByDay.Count > 0) { List<string> bydayValues = new List<string>(); IStringSerializer serializer = factory.Build(typeof(IWeekDay), SerializationContext) as IStringSerializer; if (serializer != null) { foreach (WeekDay byday in recur.ByDay) bydayValues.Add(serializer.SerializeToString(byday)); } values.Add("BYDAY=" + string.Join(",", bydayValues.ToArray())); } SerializeByValue(values, recur.ByHour, "BYHOUR"); SerializeByValue(values, recur.ByMinute, "BYMINUTE"); SerializeByValue(values, recur.ByMonth, "BYMONTH"); SerializeByValue(values, recur.ByMonthDay, "BYMONTHDAY"); SerializeByValue(values, recur.BySecond, "BYSECOND"); SerializeByValue(values, recur.BySetPosition, "BYSETPOS"); SerializeByValue(values, recur.ByWeekNo, "BYWEEKNO"); SerializeByValue(values, recur.ByYearDay, "BYYEARDAY"); // Pop the recurrence pattern off the serialization stack SerializationContext.Pop(); return Encode(recur, string.Join(";", values.ToArray())); } return null; }
public override object Deserialize(TextReader tr) { ICalendarProperty p = SerializationContext.Peek() as ICalendarProperty; if (p != null) { // Get a serializer factory to deserialize the contents of this list ISerializerFactory sf = GetService <ISerializerFactory>(); object listObj = Activator.CreateInstance(_ObjectType); if (listObj != null) { // Get a serializer for the inner type IStringSerializer stringSerializer = sf.Build(_InnerType, SerializationContext) as IStringSerializer;; if (stringSerializer != null) { // Deserialize the inner object string value = tr.ReadToEnd(); object objToAdd = stringSerializer.Deserialize(new StringReader(value)); // If deserialization failed, pass the string value // into the list. if (objToAdd == null) { objToAdd = value; } if (objToAdd != null) { // FIXME: cache this MethodInfo mi = _ObjectType.GetMethod("Add"); if (mi != null) { // Determine if the returned object is an IList<ObjectType>, // rather than just an ObjectType. if (objToAdd is IEnumerable && objToAdd.GetType().Equals(typeof(List <>).MakeGenericType(_InnerType))) { // Deserialization returned an IList<ObjectType>, instead of // simply an ObjectType. So, let's enumerate through the // items in the list and add them individually to our // list. foreach (object innerObj in (IEnumerable)objToAdd) { mi.Invoke(listObj, new object[] { innerObj }); } } else { // Add the object to the list mi.Invoke(listObj, new object[] { objToAdd }); } return(listObj); } } } } } return(null); }
public override string SerializeToString(object obj) { ICalendarProperty prop = obj as ICalendarProperty; if (prop != null && prop.Value != null) { // Don't serialize the property if the value is null // Push this object on the serialization context. SerializationContext.Push(prop); IDataTypeMapper mapper = GetService <IDataTypeMapper>(); Type serializedType = mapper.GetPropertyMapping(prop); // Build a list of values that are to be serialized. List <object> objs = new List <object>(); if (!(prop.Value is string) && !(typeof(IEnumerable <string>).IsAssignableFrom(serializedType)) && prop.Value is IEnumerable) { foreach (object v in (IEnumerable)prop.Value) { objs.Add(v); } } else { objs.Add(prop.Value); } // Get a serializer factory that we can use to serialize // the property and parameter values ISerializerFactory sf = GetService <ISerializerFactory>(); StringBuilder result = new StringBuilder(); foreach (object v in objs) { // Get a serializer to serialize the property's value. // If we can't serialize the property's value, the next step is worthless anyway. IStringSerializer valueSerializer = sf.Build(v.GetType(), SerializationContext) as IStringSerializer; if (valueSerializer != null) { // Iterate through each value to be serialized, // and give it a property (with parameters). // FIXME: this isn't always the way this is accomplished. // Multiple values can often be serialized within the // same property. How should we fix this? // NOTE: // We Serialize the property's value first, as during // serialization it may modify our parameters. // FIXME: the "parameter modification" operation should // be separated from serialization. Perhaps something // like PreSerialize(), etc. string value = valueSerializer.SerializeToString(v); // Get the list of parameters we'll be serializing ICalendarParameterList parameterList = prop.Parameters; if (v is ICalendarDataType) { parameterList = ((ICalendarDataType)v).Parameters; } StringBuilder sb = new StringBuilder(prop.Name); if (parameterList.Count > 0) { // Get a serializer for parameters IStringSerializer parameterSerializer = sf.Build(typeof(ICalendarParameter), SerializationContext) as IStringSerializer; if (parameterSerializer != null) { // Serialize each parameter List <string> parameters = new List <string>(); foreach (ICalendarParameter param in parameterList) { parameters.Add(parameterSerializer.SerializeToString(param)); } // Separate parameters with semicolons sb.Append(";"); sb.Append(string.Join(";", parameters.ToArray())); } } sb.Append(":"); sb.Append(value); result.Append(TextUtil.WrapLines(sb.ToString())); } } // Pop the object off the serialization context. SerializationContext.Pop(); return(result.ToString()); } return(null); }
public override object Deserialize(TextReader tr) { string value = tr.ReadToEnd(); // Instantiate the data type IRecurrencePattern r = CreateAndAssociate() as IRecurrencePattern; ISerializerFactory factory = GetService<ISerializerFactory>(); if (r != null && factory != null) { // Decode the value, if necessary value = Decode(r, value); Match match = Regex.Match(value, @"FREQ=(SECONDLY|MINUTELY|HOURLY|DAILY|WEEKLY|MONTHLY|YEARLY);?(.*)", RegexOptions.IgnoreCase); if (match.Success) { // Parse the frequency type r.Frequency = (FrequencyType)Enum.Parse(typeof(FrequencyType), match.Groups[1].Value, true); // NOTE: fixed a bug where the group 2 match // resulted in an empty string, which caused // an error. if (match.Groups[2].Success && match.Groups[2].Length > 0) { string[] keywordPairs = match.Groups[2].Value.Split(';'); foreach (string keywordPair in keywordPairs) { string[] keyValues = keywordPair.Split('='); string keyword = keyValues[0]; string keyValue = keyValues[1]; switch (keyword.ToUpper()) { case "UNTIL": { IStringSerializer serializer = factory.Build(typeof(IDateTime), SerializationContext) as IStringSerializer; if (serializer != null) { IDateTime dt = serializer.Deserialize(new StringReader(keyValue)) as IDateTime; if (dt != null) r.Until = dt.Value; } } break; case "COUNT": r.Count = Convert.ToInt32(keyValue); break; case "INTERVAL": r.Interval = Convert.ToInt32(keyValue); break; case "BYSECOND": AddInt32Values(r.BySecond, keyValue); break; case "BYMINUTE": AddInt32Values(r.ByMinute, keyValue); break; case "BYHOUR": AddInt32Values(r.ByHour, keyValue); break; case "BYDAY": { string[] days = keyValue.Split(','); foreach (string day in days) r.ByDay.Add(new WeekDay(day)); } break; case "BYMONTHDAY": AddInt32Values(r.ByMonthDay, keyValue); break; case "BYYEARDAY": AddInt32Values(r.ByYearDay, keyValue); break; case "BYWEEKNO": AddInt32Values(r.ByWeekNo, keyValue); break; case "BYMONTH": AddInt32Values(r.ByMonth, keyValue); break; case "BYSETPOS": AddInt32Values(r.BySetPosition, keyValue); break; case "WKST": r.FirstDayOfWeek = GetDayOfWeek(keyValue); break; } } } } else if ((match = Regex.Match(value, @"every\s+(?<Interval>other|\d+)?\w{0,2}\s*(?<Freq>second|minute|hour|day|week|month|year)s?,?\s*(?<More>.+)", RegexOptions.IgnoreCase)).Success) { if (match.Groups["Interval"].Success) { int interval; if (!int.TryParse(match.Groups["Interval"].Value, out interval)) r.Interval = 2; // "other" else r.Interval = interval; } else r.Interval = 1; switch (match.Groups["Freq"].Value.ToLower()) { case "second": r.Frequency = FrequencyType.Secondly; break; case "minute": r.Frequency = FrequencyType.Minutely; break; case "hour": r.Frequency = FrequencyType.Hourly; break; case "day": r.Frequency = FrequencyType.Daily; break; case "week": r.Frequency = FrequencyType.Weekly; break; case "month": r.Frequency = FrequencyType.Monthly; break; case "year": r.Frequency = FrequencyType.Yearly; break; } string[] values = match.Groups["More"].Value.Split(','); foreach (string item in values) { if ((match = Regex.Match(item, @"(?<Num>\d+)\w\w\s+(?<Type>second|minute|hour|day|week|month)", RegexOptions.IgnoreCase)).Success || (match = Regex.Match(item, @"(?<Type>second|minute|hour|day|week|month)\s+(?<Num>\d+)", RegexOptions.IgnoreCase)).Success) { int num; if (int.TryParse(match.Groups["Num"].Value, out num)) { switch (match.Groups["Type"].Value.ToLower()) { case "second": r.BySecond.Add(num); break; case "minute": r.ByMinute.Add(num); break; case "hour": r.ByHour.Add(num); break; case "day": switch (r.Frequency) { case FrequencyType.Yearly: r.ByYearDay.Add(num); break; case FrequencyType.Monthly: r.ByMonthDay.Add(num); break; } break; case "week": r.ByWeekNo.Add(num); break; case "month": r.ByMonth.Add(num); break; } } } else if ((match = Regex.Match(item, @"(?<Num>\d+\w{0,2})?(\w|\s)+?(?<First>first)?(?<Last>last)?\s*((?<Day>sunday|monday|tuesday|wednesday|thursday|friday|saturday)\s*(and|or)?\s*)+", RegexOptions.IgnoreCase)).Success) { int num = int.MinValue; if (match.Groups["Num"].Success) { if (int.TryParse(match.Groups["Num"].Value, out num)) { if (match.Groups["Last"].Success) { // Make number negative num *= -1; } } } else if (match.Groups["Last"].Success) num = -1; else if (match.Groups["First"].Success) num = 1; foreach (Capture capture in match.Groups["Day"].Captures) { WeekDay ds = new WeekDay((DayOfWeek)Enum.Parse(typeof(DayOfWeek), capture.Value, true)); ds.Offset = num; r.ByDay.Add(ds); } } else if ((match = Regex.Match(item, @"at\s+(?<Hour>\d{1,2})(:(?<Minute>\d{2})((:|\.)(?<Second>\d{2}))?)?\s*(?<Meridian>(a|p)m?)?", RegexOptions.IgnoreCase)).Success) { int hour, minute, second; if (int.TryParse(match.Groups["Hour"].Value, out hour)) { // Adjust for PM if (match.Groups["Meridian"].Success && match.Groups["Meridian"].Value.ToUpper().StartsWith("P")) hour += 12; r.ByHour.Add(hour); if (match.Groups["Minute"].Success && int.TryParse(match.Groups["Minute"].Value, out minute)) { r.ByMinute.Add(minute); if (match.Groups["Second"].Success && int.TryParse(match.Groups["Second"].Value, out second)) r.BySecond.Add(second); } } } else if ((match = Regex.Match(item, @"^\s*until\s+(?<DateTime>.+)$", RegexOptions.IgnoreCase)).Success) { DateTime dt = DateTime.Parse(match.Groups["DateTime"].Value); DateTime.SpecifyKind(dt, DateTimeKind.Utc); r.Until = dt; } else if ((match = Regex.Match(item, @"^\s*for\s+(?<Count>\d+)\s+occurrences\s*$", RegexOptions.IgnoreCase)).Success) { int count; if (!int.TryParse(match.Groups["Count"].Value, out count)) return false; else r.Count = count; } } } else { // Couldn't parse the object, return null! r = null; } if (r != null) { CheckMutuallyExclusive("COUNT", "UNTIL", r.Count, r.Until); CheckRange("INTERVAL", r.Interval, 1, int.MaxValue); CheckRange("COUNT", r.Count, 1, int.MaxValue); CheckRange("BYSECOND", r.BySecond, 0, 59); CheckRange("BYMINUTE", r.ByMinute, 0, 59); CheckRange("BYHOUR", r.ByHour, 0, 23); CheckRange("BYMONTHDAY", r.ByMonthDay, -31, 31); CheckRange("BYYEARDAY", r.ByYearDay, -366, 366); CheckRange("BYWEEKNO", r.ByWeekNo, -53, 53); CheckRange("BYMONTH", r.ByMonth, 1, 12); CheckRange("BYSETPOS", r.BySetPosition, -366, 366); } } return r; }
/// <summary> /// Returns a serializer that can be used to serialize and object /// of type <paramref name="objectType"/>. /// <note> /// TODO: Add support for caching. /// </note> /// </summary> /// <param name="objectType">The type of object to be serialized.</param> /// <param name="ctx">The serialization context.</param> virtual public ISerializer Build(Type objectType, ISerializationContext ctx) { if (objectType != null) { ISerializer s = null; if (typeof(IICalendar).IsAssignableFrom(objectType)) { s = new iCalendarSerializer(); } else if (typeof(ICalendarComponent).IsAssignableFrom(objectType)) { if (typeof(IEvent).IsAssignableFrom(objectType)) { s = new EventSerializer(); } else if (typeof(IUniqueComponent).IsAssignableFrom(objectType)) { s = new UniqueComponentSerializer(); } else { s = new ComponentSerializer(); } } else if (typeof(ICalendarProperty).IsAssignableFrom(objectType)) { s = new PropertySerializer(); } else if (typeof(ICalendarParameter).IsAssignableFrom(objectType)) { s = new ParameterSerializer(); } else if (typeof(string).IsAssignableFrom(objectType)) { s = new StringSerializer(); } else if (objectType.IsEnum) { s = new EnumSerializer(objectType); } else if (typeof(TimeSpan).IsAssignableFrom(objectType)) { s = new TimeSpanSerializer(); } else if (typeof(int).IsAssignableFrom(objectType)) { s = new IntegerSerializer(); } else if (typeof(Uri).IsAssignableFrom(objectType)) { s = new UriSerializer(); } else if (typeof(ICalendarDataType).IsAssignableFrom(objectType)) { s = m_DataTypeSerializerFactory.Build(objectType, ctx); } // Default to a string serializer, which simply calls // ToString() on the value to serialize it. else { s = new StringSerializer(); } // Set the serialization context if (s != null) { s.SerializationContext = ctx; } return(s); } return(null); }