-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathX9FieldType.cs
119 lines (113 loc) · 3.83 KB
/
X9FieldType.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
113
114
115
116
117
118
119
using System;
using System.Globalization;
using System.Runtime.Serialization;
namespace CompAnalytics.X9
{
[DataContract]
[Serializable]
public class X9FieldType
{
static readonly string DateFormat = "yyyyMMdd";
static readonly string TimeFormat = "hhmm";
[DataMember]
public string Name { get; set; }
[DataMember]
public X9FieldDataType DataType { get; set; }
/// <summary>
/// The type we'd prefer to use when getting/setting the value. Can be null.
/// </summary>
public Type InteropClrType { get; set; }
[DataMember]
public int? Length { get; set; }
[DataMember]
public bool IsFixedLength { get; private set; }
public X9FieldType(string name, X9FieldDataType dataType, int? length = null, Type interopType = null)
{
Name = name;
DataType = dataType;
Length = length;
IsFixedLength = Length.HasValue;
InteropClrType = interopType;
}
internal object ConvertVal(object value, Type fromType, Type toType)
{
if (value == null || fromType == toType)
{
return value;
}
else if (fromType == typeof(long?) && toType == typeof(DateTimeOffset))
{
if ((long?)value == 0)
{
return null;
}
else
{
string str = Convert.ToString(value).PadLeft(Length.Value, '0');
return new DateTimeOffset(DateTime.ParseExact(str, DateFormat, CultureInfo.InvariantCulture.DateTimeFormat), TimeSpan.FromHours(0));
}
}
else if (toType == typeof(long?) && fromType == typeof(DateTimeOffset))
{
DateTimeOffset dt = (DateTimeOffset)value;
return int.Parse(dt.ToString(DateFormat));
}
else if (fromType == typeof(long?) && toType == typeof(TimeSpan))
{
if ((long?)value == 0)
{
return null;
}
else
{
string str = Convert.ToString(value).PadLeft(Length.Value, '0');
return TimeSpan.ParseExact(str, TimeFormat, CultureInfo.InvariantCulture);
}
}
else if (toType == typeof(long?) && fromType == typeof(TimeSpan))
{
TimeSpan ts = (TimeSpan)value;
return int.Parse(ts.ToString(TimeFormat));
}
else if (fromType == typeof(long?) && toType == typeof(bool?))
{
if ((long?)value == 0)
{
return false;
}
else if ((long?)value == 1)
{
return true;
}
else
{
throw new ArgumentException("Invalid boolean value.");
}
}
else if (toType == typeof(long?) && fromType == typeof(bool?))
{
bool val = (bool)value;
return val ? 1 : 0;
}
else
{
if (fromType == typeof(long?) && toType != typeof(long?))
{
long? nullableVal = (long?)value;
if (nullableVal.HasValue)
{
return Convert.ChangeType(nullableVal.Value, toType);
}
else
{
return null;
}
}
else
{
return Convert.ChangeType(value, toType);
}
}
}
}
}