-
Notifications
You must be signed in to change notification settings - Fork 3
/
DDayCalendarWriter.cs
112 lines (91 loc) · 3.05 KB
/
DDayCalendarWriter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using DDay.iCal;
using DDay.iCal.Serialization;
using DDay.iCal.Serialization.iCalendar;
namespace DDayUtilities
{
public class DDayCalendarWriter : iCalendarSerializer, IDisposable
{
private readonly iCalendar _ical;
private readonly TextWriter _writer;
private bool _initialized;
private ISerializerFactory _serializerFactory;
private bool _closed;
public DDayCalendarWriter(iCalendar iCal, TextWriter writer)
{
if (iCal == null)
{
throw new ArgumentNullException("iCal");
}
if (writer == null)
{
throw new ArgumentNullException("writer");
}
_ical = iCal;
_writer = writer;
}
public void Write(ICalendarObject calendarObject)
{
Initialize();
WriteObject(calendarObject);
}
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));
}
}
private void Initialize()
{
if (_initialized)
{
return;
}
_initialized = true;
// Ensure VERSION and PRODUCTID are both set,
// as they are required by RFC5545.
if (string.IsNullOrEmpty(_ical.Version))
_ical.Version = CalendarVersions.v2_0;
if (string.IsNullOrEmpty(_ical.ProductID))
_ical.ProductID = CalendarProductIDs.Default;
_writer.Write(TextUtil.WrapLines("BEGIN:" + _ical.Name.ToUpper()));
// Get a serializer factory
_serializerFactory = GetService<ISerializerFactory>();
// Sort the calendar properties in alphabetical order before
// serializing them!
var properties = new List<ICalendarProperty>(_ical.Properties);
properties.Sort(PropertySorter);
foreach (ICalendarProperty property in properties)
{
WriteObject(property);
}
foreach (ICalendarObject child in _ical.Children)
{
WriteObject(child);
}
}
public void Close()
{
_writer.Write(TextUtil.WrapLines("END:" + _ical.Name.ToUpper()));
_closed = true;
}
#region Implementation of IDisposable
public void Dispose()
{
if(!_closed)
{
Close();
}
}
#endregion
}
}