@@ -7,6 +7,7 @@ This Source Code Form is subject to the terms of the
77using ScriptEngine . Machine ;
88using ScriptEngine . Machine . Contexts ;
99using System ;
10+ using System . Collections . Generic ;
1011using System . Xml ;
1112
1213using ScriptEngine . HostedScript . Library . Binary ;
@@ -16,11 +17,44 @@ namespace ScriptEngine.HostedScript.Library.Xml
1617 [ GlobalContext ( Category = "Функции работы с XML" ) ]
1718 public class XmlGlobalFunctions : GlobalContextBase < XmlGlobalFunctions >
1819 {
20+ private static readonly Dictionary < TypeDescriptor , EnumerationContext > _allowedEnums
21+ = new Dictionary < TypeDescriptor , EnumerationContext > ( ) ;
22+
23+ private static readonly TypeDescriptor _binaryDataTypeDescriptor ;
24+ private static readonly TypeDescriptor _nullTypeDescriptor ;
25+ private static readonly TypeDescriptor _guidTypeDescriptor ;
26+
27+ static XmlGlobalFunctions ( )
28+ {
29+ _binaryDataTypeDescriptor = TypeManager . GetTypeByFrameworkType ( typeof ( BinaryDataContext ) ) ;
30+ _nullTypeDescriptor = TypeManager . GetTypeByName ( "NULL" ) ;
31+ _guidTypeDescriptor = TypeManager . GetTypeByFrameworkType ( typeof ( GuidWrapper ) ) ;
32+
33+ foreach ( var e in new [ ] { typeof ( AllowedSignEnum ) , typeof ( AllowedLengthEnum ) , typeof ( DateFractionsEnum ) } )
34+ {
35+ _allowedEnums . Add ( TypeManager . GetTypeByFrameworkType ( e ) , GlobalsManager . GetSimpleEnum ( e ) ) ;
36+ }
37+ }
38+
39+ /// <summary>
40+ /// Получает XML представление значения для помещения в текст элемента или значение атрибута XML.
41+ /// </summary>
42+ /// <param name="value">
43+ /// Значение. Допустимые типы: Булево, Число, Строка, Дата, УникальныйИдентификатор, ДвоичныеДанные,
44+ /// Неопределено, Null, а также значения перечислений ДопустимыйЗнак, ДопустимаяДлина, ЧастиДаты
45+ /// </param>
46+ /// <returns>
47+ /// Строковое представление значения. Для двоичных данных - строка в формате Вase64.
48+ /// При недопустимом типе значения выбрасывается исключение
49+ /// </returns>
50+ ///
1951 [ ContextMethod ( "XMLСтрока" , "XMLString" ) ]
2052 public string XMLString ( IValue value )
2153 {
2254 switch ( value . DataType )
2355 {
56+ case DataType . String :
57+ return value . AsString ( ) ;
2458 case DataType . Undefined :
2559 return "" ;
2660 case DataType . Boolean :
@@ -29,23 +63,53 @@ public string XMLString(IValue value)
2963 return XmlConvert . ToString ( value . AsDate ( ) , XmlDateTimeSerializationMode . Unspecified ) ;
3064 case DataType . Number :
3165 return XmlConvert . ToString ( value . AsNumber ( ) ) ;
66+
67+ case DataType . Enumeration :
68+ if ( _allowedEnums . TryGetValue ( value . SystemType , out var enumeration ) )
69+ {
70+ return value . AsString ( ) ;
71+ }
72+ break ;
73+
3274 default :
33-
34- if ( value . SystemType . Equals ( TypeManager . GetTypeByFrameworkType ( typeof ( BinaryDataContext ) ) ) )
75+ if ( value . SystemType . Equals ( _binaryDataTypeDescriptor ) )
3576 {
3677 var bdc = value . GetRawValue ( ) as BinaryDataContext ;
3778 System . Diagnostics . Debug . Assert ( bdc != null ) ;
3879
3980 return Convert . ToBase64String ( bdc . Buffer , Base64FormattingOptions . InsertLineBreaks ) ;
4081 }
41- else
82+ else if ( value . SystemType . Equals ( _guidTypeDescriptor ) )
4283 {
43- return value . GetRawValue ( ) . AsString ( ) ;
84+ return value . AsString ( ) ; ;
4485 }
45-
86+ else if ( value . SystemType . Equals ( _nullTypeDescriptor ) )
87+ {
88+ return "" ;
89+ }
90+ break ;
4691 }
92+
93+ throw RuntimeException . InvalidArgumentValue ( ) ;
4794 }
4895
96+ /// <summary>
97+ /// Выполняет преобразование из строки, полученной из текста элемента или значения атрибута XML,
98+ /// в значение в соответствии с указанным типом. Действие, обратное действию метода XMLСтрока
99+ /// </summary>
100+ /// <param name="givenType">
101+ /// Тип, значение которого надо получить при преобразовании из строкового представления XML.
102+ /// Допустимые типы: Булево, Число, Строка, Дата, УникальныйИдентификатор, ДвоичныеДанные,
103+ /// Неопределено, Null, перечисления ДопустимыйЗнак, ДопустимаяДлина, ЧастиДаты
104+ /// </param>
105+ /// <param name="presentation">
106+ /// Строка, содержащая строковое представление значения соответствующего типа
107+ /// </param>
108+ /// <returns>
109+ /// Значение заданного типа.
110+ /// При недопустимом типе или неправильном строковом представлении выбрасывается исключение
111+ /// </returns>
112+ ///
49113 [ ContextMethod ( "XMLЗначение" , "XMLValue" ) ]
50114 public IValue XMLValue ( IValue givenType , string presentation )
51115 {
@@ -67,20 +131,53 @@ public IValue XMLValue(IValue givenType, string presentation)
67131 {
68132 return ValueFactory . Create ( presentation ) ;
69133 }
70- else if ( typeValue . Equals ( TypeDescriptor . FromDataType ( DataType . Undefined ) ) && presentation == "" )
134+ else if ( typeValue . Equals ( TypeDescriptor . FromDataType ( DataType . Undefined ) ) )
71135 {
72- return ValueFactory . Create ( ) ;
136+ if ( presentation . Trim ( ) == "" )
137+ return ValueFactory . Create ( ) ;
138+ else
139+ {
140+ throw RuntimeException . InvalidNthArgumentValue ( 2 ) ;
141+ }
73142 }
74- else if ( typeValue . Equals ( TypeManager . GetTypeByFrameworkType ( typeof ( BinaryDataContext ) ) ) )
143+ else if ( typeValue . Equals ( _nullTypeDescriptor ) )
144+ {
145+ if ( presentation . Trim ( ) == "" )
146+ return ValueFactory . CreateNullValue ( ) ;
147+ else
148+ {
149+ throw RuntimeException . InvalidNthArgumentValue ( 2 ) ;
150+ }
151+ }
152+ else if ( typeValue . Equals ( _binaryDataTypeDescriptor ) )
75153 {
76154 byte [ ] bytes = Convert . FromBase64String ( presentation ) ;
77155 return new BinaryDataContext ( bytes ) ;
78156 }
79- else
157+ else if ( typeValue . Equals ( _guidTypeDescriptor ) )
158+ {
159+ try
160+ {
161+ return new GuidWrapper ( presentation ) ;
162+ }
163+ catch
164+ {
165+ throw RuntimeException . InvalidNthArgumentValue ( 2 ) ;
166+ }
167+ }
168+ else if ( _allowedEnums . TryGetValue ( typeValue , out var enumerationContext ) )
80169 {
81- throw RuntimeException . InvalidArgumentValue ( ) ;
170+ try
171+ {
172+ return enumerationContext [ presentation ] ;
173+ }
174+ catch ( RuntimeException )
175+ {
176+ throw RuntimeException . InvalidNthArgumentValue ( 2 ) ;
177+ }
82178 }
83179
180+ throw RuntimeException . InvalidNthArgumentValue ( 1 ) ;
84181 }
85182
86183 public static IAttachableContext CreateInstance ( )
0 commit comments