forked from ServiceStack/ServiceStack.Text
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPclExport.cs
More file actions
535 lines (441 loc) · 15.8 KB
/
PclExport.cs
File metadata and controls
535 lines (441 loc) · 15.8 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//Copyright (c) Service Stack LLC. All Rights Reserved.
//License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ServiceStack.Text;
using ServiceStack.Text.Common;
namespace ServiceStack
{
public abstract class PclExport
{
public static class Platforms
{
public const string WindowsStore = "WindowsStore";
public const string Android = "Android";
public const string IOS = "IOS";
public const string Mac = "MAC";
public const string Silverlight5 = "Silverlight5";
public const string WindowsPhone = "WindowsPhone";
public const string NetStandard = "NETStandard";
}
public static PclExport Instance
#if PCL
/*attempts to be inferred otherwise needs to be set explicitly by host project*/
#elif SL5
= new Sl5PclExport()
#elif NETFX_CORE
= new WinStorePclExport()
#elif NETSTANDARD1_1
= new NetStandardPclExport()
#elif WP
= new WpPclExport()
#elif XBOX
= new XboxPclExport()
#elif __IOS__
= new IosPclExport()
#elif __MAC__
= new MacPclExport()
#elif ANDROID
= new AndroidPclExport()
#elif NET45
= new Net45PclExport()
#else
= new Net40PclExport()
#endif
;
static PclExport()
{
if (Instance != null)
return;
try
{
if (ConfigureProvider("ServiceStack.IosPclExportClient, ServiceStack.Pcl.iOS"))
return;
if (ConfigureProvider("ServiceStack.AndroidPclExportClient, ServiceStack.Pcl.Android"))
return;
if (ConfigureProvider("ServiceStack.MacPclExportClient, ServiceStack.Pcl.Mac20"))
return;
if (ConfigureProvider("ServiceStack.WinStorePclExportClient, ServiceStack.Pcl.WinStore"))
return;
if (ConfigureProvider("ServiceStack.Net40PclExportClient, ServiceStack.Pcl.Net45"))
return;
}
catch (Exception /*ignore*/) {}
}
public static bool ConfigureProvider(string typeName)
{
var type = Type.GetType(typeName);
if (type == null)
return false;
var mi = type.GetMethod("Configure");
if (mi != null)
{
mi.Invoke(null, new object[0]);
}
return true;
}
public static void Configure(PclExport instance)
{
Instance = instance ?? Instance;
if (Instance != null && Instance.EmptyTask == null)
{
var tcs = new TaskCompletionSource<object>();
tcs.SetResult(null);
Instance.EmptyTask = tcs.Task;
}
}
public Task EmptyTask;
public bool SupportsExpression;
public bool SupportsEmit;
public char DirSep = '\\';
public char AltDirSep = '/';
public string PlatformName = "Unknown";
public TextInfo TextInfo = CultureInfo.InvariantCulture.TextInfo;
public RegexOptions RegexOptions = RegexOptions.None;
public StringComparison InvariantComparison = StringComparison.Ordinal;
public StringComparison InvariantComparisonIgnoreCase = StringComparison.OrdinalIgnoreCase;
public StringComparer InvariantComparer = StringComparer.Ordinal;
public StringComparer InvariantComparerIgnoreCase = StringComparer.OrdinalIgnoreCase;
public abstract string ReadAllText(string filePath);
public virtual string ToTitleCase(string value)
{
string[] words = value.Split('_');
for (int i = 0; i <= words.Length - 1; i++)
{
if ((!object.ReferenceEquals(words[i], string.Empty)))
{
string firstLetter = words[i].Substring(0, 1);
string rest = words[i].Substring(1);
string result = firstLetter.ToUpper() + rest.ToLower();
words[i] = result;
}
}
return string.Join("", words);
}
// HACK: The only way to detect anonymous types right now.
public virtual bool IsAnonymousType(Type type)
{
return type.IsGeneric() && type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>", StringComparison.Ordinal) || type.Name.StartsWith("VB$", StringComparison.Ordinal));
}
public virtual string ToInvariantUpper(char value)
{
return value.ToString().ToUpperInvariant();
}
public virtual bool FileExists(string filePath)
{
return false;
}
public virtual bool DirectoryExists(string dirPath)
{
return false;
}
public virtual void CreateDirectory(string dirPath)
{
}
public virtual void RegisterLicenseFromConfig()
{
}
public virtual string GetEnvironmentVariable(string name)
{
return null;
}
public virtual string[] GetFileNames(string dirPath, string searchPattern = null)
{
return TypeConstants.EmptyStringArray;
}
public virtual string[] GetDirectoryNames(string dirPath, string searchPattern = null)
{
return TypeConstants.EmptyStringArray;
}
public virtual void WriteLine(string line)
{
}
public virtual void WriteLine(string line, params object[] args)
{
}
public virtual HttpWebRequest CreateWebRequest(string requestUri, bool? emulateHttpViaPost = null)
{
return (HttpWebRequest)WebRequest.Create(requestUri);
}
public virtual void Config(HttpWebRequest req,
bool? allowAutoRedirect = null,
TimeSpan? timeout = null,
TimeSpan? readWriteTimeout = null,
string userAgent = null,
bool? preAuthenticate = null)
{
}
public virtual void AddCompression(WebRequest webRequest)
{
}
public virtual Stream GetRequestStream(WebRequest webRequest)
{
var async = webRequest.GetRequestStreamAsync();
async.Wait();
return async.Result;
}
public virtual WebResponse GetResponse(WebRequest webRequest)
{
try
{
var async = webRequest.GetResponseAsync();
async.Wait();
return async.Result;
}
catch (Exception ex)
{
throw ex.UnwrapIfSingleException();
}
}
public virtual bool IsDebugBuild(Assembly assembly)
{
return assembly.AllAttributes()
.Any(x => x.GetType().Name == "DebuggableAttribute");
}
public virtual string MapAbsolutePath(string relativePath, string appendPartialPathModifier)
{
return relativePath;
}
public virtual Assembly LoadAssembly(string assemblyPath)
{
#if PCL
return Assembly.Load(new AssemblyName(assemblyPath));
#else
return null;
#endif
}
public virtual void AddHeader(WebRequest webReq, string name, string value)
{
webReq.Headers[name] = value;
}
public virtual void SetUserAgent(HttpWebRequest httpReq, string value)
{
httpReq.Headers[HttpRequestHeader.UserAgent] = value;
}
public virtual void SetContentLength(HttpWebRequest httpReq, long value)
{
httpReq.Headers[HttpRequestHeader.ContentLength] = value.ToString();
}
public virtual void SetAllowAutoRedirect(HttpWebRequest httpReq, bool value)
{
}
public virtual void SetKeepAlive(HttpWebRequest httpReq, bool value)
{
}
public virtual Assembly[] GetAllAssemblies()
{
return new Assembly[0];
}
public virtual Type FindType(string typeName, string assemblyName)
{
return null;
}
public virtual string GetAssemblyCodeBase(Assembly assembly)
{
return assembly.FullName;
}
public virtual string GetAssemblyPath(Type source)
{
return null;
}
public virtual string GetAsciiString(byte[] bytes)
{
return GetAsciiString(bytes, 0, bytes.Length);
}
public virtual string GetAsciiString(byte[] bytes, int index, int count)
{
return Encoding.UTF8.GetString(bytes, index, count);
}
public virtual byte[] GetAsciiBytes(string str)
{
return Encoding.UTF8.GetBytes(str);
}
public virtual Encoding GetUTF8Encoding(bool emitBom=false)
{
#if !PCL
return new UTF8Encoding(emitBom);
#else
return Encoding.UTF8;
#endif
}
public virtual SetMemberDelegate GetFieldSetterFn(FieldInfo fieldInfo)
{
return fieldInfo.SetValue;
}
public virtual GetMemberDelegate GetFieldGetterFn(FieldInfo fieldInfo)
{
return fieldInfo.GetValue;
}
public virtual SetMemberDelegate GetSetMethod(PropertyInfo propertyInfo, FieldInfo fieldInfo)
{
if (propertyInfo.CanWrite)
{
var setMethodInfo = propertyInfo.SetMethod();
if (setMethodInfo.IsStatic)
return (instance, value) => setMethodInfo.Invoke(null, new[] { value });
return (instance, value) => setMethodInfo.Invoke(instance, new[] { value });
}
if (fieldInfo == null) return null;
return fieldInfo.SetValue;
}
public virtual Type UseType(Type type)
{
return type;
}
public virtual bool InSameAssembly(Type t1, Type t2)
{
return t1.AssemblyQualifiedName != null && t1.AssemblyQualifiedName.Equals(t2.AssemblyQualifiedName);
}
public virtual Type GetGenericCollectionType(Type type)
{
return type.GetTypeInterfaces()
.FirstOrDefault(t => t.IsGenericType()
&& t.GetGenericTypeDefinition() == typeof(ICollection<>));
}
public virtual SetMemberDelegate GetPropertySetterFn(PropertyInfo propertyInfo)
{
var propertySetMethod = propertyInfo.SetMethod();
if (propertySetMethod == null) return null;
return (o, convertedValue) =>
propertySetMethod.Invoke(o, new[] { convertedValue });
}
public virtual GetMemberDelegate GetPropertyGetterFn(PropertyInfo propertyInfo)
{
var getMethodInfo = propertyInfo.GetMethodInfo();
if (getMethodInfo == null) return null;
return o => propertyInfo.GetMethodInfo().Invoke(o, new object[] { });
}
public virtual string ToXsdDateTimeString(DateTime dateTime)
{
#if !PCL
return System.Xml.XmlConvert.ToString(dateTime.ToStableUniversalTime(), DateTimeSerializer.XsdDateTimeFormat);
#else
return dateTime.ToStableUniversalTime().ToString(DateTimeSerializer.XsdDateTimeFormat);
#endif
}
public virtual string ToLocalXsdDateTimeString(DateTime dateTime)
{
#if !PCL
return System.Xml.XmlConvert.ToString(dateTime, DateTimeSerializer.XsdDateTimeFormat);
#else
return dateTime.ToString(DateTimeSerializer.XsdDateTimeFormat);
#endif
}
public virtual DateTime ParseXsdDateTime(string dateTimeStr)
{
#if !PCL
return System.Xml.XmlConvert.ToDateTimeOffset(dateTimeStr).DateTime;
#else
return DateTime.ParseExact(dateTimeStr, DateTimeSerializer.XsdDateTimeFormat, CultureInfo.InvariantCulture);
#endif
}
public virtual DateTime ParseXsdDateTimeAsUtc(string dateTimeStr)
{
return DateTimeSerializer.ParseManual(dateTimeStr, DateTimeKind.Utc)
?? DateTime.ParseExact(dateTimeStr, DateTimeSerializer.XsdDateTimeFormat, CultureInfo.InvariantCulture);
}
public virtual DateTime ToStableUniversalTime(DateTime dateTime)
{
// Silverlight 3, 4 and 5 all work ok with DateTime.ToUniversalTime, but have no TimeZoneInfo.ConverTimeToUtc implementation.
return dateTime.ToUniversalTime();
}
public virtual ParseStringDelegate GetDictionaryParseMethod<TSerializer>(Type type)
where TSerializer : ITypeSerializer
{
return null;
}
public virtual ParseStringSegmentDelegate GetDictionaryParseStringSegmentMethod<TSerializer>(Type type)
where TSerializer : ITypeSerializer
{
return null;
}
public virtual ParseStringDelegate GetSpecializedCollectionParseMethod<TSerializer>(Type type)
where TSerializer : ITypeSerializer
{
return null;
}
public virtual ParseStringSegmentDelegate GetSpecializedCollectionParseStringSegmentMethod<TSerializer>(Type type)
where TSerializer : ITypeSerializer
{
return null;
}
public virtual ParseStringDelegate GetJsReaderParseMethod<TSerializer>(Type type)
where TSerializer : ITypeSerializer
{
#if !PCL
//if (type.AssignableFrom(typeof(System.Dynamic.IDynamicMetaObjectProvider)) ||
// type.HasInterface(typeof(System.Dynamic.IDynamicMetaObjectProvider)))
//{
// return DeserializeDynamic<TSerializer>.Parse;
//}
#endif
return null;
}
public virtual ParseStringSegmentDelegate GetJsReaderParseStringSegmentMethod<TSerializer>(Type type)
where TSerializer : ITypeSerializer
{
return null;
}
public virtual void InitHttpWebRequest(HttpWebRequest httpReq,
long? contentLength = null, bool allowAutoRedirect = true, bool keepAlive = true)
{
}
public virtual void CloseStream(Stream stream)
{
stream.Flush();
}
public virtual void ResetStream(Stream stream)
{
stream.Position = 0;
}
public virtual LicenseKey VerifyLicenseKeyText(string licenseKeyText)
{
return licenseKeyText.ToLicenseKey();
}
public virtual LicenseKey VerifyLicenseKeyTextFallback(string licenseKeyText)
{
return licenseKeyText.ToLicenseKeyFallback();
}
public virtual void BeginThreadAffinity()
{
}
public virtual void EndThreadAffinity()
{
}
public virtual DataContractAttribute GetWeakDataContract(Type type)
{
return null;
}
public virtual DataMemberAttribute GetWeakDataMember(PropertyInfo pi)
{
return null;
}
public virtual DataMemberAttribute GetWeakDataMember(FieldInfo pi)
{
return null;
}
public virtual void RegisterForAot()
{
}
public virtual string GetStackTrace()
{
return null;
}
public virtual Task WriteAndFlushAsync(Stream stream, byte[] bytes)
{
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
return EmptyTask;
}
}
}