GPAL - Generally Positive Automation Library v1.0
GPAL The Fluent Automation LIbrary
Loading...
Searching...
No Matches
UriYamlConverter.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 YamlDotNet.Core;
19using YamlDotNet.Core.Events;
20using YamlDotNet.Serialization;
21
22public class UriYamlConverter : IYamlTypeConverter
23{
24 public bool Accepts(Type type)
25 {
26 return type == typeof(Uri);
27 }
28
29 public object ReadYaml(IParser parser, Type type)
30 {
31 var scalar = parser.Consume<Scalar>();
32 return new Uri(scalar.Value); // Parse the scalar string as a Uri
33 }
34
35 public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer)
36 {
37 // Deserialize the scalar value as a string using rootDeserializer
38 var scalarValue = rootDeserializer(typeof(string)) as string;
39
40 if (string.IsNullOrEmpty(scalarValue))
41 {
42 throw new YamlException("Invalid Uri format: string is null or empty.");
43 }
44
45 return new Uri(scalarValue); // Parse the string as a Uri
46 }
47
48 public void WriteYaml(IEmitter emitter, object value, Type type)
49 {
50 if (value == null)
51 {
52 // a null is data, not a failure. without this a null entry in a collection of Uri throws and takes
53 // the whole conversion with it
54 emitter.Emit(new Scalar("null"));
55 }
56 else
57 {
58 var uri = (Uri)value;
59 emitter.Emit(new Scalar(null, null, uri.ToString())); // Emit the Uri as a string
60 }
61 }
62
63 public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerializer serializer)
64 {
65 if (value == null)
66 {
67 emitter.Emit(new Scalar("null")); // a null-valued scalar renders as '' which does not read back as null
68 }
69 else
70 {
71 var uri = (Uri)value;
72 // Use the serializer to emit the Uri as a string
73 serializer(uri.ToString(), typeof(string));
74 }
75 }
76
77}
78