GPAL - Generally Positive Automation Library v1.0
GPAL The Fluent Automation LIbrary
Loading...
Searching...
No Matches
NullableTimeSpanYamlConverter.cs
1// =============================================================================
2// GPAL - Generally Positive Automation Library
3// Copyright © 2026 Software Decisions, Inc. All rights reserved.
4//
5// This file is part of GPAL.
6// Licensed under the Business Source License 1.1
7//
8// Primary development, architecture, and vision by Michael B. Vederman,
9// CEO of Software Decisions, Inc., Texas.
10//
11// Internal development maintained privately.
12// Public releases appear on GitHub: https://github.com/SoftwareDecisionsInc/GPAL.
13//
14// See LICENSE for full terms, including Additional Use Grant.
15// =============================================================================
16
17using System;
18using System.Globalization;
19using YamlDotNet.Core;
20using YamlDotNet.Core.Events;
21using YamlDotNet.Serialization;
22
28public class NullableTimeSpanYamlConverter : IYamlTypeConverter
29{
30 public bool Accepts(Type type)
31 {
32 return type == typeof(TimeSpan) || typeof(TimeSpan?) == type;
33 }
34
35 public object ReadYaml(IParser parser, Type type)
36 {
37 var scalar = parser.Consume<Scalar>();
38
39 if (string.IsNullOrEmpty(scalar.Value) || scalar.Value.ToLower() == "null")
40 return null;
41
42 return TimeSpan.Parse(scalar.Value, CultureInfo.InvariantCulture);
43 }
44
45 public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer)
46 {
47 var scalarValue = rootDeserializer(typeof(string)) as string;
48
49 if (string.IsNullOrEmpty(scalarValue) || scalarValue.ToLower() == "null")
50 return null;
51
52 return TimeSpan.Parse(scalarValue, CultureInfo.InvariantCulture);
53 }
54
55 public void WriteYaml(IEmitter emitter, object value, Type type)
56 {
57 if (value == null)
58 emitter.Emit(new Scalar("null"));
59 else
60 emitter.Emit(new Scalar(null, null, ((TimeSpan)value).ToString("c")));
61 }
62
63 public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerializer serializer)
64 {
65 if (value == null)
66 emitter.Emit(new Scalar("null"));
67 else
68 serializer(((TimeSpan)value).ToString("c"), typeof(string));
69 }
70}
Writes a TimeSpan, and a null TimeSpan?, the way the rest of GPAL writes nulls. Without this YamlDotN...