Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
XmlFileEventSink.cs
1using System;
2using System.IO;
3using System.Text;
4using System.Xml;
5using System.Threading.Tasks;
6using Waher.Content;
7
8namespace Waher.Events.Files
9{
14 {
15 private readonly XmlWriterSettings settings;
16 private StreamWriter file;
17 private readonly string fileName;
18 private string lastFileName = null;
19 private readonly string transform = null;
20 private readonly int deleteAfterDays;
21
37 public XmlFileEventSink(string ObjectID, string FileName)
38 : this(ObjectID, FileName, string.Empty, 7)
39 {
40 }
41
59 public XmlFileEventSink(string ObjectID, string FileName, int DeleteAfterDays)
60 : this(ObjectID, FileName, string.Empty, DeleteAfterDays)
61 {
62 }
63
80 public XmlFileEventSink(string ObjectID, string FileName, string Transform)
81 : this(ObjectID, FileName, Transform, 7)
82 {
83 }
84
103 public XmlFileEventSink(string ObjectID, string FileName, string Transform, int DeleteAfterDays)
104 : base(ObjectID, null)
105 {
106 this.file = null;
107 this.output = null;
108 this.fileName = FileName;
109 this.transform = Transform;
110 this.deleteAfterDays = DeleteAfterDays;
111
112 this.settings = new XmlWriterSettings
113 {
114 CloseOutput = true,
115 ConformanceLevel = ConformanceLevel.Document,
116 Encoding = Encoding.UTF8,
117 Indent = true,
118 IndentChars = "\t",
119 NewLineChars = "\r\n",
120 NewLineHandling = NewLineHandling.Replace,
121 NewLineOnAttributes = false,
122 OmitXmlDeclaration = false,
123 WriteEndDocumentOnClose = true
124 };
125
126 string FolderName = Path.GetDirectoryName(FileName);
127
128 if (!Directory.Exists(FolderName))
129 {
130 Log.Informational("Creating folder.", FolderName);
131 Directory.CreateDirectory(FolderName);
132 }
133 }
134
140 public static string GetFileName(string TemplateFileName)
141 {
142 DateTime TP = DateTime.Now;
143 return TemplateFileName.
144 Replace("%YEAR%", TP.Year.ToString("D4")).
145 Replace("%MONTH%", TP.Month.ToString("D2")).
146 Replace("%DAY%", TP.Day.ToString("D2")).
147 Replace("%HOUR%", TP.Hour.ToString("D2")).
148 Replace("%MINUTE%", TP.Minute.ToString("D2")).
149 Replace("%SECOND%", TP.Second.ToString("D2"));
150 }
151
156 public static void MakeUnique(ref string FileName)
157 {
158 if (File.Exists(FileName))
159 {
160 int i = FileName.LastIndexOf('.');
161 int j = 2;
162
163 if (i < 0)
164 i = FileName.Length;
165
166 string s;
167
168 do
169 {
170 s = FileName.Insert(i, " (" + (j++).ToString() + ")");
171 }
172 while (File.Exists(s));
173
174 FileName = s;
175 }
176 }
177
181 protected override async Task BeforeWrite()
182 {
183 string s = GetFileName(this.fileName);
184 if (!(this.lastFileName is null) && this.lastFileName == s && !(this.file is null) && this.file.BaseStream.CanWrite)
185 return;
186
187 try
188 {
189 this.output?.WriteEndElement();
190 this.output?.WriteEndDocument();
191 this.output?.Flush();
192 this.file?.Dispose();
193 }
194 catch (Exception)
195 {
196 try
197 {
198 this.DisposeOutput();
199 }
200 catch (Exception)
201 {
202 // Ignore
203 }
204 }
205
206 this.file = null;
207 this.output = null;
208
209 string s2 = s;
210
211 MakeUnique(ref s2);
212 this.file = File.CreateText(s2);
213 this.lastFileName = s;
214
215 this.output = XmlWriter.Create(this.file, this.settings);
216 this.output.WriteStartDocument();
217
218 if (!string.IsNullOrEmpty(this.transform))
219 {
220 if (File.Exists(this.transform))
221 {
222 try
223 {
224 byte[] XsltBin = await Resources.ReadAllBytesAsync(this.transform);
225
226 this.output.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"data:text/xsl;base64," +
227 Convert.ToBase64String(XsltBin) + "\"");
228 }
229 catch (Exception)
230 {
231 this.output.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + this.transform + "\"");
232 }
233 }
234 else
235 this.output.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + this.transform + "\"");
236 }
237
238 this.output.WriteStartElement("EventOutput", EventExtensions.LogNamespace);
239 this.output.Flush();
240
241 if (this.deleteAfterDays < int.MaxValue)
242 {
243 string FolderName = Path.GetDirectoryName(s);
244 if (string.IsNullOrEmpty(FolderName))
245 FolderName = ".";
246
247 string[] Files = Directory.GetFiles(FolderName, "*.*");
248
249 foreach (string FileName in Files)
250 {
251 if ((DateTime.Now - File.GetLastWriteTime(FileName)).TotalDays >= this.deleteAfterDays)
252 {
253 try
254 {
255 File.Delete(FileName);
256 }
257 catch (Exception ex)
258 {
259 Log.Exception(ex);
260 }
261 }
262 }
263 }
264 }
265
269 public override void DisposeOutput()
270 {
271 base.DisposeOutput();
272
273 this.file?.Dispose();
274 this.file = null;
275 }
276 }
277}
Static class managing loading of resources stored as embedded resources or in content files.
Definition: Resources.cs:15
static async Task< byte[]> ReadAllBytesAsync(string FileName)
Reads a binary file asynchronously.
Definition: Resources.cs:183
const string LogNamespace
http://waher.se/Schema/EventOutput.xsd
Outputs sniffed data to an XML file.
XmlFileEventSink(string ObjectID, string FileName, int DeleteAfterDays)
Outputs sniffed data to an XML file.
static string GetFileName(string TemplateFileName)
Gets the name of a file, given a file name template.
override void DisposeOutput()
Disposes of the current output.
static void MakeUnique(ref string FileName)
Makes a file name unique.
XmlFileEventSink(string ObjectID, string FileName, string Transform, int DeleteAfterDays)
Outputs sniffed data to an XML file.
XmlFileEventSink(string ObjectID, string FileName)
Outputs sniffed data to an XML file.
override async Task BeforeWrite()
Method is called before writing something to the text file.
XmlFileEventSink(string ObjectID, string FileName, string Transform)
Outputs sniffed data to an XML file.
Outputs sniffed data to an XML writer.
XmlWriter output
XML writer object.
Static class managing the application event log. Applications and services log events on this static ...
Definition: Log.cs:13
static void Exception(Exception Exception, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, params KeyValuePair< string, object >[] Tags)
Logs an exception. Event type will be determined by the severity of the exception.
Definition: Log.cs:1647
static void Informational(string Message, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, string StackTrace, params KeyValuePair< string, object >[] Tags)
Logs an informational event.
Definition: Log.cs:334
virtual string ObjectID
Object ID, used when logging events.
Definition: LogObject.cs:25
delegate string ToString(IElement Element)
Delegate for callback methods that convert an element value to a string.