PageRenderTime 30ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/src/ServiceStack.Text/PclExport.Net40.cs

https://github.com/ServiceStack/ServiceStack.Text
C# | 1815 lines | 1410 code | 268 blank | 137 comment | 181 complexity | 541e653396493ec136e82a78bb421971 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. #if !(XBOX || SL5 || NETFX_CORE || WP || PCL)
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Collections.Specialized;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Linq.Expressions;
  11. using System.Net;
  12. using System.Reflection;
  13. using System.Runtime.CompilerServices;
  14. using System.Runtime.Serialization;
  15. using System.Security.Cryptography;
  16. using System.Text;
  17. using System.Text.RegularExpressions;
  18. using System.Threading;
  19. using ServiceStack.Text;
  20. using ServiceStack.Text.Common;
  21. using ServiceStack.Text.Json;
  22. #if !__IOS__
  23. using System.Reflection.Emit;
  24. using FastMember = ServiceStack.Text.FastMember;
  25. #endif
  26. #if __UNIFIED__
  27. using Preserve = Foundation.PreserveAttribute;
  28. #elif __IOS__
  29. using Preserve = MonoTouch.Foundation.PreserveAttribute;
  30. #endif
  31. namespace ServiceStack
  32. {
  33. public class Net40PclExport : PclExport
  34. {
  35. public static Net40PclExport Provider = new Net40PclExport();
  36. public Net40PclExport()
  37. {
  38. this.SupportsEmit = SupportsExpression = true;
  39. this.DirSep = Path.DirectorySeparatorChar;
  40. this.AltDirSep = Path.DirectorySeparatorChar == '/' ? '\\' : '/';
  41. this.RegexOptions = RegexOptions.Compiled;
  42. #if DNXCORE50
  43. this.InvariantComparison = CultureInfo.InvariantCulture.CompareInfo.GetStringComparer();
  44. this.InvariantComparisonIgnoreCase = CultureInfo.InvariantCultureIgnoreCase.CompareInfo.GetStringComparer();
  45. #else
  46. this.InvariantComparison = StringComparison.InvariantCulture;
  47. this.InvariantComparisonIgnoreCase = StringComparison.InvariantCultureIgnoreCase;
  48. #endif
  49. this.InvariantComparer = StringComparer.InvariantCulture;
  50. this.InvariantComparerIgnoreCase = StringComparer.InvariantCultureIgnoreCase;
  51. this.PlatformName = Environment.OSVersion.Platform.ToString();
  52. }
  53. public static PclExport Configure()
  54. {
  55. Configure(Provider);
  56. return Provider;
  57. }
  58. public override string ReadAllText(string filePath)
  59. {
  60. return File.ReadAllText(filePath);
  61. }
  62. public override string ToTitleCase(string value)
  63. {
  64. return TextInfo.ToTitleCase(value).Replace("_", String.Empty);
  65. }
  66. public override string ToInvariantUpper(char value)
  67. {
  68. return value.ToString(CultureInfo.InvariantCulture).ToUpper();
  69. }
  70. public override bool IsAnonymousType(Type type)
  71. {
  72. return type.HasAttribute<CompilerGeneratedAttribute>()
  73. && type.IsGeneric() && type.Name.Contains("AnonymousType")
  74. && (type.Name.StartsWith("<>", StringComparison.Ordinal) || type.Name.StartsWith("VB$", StringComparison.Ordinal))
  75. && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
  76. }
  77. public override bool FileExists(string filePath)
  78. {
  79. return File.Exists(filePath);
  80. }
  81. public override bool DirectoryExists(string dirPath)
  82. {
  83. return Directory.Exists(dirPath);
  84. }
  85. public override void CreateDirectory(string dirPath)
  86. {
  87. Directory.CreateDirectory(dirPath);
  88. }
  89. public override string[] GetFileNames(string dirPath, string searchPattern = null)
  90. {
  91. if (!Directory.Exists(dirPath))
  92. return new string[0];
  93. return searchPattern != null
  94. ? Directory.GetFiles(dirPath, searchPattern)
  95. : Directory.GetFiles(dirPath);
  96. }
  97. public override string[] GetDirectoryNames(string dirPath, string searchPattern = null)
  98. {
  99. if (!Directory.Exists(dirPath))
  100. return new string[0];
  101. return searchPattern != null
  102. ? Directory.GetDirectories(dirPath, searchPattern)
  103. : Directory.GetDirectories(dirPath);
  104. }
  105. public const string AppSettingsKey = "servicestack:license";
  106. public const string EnvironmentKey = "SERVICESTACK_LICENSE";
  107. public override void RegisterLicenseFromConfig()
  108. {
  109. #if ANDROID
  110. #elif __IOS__
  111. #elif __MAC__
  112. #else
  113. //Automatically register license key stored in <appSettings/>
  114. var licenceKeyText = System.Configuration.ConfigurationManager.AppSettings[AppSettingsKey];
  115. if (!string.IsNullOrEmpty(licenceKeyText))
  116. {
  117. LicenseUtils.RegisterLicense(licenceKeyText);
  118. return;
  119. }
  120. //or SERVICESTACK_LICENSE Environment variable
  121. licenceKeyText = Environment.GetEnvironmentVariable(EnvironmentKey);
  122. if (!string.IsNullOrEmpty(licenceKeyText))
  123. {
  124. LicenseUtils.RegisterLicense(licenceKeyText);
  125. }
  126. #endif
  127. }
  128. public override string GetEnvironmentVariable(string name)
  129. {
  130. return Environment.GetEnvironmentVariable(name);
  131. }
  132. public override void WriteLine(string line)
  133. {
  134. Console.WriteLine(line);
  135. }
  136. public override void WriteLine(string format, params object[] args)
  137. {
  138. Console.WriteLine(format, args);
  139. }
  140. public override void AddCompression(WebRequest webReq)
  141. {
  142. var httpReq = (HttpWebRequest)webReq;
  143. httpReq.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
  144. httpReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
  145. }
  146. public override Stream GetRequestStream(WebRequest webRequest)
  147. {
  148. return webRequest.GetRequestStream();
  149. }
  150. public override WebResponse GetResponse(WebRequest webRequest)
  151. {
  152. return webRequest.GetResponse();
  153. }
  154. #if !LITE
  155. public override bool IsDebugBuild(Assembly assembly)
  156. {
  157. return assembly.AllAttributes()
  158. .OfType<System.Diagnostics.DebuggableAttribute>()
  159. .Select(attr => attr.IsJITTrackingEnabled)
  160. .FirstOrDefault();
  161. }
  162. #endif
  163. public override string MapAbsolutePath(string relativePath, string appendPartialPathModifier)
  164. {
  165. if (relativePath.StartsWith("~"))
  166. {
  167. var assemblyDirectoryPath = Path.GetDirectoryName(new Uri(typeof(PathUtils).Assembly.EscapedCodeBase).LocalPath);
  168. // Escape the assembly bin directory to the hostname directory
  169. var hostDirectoryPath = appendPartialPathModifier != null
  170. ? assemblyDirectoryPath + appendPartialPathModifier
  171. : assemblyDirectoryPath;
  172. return Path.GetFullPath(relativePath.Replace("~", hostDirectoryPath));
  173. }
  174. return relativePath;
  175. }
  176. public override Assembly LoadAssembly(string assemblyPath)
  177. {
  178. return Assembly.LoadFrom(assemblyPath);
  179. }
  180. public override void AddHeader(WebRequest webReq, string name, string value)
  181. {
  182. webReq.Headers.Add(name, value);
  183. }
  184. public override Assembly[] GetAllAssemblies()
  185. {
  186. return AppDomain.CurrentDomain.GetAssemblies();
  187. }
  188. public override Type FindType(string typeName, string assemblyName)
  189. {
  190. var binPath = AssemblyUtils.GetAssemblyBinPath(Assembly.GetExecutingAssembly());
  191. Assembly assembly = null;
  192. var assemblyDllPath = binPath + string.Format("{0}.{1}", assemblyName, "dll");
  193. if (File.Exists(assemblyDllPath))
  194. {
  195. assembly = AssemblyUtils.LoadAssembly(assemblyDllPath);
  196. }
  197. var assemblyExePath = binPath + string.Format("{0}.{1}", assemblyName, "exe");
  198. if (File.Exists(assemblyExePath))
  199. {
  200. assembly = AssemblyUtils.LoadAssembly(assemblyExePath);
  201. }
  202. return assembly != null ? assembly.GetType(typeName) : null;
  203. }
  204. public override string GetAssemblyCodeBase(Assembly assembly)
  205. {
  206. return assembly.CodeBase;
  207. }
  208. public override string GetAssemblyPath(Type source)
  209. {
  210. var assemblyUri = new Uri(source.Assembly.EscapedCodeBase);
  211. return assemblyUri.LocalPath;
  212. }
  213. public override string GetAsciiString(byte[] bytes, int index, int count)
  214. {
  215. return Encoding.ASCII.GetString(bytes, index, count);
  216. }
  217. public override byte[] GetAsciiBytes(string str)
  218. {
  219. return Encoding.ASCII.GetBytes(str);
  220. }
  221. public override bool InSameAssembly(Type t1, Type t2)
  222. {
  223. return t1.GetAssembly() == t2.GetAssembly();
  224. }
  225. public override Type GetGenericCollectionType(Type type)
  226. {
  227. return type.FindInterfaces((t, critera) =>
  228. t.IsGenericType
  229. && t.GetGenericTypeDefinition() == typeof(ICollection<>), null).FirstOrDefault();
  230. }
  231. public override PropertySetterDelegate GetPropertySetterFn(PropertyInfo propertyInfo)
  232. {
  233. var propertySetMethod = propertyInfo.SetMethod();
  234. if (propertySetMethod == null) return null;
  235. if (!SupportsExpression)
  236. {
  237. return (o, convertedValue) =>
  238. propertySetMethod.Invoke(o, new[] { convertedValue });
  239. }
  240. try
  241. {
  242. var instance = Expression.Parameter(typeof(object), "i");
  243. var argument = Expression.Parameter(typeof(object), "a");
  244. var instanceParam = Expression.Convert(instance, propertyInfo.ReflectedType());
  245. var valueParam = Expression.Convert(argument, propertyInfo.PropertyType);
  246. var setterCall = Expression.Call(instanceParam, propertySetMethod, valueParam);
  247. return Expression.Lambda<PropertySetterDelegate>(setterCall, instance, argument).Compile();
  248. }
  249. catch //fallback for Android
  250. {
  251. return (o, convertedValue) =>
  252. propertySetMethod.Invoke(o, new[] { convertedValue });
  253. }
  254. }
  255. public override PropertyGetterDelegate GetPropertyGetterFn(PropertyInfo propertyInfo)
  256. {
  257. if (!SupportsExpression)
  258. return base.GetPropertyGetterFn(propertyInfo);
  259. var getMethodInfo = propertyInfo.GetMethodInfo();
  260. if (getMethodInfo == null) return null;
  261. try
  262. {
  263. var oInstanceParam = Expression.Parameter(typeof(object), "oInstanceParam");
  264. var instanceParam = Expression.Convert(oInstanceParam, propertyInfo.ReflectedType); //propertyInfo.DeclaringType doesn't work on Proxy types
  265. var exprCallPropertyGetFn = Expression.Call(instanceParam, getMethodInfo);
  266. var oExprCallPropertyGetFn = Expression.Convert(exprCallPropertyGetFn, typeof(object));
  267. var propertyGetFn = Expression.Lambda<PropertyGetterDelegate>
  268. (
  269. oExprCallPropertyGetFn,
  270. oInstanceParam
  271. ).Compile();
  272. return propertyGetFn;
  273. }
  274. catch (Exception ex)
  275. {
  276. Tracer.Instance.WriteError(ex);
  277. throw;
  278. }
  279. }
  280. private static readonly MethodInfo setFieldMethod =
  281. typeof(Net40PclExport).GetStaticMethod("SetField");
  282. internal static void SetField<TValue>(ref TValue field, TValue newValue)
  283. {
  284. field = newValue;
  285. }
  286. public override PropertySetterDelegate GetFieldSetterFn(FieldInfo fieldInfo)
  287. {
  288. if (!SupportsExpression)
  289. return base.GetFieldSetterFn(fieldInfo);
  290. var fieldDeclaringType = fieldInfo.DeclaringType;
  291. var sourceParameter = Expression.Parameter(typeof(object), "source");
  292. var valueParameter = Expression.Parameter(typeof(object), "value");
  293. var sourceExpression = this.GetCastOrConvertExpression(sourceParameter, fieldDeclaringType);
  294. var fieldExpression = Expression.Field(sourceExpression, fieldInfo);
  295. var valueExpression = this.GetCastOrConvertExpression(valueParameter, fieldExpression.Type);
  296. var genericSetFieldMethodInfo = setFieldMethod.MakeGenericMethod(fieldExpression.Type);
  297. var setFieldMethodCallExpression = Expression.Call(
  298. null, genericSetFieldMethodInfo, fieldExpression, valueExpression);
  299. var setterFn = Expression.Lambda<PropertySetterDelegate>(
  300. setFieldMethodCallExpression, sourceParameter, valueParameter).Compile();
  301. return setterFn;
  302. }
  303. public override PropertyGetterDelegate GetFieldGetterFn(FieldInfo fieldInfo)
  304. {
  305. if (!SupportsExpression)
  306. return base.GetFieldGetterFn(fieldInfo);
  307. try
  308. {
  309. var fieldDeclaringType = fieldInfo.DeclaringType;
  310. var oInstanceParam = Expression.Parameter(typeof(object), "source");
  311. var instanceParam = this.GetCastOrConvertExpression(oInstanceParam, fieldDeclaringType);
  312. var exprCallFieldGetFn = Expression.Field(instanceParam, fieldInfo);
  313. //var oExprCallFieldGetFn = this.GetCastOrConvertExpression(exprCallFieldGetFn, typeof(object));
  314. var oExprCallFieldGetFn = Expression.Convert(exprCallFieldGetFn, typeof(object));
  315. var fieldGetterFn = Expression.Lambda<PropertyGetterDelegate>
  316. (
  317. oExprCallFieldGetFn,
  318. oInstanceParam
  319. )
  320. .Compile();
  321. return fieldGetterFn;
  322. }
  323. catch (Exception ex)
  324. {
  325. Tracer.Instance.WriteError(ex);
  326. throw;
  327. }
  328. }
  329. private Expression GetCastOrConvertExpression(Expression expression, Type targetType)
  330. {
  331. Expression result;
  332. var expressionType = expression.Type;
  333. if (targetType.IsAssignableFrom(expressionType))
  334. {
  335. result = expression;
  336. }
  337. else
  338. {
  339. // Check if we can use the as operator for casting or if we must use the convert method
  340. if (targetType.IsValueType && !targetType.IsNullableType())
  341. {
  342. result = Expression.Convert(expression, targetType);
  343. }
  344. else
  345. {
  346. result = Expression.TypeAs(expression, targetType);
  347. }
  348. }
  349. return result;
  350. }
  351. public override string ToXsdDateTimeString(DateTime dateTime)
  352. {
  353. #if !LITE
  354. return System.Xml.XmlConvert.ToString(dateTime.ToStableUniversalTime(), System.Xml.XmlDateTimeSerializationMode.Utc);
  355. #else
  356. return dateTime.ToStableUniversalTime().ToString(DateTimeSerializer.XsdDateTimeFormat);
  357. #endif
  358. }
  359. public override string ToLocalXsdDateTimeString(DateTime dateTime)
  360. {
  361. #if !LITE
  362. return System.Xml.XmlConvert.ToString(dateTime, System.Xml.XmlDateTimeSerializationMode.Local);
  363. #else
  364. return dateTime.ToString(DateTimeSerializer.XsdDateTimeFormat);
  365. #endif
  366. }
  367. public override DateTime ParseXsdDateTime(string dateTimeStr)
  368. {
  369. #if !LITE
  370. return System.Xml.XmlConvert.ToDateTime(dateTimeStr, System.Xml.XmlDateTimeSerializationMode.Utc);
  371. #else
  372. return DateTime.ParseExact(dateTimeStr, DateTimeSerializer.XsdDateTimeFormat, CultureInfo.InvariantCulture);
  373. #endif
  374. }
  375. #if !LITE
  376. public override DateTime ParseXsdDateTimeAsUtc(string dateTimeStr)
  377. {
  378. return System.Xml.XmlConvert.ToDateTime(dateTimeStr, System.Xml.XmlDateTimeSerializationMode.Utc).Prepare(parsedAsUtc: true);
  379. }
  380. #endif
  381. public override DateTime ToStableUniversalTime(DateTime dateTime)
  382. {
  383. // .Net 2.0 - 3.5 has an issue with DateTime.ToUniversalTime, but works ok with TimeZoneInfo.ConvertTimeToUtc.
  384. // .Net 4.0+ does this under the hood anyway.
  385. return TimeZoneInfo.ConvertTimeToUtc(dateTime);
  386. }
  387. public override ParseStringDelegate GetDictionaryParseMethod<TSerializer>(Type type)
  388. {
  389. if (type == typeof(Hashtable))
  390. {
  391. return SerializerUtils<TSerializer>.ParseHashtable;
  392. }
  393. return null;
  394. }
  395. public override ParseStringDelegate GetSpecializedCollectionParseMethod<TSerializer>(Type type)
  396. {
  397. if (type == typeof(StringCollection))
  398. {
  399. return SerializerUtils<TSerializer>.ParseStringCollection<TSerializer>;
  400. }
  401. return null;
  402. }
  403. public override ParseStringDelegate GetJsReaderParseMethod<TSerializer>(Type type)
  404. {
  405. #if !(__IOS__ || LITE)
  406. if (type.AssignableFrom(typeof(System.Dynamic.IDynamicMetaObjectProvider)) ||
  407. type.HasInterface(typeof(System.Dynamic.IDynamicMetaObjectProvider)))
  408. {
  409. return DeserializeDynamic<TSerializer>.Parse;
  410. }
  411. #endif
  412. return null;
  413. }
  414. public override void InitHttpWebRequest(HttpWebRequest httpReq,
  415. long? contentLength = null, bool allowAutoRedirect = true, bool keepAlive = true)
  416. {
  417. httpReq.UserAgent = Env.ServerUserAgent;
  418. httpReq.AllowAutoRedirect = allowAutoRedirect;
  419. httpReq.KeepAlive = keepAlive;
  420. if (contentLength != null)
  421. {
  422. httpReq.ContentLength = contentLength.Value;
  423. }
  424. }
  425. public override void CloseStream(Stream stream)
  426. {
  427. stream.Close();
  428. }
  429. public override LicenseKey VerifyLicenseKeyText(string licenseKeyText)
  430. {
  431. LicenseKey key;
  432. if (!licenseKeyText.VerifyLicenseKeyText(out key))
  433. throw new ArgumentException("licenseKeyText");
  434. return key;
  435. }
  436. public override void VerifyInAssembly(Type accessType, ICollection<string> assemblyNames)
  437. {
  438. //might get merged/mangled on alt platforms
  439. if (assemblyNames.Contains(accessType.Assembly.ManifestModule.Name))
  440. return;
  441. try
  442. {
  443. if (assemblyNames.Contains(accessType.Assembly.Location.SplitOnLast(Path.DirectorySeparatorChar).Last()))
  444. return;
  445. }
  446. catch (Exception)
  447. {
  448. return; //dynamic assembly
  449. }
  450. var errorDetails = " Type: '{0}', Assembly: '{1}', '{2}'".Fmt(
  451. accessType.Name,
  452. accessType.Assembly.ManifestModule.Name,
  453. accessType.Assembly.Location);
  454. throw new LicenseException(LicenseUtils.ErrorMessages.UnauthorizedAccessRequest + errorDetails);
  455. }
  456. public override void BeginThreadAffinity()
  457. {
  458. Thread.BeginThreadAffinity();
  459. }
  460. public override void EndThreadAffinity()
  461. {
  462. Thread.EndThreadAffinity();
  463. }
  464. public override void Config(HttpWebRequest req,
  465. bool? allowAutoRedirect = null,
  466. TimeSpan? timeout = null,
  467. TimeSpan? readWriteTimeout = null,
  468. string userAgent = null,
  469. bool? preAuthenticate = null)
  470. {
  471. req.MaximumResponseHeadersLength = int.MaxValue; //throws "The message length limit was exceeded" exception
  472. if (allowAutoRedirect.HasValue) req.AllowAutoRedirect = allowAutoRedirect.Value;
  473. if (readWriteTimeout.HasValue) req.ReadWriteTimeout = (int)readWriteTimeout.Value.TotalMilliseconds;
  474. if (timeout.HasValue) req.Timeout = (int)timeout.Value.TotalMilliseconds;
  475. if (userAgent != null) req.UserAgent = userAgent;
  476. if (preAuthenticate.HasValue) req.PreAuthenticate = preAuthenticate.Value;
  477. }
  478. public override string GetStackTrace()
  479. {
  480. return Environment.StackTrace;
  481. }
  482. #if !__IOS__
  483. public override SetPropertyDelegate GetSetPropertyMethod(PropertyInfo propertyInfo)
  484. {
  485. return CreateIlPropertySetter(propertyInfo);
  486. }
  487. public override SetPropertyDelegate GetSetFieldMethod(FieldInfo fieldInfo)
  488. {
  489. return CreateIlFieldSetter(fieldInfo);
  490. }
  491. public override SetPropertyDelegate GetSetMethod(PropertyInfo propertyInfo, FieldInfo fieldInfo)
  492. {
  493. return propertyInfo.CanWrite
  494. ? CreateIlPropertySetter(propertyInfo)
  495. : CreateIlFieldSetter(fieldInfo);
  496. }
  497. public override Type UseType(Type type)
  498. {
  499. if (type.IsInterface || type.IsAbstract)
  500. {
  501. return DynamicProxy.GetInstanceFor(type).GetType();
  502. }
  503. return type;
  504. }
  505. public override DataContractAttribute GetWeakDataContract(Type type)
  506. {
  507. return type.GetWeakDataContract();
  508. }
  509. public override DataMemberAttribute GetWeakDataMember(PropertyInfo pi)
  510. {
  511. return pi.GetWeakDataMember();
  512. }
  513. public override DataMemberAttribute GetWeakDataMember(FieldInfo pi)
  514. {
  515. return pi.GetWeakDataMember();
  516. }
  517. public static SetPropertyDelegate CreateIlPropertySetter(PropertyInfo propertyInfo)
  518. {
  519. var propSetMethod = propertyInfo.GetSetMethod(true);
  520. if (propSetMethod == null)
  521. return null;
  522. var setter = CreateDynamicSetMethod(propertyInfo);
  523. var generator = setter.GetILGenerator();
  524. generator.Emit(OpCodes.Ldarg_0);
  525. generator.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
  526. generator.Emit(OpCodes.Ldarg_1);
  527. generator.Emit(propertyInfo.PropertyType.IsClass
  528. ? OpCodes.Castclass
  529. : OpCodes.Unbox_Any,
  530. propertyInfo.PropertyType);
  531. generator.EmitCall(OpCodes.Callvirt, propSetMethod, (Type[])null);
  532. generator.Emit(OpCodes.Ret);
  533. return (SetPropertyDelegate)setter.CreateDelegate(typeof(SetPropertyDelegate));
  534. }
  535. public static SetPropertyDelegate CreateIlFieldSetter(FieldInfo fieldInfo)
  536. {
  537. var setter = CreateDynamicSetMethod(fieldInfo);
  538. var generator = setter.GetILGenerator();
  539. generator.Emit(OpCodes.Ldarg_0);
  540. generator.Emit(OpCodes.Castclass, fieldInfo.DeclaringType);
  541. generator.Emit(OpCodes.Ldarg_1);
  542. generator.Emit(fieldInfo.FieldType.IsClass
  543. ? OpCodes.Castclass
  544. : OpCodes.Unbox_Any,
  545. fieldInfo.FieldType);
  546. generator.Emit(OpCodes.Stfld, fieldInfo);
  547. generator.Emit(OpCodes.Ret);
  548. return (SetPropertyDelegate)setter.CreateDelegate(typeof(SetPropertyDelegate));
  549. }
  550. private static DynamicMethod CreateDynamicSetMethod(MemberInfo memberInfo)
  551. {
  552. var args = new[] { typeof(object), typeof(object) };
  553. var name = string.Format("_{0}{1}_", "Set", memberInfo.Name);
  554. var returnType = typeof(void);
  555. return !memberInfo.DeclaringType.IsInterface
  556. ? new DynamicMethod(name, returnType, args, memberInfo.DeclaringType, true)
  557. : new DynamicMethod(name, returnType, args, memberInfo.Module, true);
  558. }
  559. #endif
  560. }
  561. #if __MAC__
  562. public class MacPclExport : IosPclExport
  563. {
  564. public static new MacPclExport Provider = new MacPclExport();
  565. public MacPclExport()
  566. {
  567. PlatformName = "MAC";
  568. SupportsEmit = SupportsExpression = true;
  569. }
  570. public new static void Configure()
  571. {
  572. Configure(Provider);
  573. }
  574. }
  575. #endif
  576. #if NET45 || NETFX_CORE
  577. public class Net45PclExport : Net40PclExport
  578. {
  579. public static new Net45PclExport Provider = new IosPclExport();
  580. public Net45PclExport()
  581. {
  582. PlatformName = "NET45 " + Environment.OSVersion.Platform.ToString();
  583. }
  584. public new static void Configure()
  585. {
  586. Configure(Provider);
  587. }
  588. public override Task WriteAndFlushAsync(Stream stream, byte[] bytes)
  589. {
  590. return stream.WriteAsync(bytes, 0, bytes.Length)
  591. .ContinueWith(t => stream.FlushAsync());
  592. }
  593. }
  594. #endif
  595. #if __IOS__ || __MAC__
  596. [Preserve(AllMembers = true)]
  597. internal class Poco
  598. {
  599. public string Dummy { get; set; }
  600. }
  601. public class IosPclExport : Net40PclExport
  602. {
  603. public static new IosPclExport Provider = new IosPclExport();
  604. public IosPclExport()
  605. {
  606. PlatformName = "IOS";
  607. SupportsEmit = SupportsExpression = false;
  608. }
  609. public override void VerifyInAssembly(Type accessType, ICollection<string> assemblyNames)
  610. {
  611. }
  612. public new static void Configure()
  613. {
  614. Configure(Provider);
  615. }
  616. public override void ResetStream(Stream stream)
  617. {
  618. // MonoTouch throws NotSupportedException when setting System.Net.WebConnectionStream.Position
  619. // Not sure if the stream is used later though, so may have to copy to MemoryStream and
  620. // pass that around instead after this point?
  621. }
  622. /// <summary>
  623. /// Provide hint to IOS AOT compiler to pre-compile generic classes for all your DTOs.
  624. /// Just needs to be called once in a static constructor.
  625. /// </summary>
  626. [Preserve]
  627. public static void InitForAot()
  628. {
  629. }
  630. [Preserve]
  631. public override void RegisterForAot()
  632. {
  633. RegisterTypeForAot<Poco>();
  634. RegisterElement<Poco, string>();
  635. RegisterElement<Poco, bool>();
  636. RegisterElement<Poco, char>();
  637. RegisterElement<Poco, byte>();
  638. RegisterElement<Poco, sbyte>();
  639. RegisterElement<Poco, short>();
  640. RegisterElement<Poco, ushort>();
  641. RegisterElement<Poco, int>();
  642. RegisterElement<Poco, uint>();
  643. RegisterElement<Poco, long>();
  644. RegisterElement<Poco, ulong>();
  645. RegisterElement<Poco, float>();
  646. RegisterElement<Poco, double>();
  647. RegisterElement<Poco, decimal>();
  648. RegisterElement<Poco, bool?>();
  649. RegisterElement<Poco, char?>();
  650. RegisterElement<Poco, byte?>();
  651. RegisterElement<Poco, sbyte?>();
  652. RegisterElement<Poco, short?>();
  653. RegisterElement<Poco, ushort?>();
  654. RegisterElement<Poco, int?>();
  655. RegisterElement<Poco, uint?>();
  656. RegisterElement<Poco, long?>();
  657. RegisterElement<Poco, ulong?>();
  658. RegisterElement<Poco, float?>();
  659. RegisterElement<Poco, double?>();
  660. RegisterElement<Poco, decimal?>();
  661. //RegisterElement<Poco, JsonValue>();
  662. RegisterTypeForAot<DayOfWeek>(); // used by DateTime
  663. // register built in structs
  664. RegisterTypeForAot<Guid>();
  665. RegisterTypeForAot<TimeSpan>();
  666. RegisterTypeForAot<DateTime>();
  667. RegisterTypeForAot<DateTimeOffset>();
  668. RegisterTypeForAot<Guid?>();
  669. RegisterTypeForAot<TimeSpan?>();
  670. RegisterTypeForAot<DateTime?>();
  671. RegisterTypeForAot<DateTimeOffset?>();
  672. }
  673. [Preserve]
  674. public static void RegisterTypeForAot<T>()
  675. {
  676. AotConfig.RegisterSerializers<T>();
  677. }
  678. [Preserve]
  679. public static void RegisterQueryStringWriter()
  680. {
  681. var i = 0;
  682. if (QueryStringWriter<Poco>.WriteFn() != null) i++;
  683. }
  684. [Preserve]
  685. public static int RegisterElement<T, TElement>()
  686. {
  687. var i = 0;
  688. i += AotConfig.RegisterSerializers<TElement>();
  689. AotConfig.RegisterElement<T, TElement, JsonTypeSerializer>();
  690. AotConfig.RegisterElement<T, TElement, Text.Jsv.JsvTypeSerializer>();
  691. return i;
  692. }
  693. ///<summary>
  694. /// Class contains Ahead-of-Time (AOT) explicit class declarations which is used only to workaround "-aot-only" exceptions occured on device only.
  695. /// </summary>
  696. [Preserve(AllMembers = true)]
  697. internal class AotConfig
  698. {
  699. internal static JsReader<JsonTypeSerializer> jsonReader;
  700. internal static JsWriter<JsonTypeSerializer> jsonWriter;
  701. internal static JsReader<Text.Jsv.JsvTypeSerializer> jsvReader;
  702. internal static JsWriter<Text.Jsv.JsvTypeSerializer> jsvWriter;
  703. internal static JsonTypeSerializer jsonSerializer;
  704. internal static Text.Jsv.JsvTypeSerializer jsvSerializer;
  705. static AotConfig()
  706. {
  707. jsonSerializer = new JsonTypeSerializer();
  708. jsvSerializer = new Text.Jsv.JsvTypeSerializer();
  709. jsonReader = new JsReader<JsonTypeSerializer>();
  710. jsonWriter = new JsWriter<JsonTypeSerializer>();
  711. jsvReader = new JsReader<Text.Jsv.JsvTypeSerializer>();
  712. jsvWriter = new JsWriter<Text.Jsv.JsvTypeSerializer>();
  713. }
  714. internal static int RegisterSerializers<T>()
  715. {
  716. var i = 0;
  717. i += Register<T, JsonTypeSerializer>();
  718. if (jsonSerializer.GetParseFn<T>() != null) i++;
  719. if (jsonSerializer.GetWriteFn<T>() != null) i++;
  720. if (jsonReader.GetParseFn<T>() != null) i++;
  721. if (jsonWriter.GetWriteFn<T>() != null) i++;
  722. i += Register<T, Text.Jsv.JsvTypeSerializer>();
  723. if (jsvSerializer.GetParseFn<T>() != null) i++;
  724. if (jsvSerializer.GetWriteFn<T>() != null) i++;
  725. if (jsvReader.GetParseFn<T>() != null) i++;
  726. if (jsvWriter.GetWriteFn<T>() != null) i++;
  727. //RegisterCsvSerializer<T>();
  728. RegisterQueryStringWriter();
  729. return i;
  730. }
  731. internal static void RegisterCsvSerializer<T>()
  732. {
  733. CsvSerializer<T>.WriteFn();
  734. CsvSerializer<T>.WriteObject(null, null);
  735. CsvWriter<T>.Write(null, default(IEnumerable<T>));
  736. CsvWriter<T>.WriteRow(null, default(T));
  737. }
  738. public static ParseStringDelegate GetParseFn(Type type)
  739. {
  740. var parseFn = JsonTypeSerializer.Instance.GetParseFn(type);
  741. return parseFn;
  742. }
  743. internal static int Register<T, TSerializer>() where TSerializer : ITypeSerializer
  744. {
  745. var i = 0;
  746. if (JsonWriter<T>.WriteFn() != null) i++;
  747. if (JsonWriter.Instance.GetWriteFn<T>() != null) i++;
  748. if (JsonReader.Instance.GetParseFn<T>() != null) i++;
  749. if (JsonReader<T>.Parse(null) != null) i++;
  750. if (JsonReader<T>.GetParseFn() != null) i++;
  751. //if (JsWriter.GetTypeSerializer<JsonTypeSerializer>().GetWriteFn<T>() != null) i++;
  752. if (new List<T>() != null) i++;
  753. if (new T[0] != null) i++;
  754. JsConfig<T>.ExcludeTypeInfo = false;
  755. if (JsConfig<T>.OnDeserializedFn != null) i++;
  756. if (JsConfig<T>.HasDeserializeFn) i++;
  757. if (JsConfig<T>.SerializeFn != null) i++;
  758. if (JsConfig<T>.DeSerializeFn != null) i++;
  759. //JsConfig<T>.SerializeFn = arg => "";
  760. //JsConfig<T>.DeSerializeFn = arg => default(T);
  761. if (TypeConfig<T>.Properties != null) i++;
  762. /*
  763. if (WriteType<T, TSerializer>.Write != null) i++;
  764. if (WriteType<object, TSerializer>.Write != null) i++;
  765. if (DeserializeBuiltin<T>.Parse != null) i++;
  766. if (DeserializeArray<T[], TSerializer>.Parse != null) i++;
  767. DeserializeType<TSerializer>.ExtractType(null);
  768. DeserializeArrayWithElements<T, TSerializer>.ParseGenericArray(null, null);
  769. DeserializeCollection<TSerializer>.ParseCollection<T>(null, null, null);
  770. DeserializeListWithElements<T, TSerializer>.ParseGenericList(null, null, null);
  771. SpecializedQueueElements<T>.ConvertToQueue(null);
  772. SpecializedQueueElements<T>.ConvertToStack(null);
  773. */
  774. WriteListsOfElements<T, TSerializer>.WriteList(null, null);
  775. WriteListsOfElements<T, TSerializer>.WriteIList(null, null);
  776. WriteListsOfElements<T, TSerializer>.WriteEnumerable(null, null);
  777. WriteListsOfElements<T, TSerializer>.WriteListValueType(null, null);
  778. WriteListsOfElements<T, TSerializer>.WriteIListValueType(null, null);
  779. WriteListsOfElements<T, TSerializer>.WriteGenericArrayValueType(null, null);
  780. WriteListsOfElements<T, TSerializer>.WriteArray(null, null);
  781. TranslateListWithElements<T>.LateBoundTranslateToGenericICollection(null, null);
  782. TranslateListWithConvertibleElements<T, T>.LateBoundTranslateToGenericICollection(null, null);
  783. QueryStringWriter<T>.WriteObject(null, null);
  784. return i;
  785. }
  786. internal static void RegisterElement<T, TElement, TSerializer>() where TSerializer : ITypeSerializer
  787. {
  788. DeserializeDictionary<TSerializer>.ParseDictionary<T, TElement>(null, null, null, null);
  789. DeserializeDictionary<TSerializer>.ParseDictionary<TElement, T>(null, null, null, null);
  790. ToStringDictionaryMethods<T, TElement, TSerializer>.WriteIDictionary(null, null, null, null);
  791. ToStringDictionaryMethods<TElement, T, TSerializer>.WriteIDictionary(null, null, null, null);
  792. // Include List deserialisations from the Register<> method above. This solves issue where List<Guid> properties on responses deserialise to null.
  793. // No idea why this is happening because there is no visible exception raised. Suspect IOS is swallowing an AOT exception somewhere.
  794. DeserializeArrayWithElements<TElement, TSerializer>.ParseGenericArray(null, null);
  795. DeserializeListWithElements<TElement, TSerializer>.ParseGenericList(null, null, null);
  796. // Cannot use the line below for some unknown reason - when trying to compile to run on device, mtouch bombs during native code compile.
  797. // Something about this line or its inner workings is offensive to mtouch. Luckily this was not needed for my List<Guide> issue.
  798. // DeserializeCollection<JsonTypeSerializer>.ParseCollection<TElement>(null, null, null);
  799. TranslateListWithElements<TElement>.LateBoundTranslateToGenericICollection(null, typeof(List<TElement>));
  800. TranslateListWithConvertibleElements<TElement, TElement>.LateBoundTranslateToGenericICollection(null, typeof(List<TElement>));
  801. }
  802. }
  803. }
  804. #endif
  805. #if ANDROID
  806. public class AndroidPclExport : Net40PclExport
  807. {
  808. public static new AndroidPclExport Provider = new AndroidPclExport();
  809. public AndroidPclExport()
  810. {
  811. PlatformName = "Android";
  812. }
  813. public override void VerifyInAssembly(Type accessType, ICollection<string> assemblyNames)
  814. {
  815. }
  816. public new static void Configure()
  817. {
  818. Configure(Provider);
  819. }
  820. }
  821. #endif
  822. #if !__IOS__
  823. public static class DynamicProxy
  824. {
  825. public static T GetInstanceFor<T>()
  826. {
  827. return (T)GetInstanceFor(typeof(T));
  828. }
  829. static readonly ModuleBuilder ModuleBuilder;
  830. static readonly AssemblyBuilder DynamicAssembly;
  831. public static object GetInstanceFor(Type targetType)
  832. {
  833. lock (DynamicAssembly)
  834. {
  835. var constructedType = DynamicAssembly.GetType(ProxyName(targetType)) ?? GetConstructedType(targetType);
  836. var instance = Activator.CreateInstance(constructedType);
  837. return instance;
  838. }
  839. }
  840. static string ProxyName(Type targetType)
  841. {
  842. return targetType.Name + "Proxy";
  843. }
  844. static DynamicProxy()
  845. {
  846. var assemblyName = new AssemblyName("DynImpl");
  847. DynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
  848. ModuleBuilder = DynamicAssembly.DefineDynamicModule("DynImplModule");
  849. }
  850. static Type GetConstructedType(Type targetType)
  851. {
  852. var typeBuilder = ModuleBuilder.DefineType(targetType.Name + "Proxy", TypeAttributes.Public);
  853. var ctorBuilder = typeBuilder.DefineConstructor(
  854. MethodAttributes.Public,
  855. CallingConventions.Standard,
  856. new Type[] { });
  857. var ilGenerator = ctorBuilder.GetILGenerator();
  858. ilGenerator.Emit(OpCodes.Ret);
  859. IncludeType(targetType, typeBuilder);
  860. foreach (var face in targetType.GetInterfaces())
  861. IncludeType(face, typeBuilder);
  862. return typeBuilder.CreateType();
  863. }
  864. static void IncludeType(Type typeOfT, TypeBuilder typeBuilder)
  865. {
  866. var methodInfos = typeOfT.GetMethods();
  867. foreach (var methodInfo in methodInfos)
  868. {
  869. if (methodInfo.Name.StartsWith("set_", StringComparison.Ordinal)) continue; // we always add a set for a get.
  870. if (methodInfo.Name.StartsWith("get_", StringComparison.Ordinal))
  871. {
  872. BindProperty(typeBuilder, methodInfo);
  873. }
  874. else
  875. {
  876. BindMethod(typeBuilder, methodInfo);
  877. }
  878. }
  879. typeBuilder.AddInterfaceImplementation(typeOfT);
  880. }
  881. static void BindMethod(TypeBuilder typeBuilder, MethodInfo methodInfo)
  882. {
  883. var methodBuilder = typeBuilder.DefineMethod(
  884. methodInfo.Name,
  885. MethodAttributes.Public | MethodAttributes.Virtual,
  886. methodInfo.ReturnType,
  887. methodInfo.GetParameters().Select(p => p.GetType()).ToArray()
  888. );
  889. var methodILGen = methodBuilder.GetILGenerator();
  890. if (methodInfo.ReturnType == typeof(void))
  891. {
  892. methodILGen.Emit(OpCodes.Ret);
  893. }
  894. else
  895. {
  896. if (methodInfo.ReturnType.IsValueType || methodInfo.ReturnType.IsEnum)
  897. {
  898. MethodInfo getMethod = typeof(Activator).GetMethod("CreateInstance",
  899. new[] { typeof(Type) });
  900. LocalBuilder lb = methodILGen.DeclareLocal(methodInfo.ReturnType);
  901. methodILGen.Emit(OpCodes.Ldtoken, lb.LocalType);
  902. methodILGen.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"));
  903. methodILGen.Emit(OpCodes.Callvirt, getMethod);
  904. methodILGen.Emit(OpCodes.Unbox_Any, lb.LocalType);
  905. }
  906. else
  907. {
  908. methodILGen.Emit(OpCodes.Ldnull);
  909. }
  910. methodILGen.Emit(OpCodes.Ret);
  911. }
  912. typeBuilder.DefineMethodOverride(methodBuilder, methodInfo);
  913. }
  914. public static void BindProperty(TypeBuilder typeBuilder, MethodInfo methodInfo)
  915. {
  916. // Backing Field
  917. string propertyName = methodInfo.Name.Replace("get_", "");
  918. Type propertyType = methodInfo.ReturnType;
  919. FieldBuilder backingField = typeBuilder.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);
  920. //Getter
  921. MethodBuilder backingGet = typeBuilder.DefineMethod("get_" + propertyName, MethodAttributes.Public |
  922. MethodAttributes.SpecialName | MethodAttributes.Virtual |
  923. MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
  924. ILGenerator getIl = backingGet.GetILGenerator();
  925. getIl.Emit(OpCodes.Ldarg_0);
  926. getIl.Emit(OpCodes.Ldfld, backingField);
  927. getIl.Emit(OpCodes.Ret);
  928. //Setter
  929. MethodBuilder backingSet = typeBuilder.DefineMethod("set_" + propertyName, MethodAttributes.Public |
  930. MethodAttributes.SpecialName | MethodAttributes.Virtual |
  931. MethodAttributes.HideBySig, null, new[] { propertyType });
  932. ILGenerator setIl = backingSet.GetILGenerator();
  933. setIl.Emit(OpCodes.Ldarg_0);
  934. setIl.Emit(OpCodes.Ldarg_1);
  935. setIl.Emit(OpCodes.Stfld, backingField);
  936. setIl.Emit(OpCodes.Ret);
  937. // Property
  938. PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, propertyType, null);
  939. propertyBuilder.SetGetMethod(backingGet);
  940. propertyBuilder.SetSetMethod(backingSet);
  941. }
  942. }
  943. #endif
  944. internal class SerializerUtils<TSerializer>
  945. where TSerializer : ITypeSerializer
  946. {
  947. private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
  948. private static int VerifyAndGetStartIndex(string value, Type createMapType)
  949. {
  950. var index = 0;
  951. if (!Serializer.EatMapStartChar(value, ref index))
  952. {
  953. //Don't throw ex because some KeyValueDataContractDeserializer don't have '{}'
  954. Tracer.Instance.WriteDebug("WARN: Map definitions should start with a '{0}', expecting serialized type '{1}', got string starting with: {2}",
  955. JsWriter.MapStartChar, createMapType != null ? createMapType.Name : "Dictionary<,>", value.Substring(0, value.Length < 50 ? value.Length : 50));
  956. }
  957. return index;
  958. }
  959. public static Hashtable ParseHashtable(string value)
  960. {
  961. if (value == null)
  962. return null;
  963. var index = VerifyAndGetStartIndex(value, typeof(Hashtable));
  964. var result = new Hashtable();
  965. if (JsonTypeSerializer.IsEmptyMap(value, index)) return result;
  966. var valueLength = value.Length;
  967. while (index < valueLength)
  968. {
  969. var keyValue = Serializer.EatMapKey(value, ref index);
  970. Serializer.EatMapKeySeperator(value, ref index);
  971. var elementValue = Serializer.EatValue(value, ref index);
  972. if (keyValue == null) continue;
  973. var mapKey = keyValue;
  974. var mapValue = elementValue;
  975. result[mapKey] = mapValue;
  976. Serializer.EatItemSeperatorOrMapEndChar(value, ref index);
  977. }
  978. return result;
  979. }
  980. public static StringCollection ParseStringCollection<TS>(string value) where TS : ITypeSerializer
  981. {
  982. if ((value = DeserializeListWithElements<TS>.StripList(value)) == null) return null;
  983. return value == String.Empty
  984. ? new StringCollection()
  985. : ToStringCollection(DeserializeListWithElements<TSerializer>.ParseStringList(value));
  986. }
  987. public static StringCollection ToStringCollection(List<string> items)
  988. {
  989. var to = new StringCollection();
  990. foreach (var item in items)
  991. {
  992. to.Add(item);
  993. }
  994. return to;
  995. }
  996. }
  997. public static class PclExportExt
  998. {
  999. public static string ToFormUrlEncoded(this NameValueCollection queryParams)
  1000. {
  1001. var sb = new System.Text.StringBuilder();
  1002. foreach (string key in queryParams)
  1003. {
  1004. var values = queryParams.GetValues(key);
  1005. if (values == null) continue;
  1006. foreach (var value in values)
  1007. {
  1008. if (sb.Length > 0)
  1009. sb.Append('&');
  1010. sb.AppendFormat("{0}={1}", key.UrlEncode(), value.UrlEncode());
  1011. }
  1012. }
  1013. return sb.ToString();
  1014. }
  1015. //HttpUtils
  1016. public static WebResponse PostFileToUrl(this string url,
  1017. FileInfo uploadFileInfo, string uploadFileMimeType,
  1018. string accept = null,
  1019. Action<HttpWebRequest> requestFilter = null)
  1020. {
  1021. var webReq = (HttpWebRequest)WebRequest.Create(url);
  1022. using (var fileStream = uploadFileInfo.OpenRead())
  1023. {
  1024. var fileName = uploadFileInfo.Name;
  1025. webReq.UploadFile(fileStream, fileName, uploadFileMimeType, accept: accept, requestFilter: requestFilter, method: "POST");
  1026. }
  1027. if (HttpUtils.ResultsFilter != null)
  1028. return null;
  1029. return webReq.GetResponse();
  1030. }
  1031. public static WebResponse PutFileToUrl(this string url,
  1032. FileInfo uploadFileInfo, string uploadFileMimeType,
  1033. string accept = null,
  1034. Action<HttpWebRequest> requestFilter = null)
  1035. {
  1036. var webReq = (HttpWebRequest)WebRequest.Create(url);
  1037. using (var fileStream = uploadFileInfo.OpenRead())
  1038. {
  1039. var fileName = uploadFileInfo.Name;
  1040. webReq.UploadFile(fileStream, fileName, uploadFileMimeType, accept: accept, requestFilter: requestFilter, method: "PUT");
  1041. }
  1042. if (HttpUtils.ResultsFilter != null)
  1043. return null;
  1044. return webReq.GetResponse();
  1045. }
  1046. public static WebResponse UploadFile(this WebRequest webRequest,
  1047. FileInfo uploadFileInfo, string uploadFileMimeType)
  1048. {
  1049. using (var fileStream = uploadFileInfo.OpenRead())
  1050. {
  1051. var fileName = uploadFileInfo.Name;
  1052. webRequest.UploadFile(fileStream, fileName, uploadFileMimeType);
  1053. }
  1054. if (HttpUtils.ResultsFilter != null)
  1055. return null;
  1056. return webRequest.GetResponse();
  1057. }
  1058. //XmlSerializer
  1059. public static void CompressToStream<TXmlDto>(TXmlDto from, Stream stream)
  1060. {
  1061. #if __IOS__ || ANDROID
  1062. throw new NotImplementedException("Compression is not supported on this platform");
  1063. #else
  1064. using (var deflateStream = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Compress))
  1065. using (var xw = new System.Xml.XmlTextWriter(deflateStream, Encoding.UTF8))
  1066. {
  1067. var serializer = new DataContractSerializer(from.GetType());
  1068. serializer.WriteObject(xw, from);
  1069. xw.Flush();
  1070. }
  1071. #endif
  1072. }
  1073. public static byte[] Compress<TXmlDto>(TXmlDto from)
  1074. {
  1075. using (var ms = MemoryStreamFactory.GetStream())
  1076. {
  1077. CompressToStream(from, ms);
  1078. return ms.ToArray();
  1079. }
  1080. }
  1081. //License Utils
  1082. public static bool VerifySignedHash(byte[] DataToVerify, byte[] SignedData, RSAParameters Key)
  1083. {
  1084. try
  1085. {
  1086. var RSAalg = new RSACryptoServiceProvider();
  1087. RSAalg.ImportParameters(Key);
  1088. return RSAalg.VerifySha1Data(DataToVerify, SignedData);
  1089. }
  1090. catch (CryptographicException ex)
  1091. {
  1092. Tracer.Instance.WriteError(ex)

Large files files are truncated, but you can click here to view the full file