You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1079 lines
46 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. /*
  2. * MinIO .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017-2021 MinIO, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. using System.ComponentModel;
  17. using System.Diagnostics.CodeAnalysis;
  18. using System.Globalization;
  19. using System.Reflection;
  20. using System.Security.Cryptography;
  21. using System.Text;
  22. using System.Text.Json;
  23. using System.Text.RegularExpressions;
  24. using System.Xml;
  25. using System.Xml.Linq;
  26. using System.Xml.Serialization;
  27. using Minio.DataModel;
  28. using Minio.Exceptions;
  29. #if !NET6_0_OR_GREATER
  30. using System.Collections.Concurrent;
  31. #endif
  32. namespace Minio.Helper;
  33. public static class Utils
  34. {
  35. // We support '.' with bucket names but we fallback to using path
  36. // style requests instead for such buckets.
  37. private static readonly Regex validBucketName =
  38. new("^[a-z0-9][a-z0-9\\.\\-]{1,61}[a-z0-9]$", RegexOptions.None, TimeSpan.FromHours(1));
  39. // Invalid bucket name with double dot.
  40. private static readonly Regex invalidDotBucketName = new("`/./.", RegexOptions.None, TimeSpan.FromHours(1));
  41. private static readonly Lazy<IDictionary<string, string>> contentTypeMap = new(AddContentTypeMappings);
  42. /// <summary>
  43. /// IsValidBucketName - verify bucket name in accordance with
  44. /// http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html
  45. /// </summary>
  46. /// <param name="bucketName">Bucket to test existence of</param>
  47. internal static void ValidateBucketName(string bucketName)
  48. {
  49. if (string.IsNullOrEmpty(bucketName))
  50. throw new InvalidBucketNameException(bucketName, "Bucket name cannot be empty.");
  51. if (bucketName.Length < 3)
  52. throw new InvalidBucketNameException(bucketName, "Bucket name cannot be smaller than 3 characters.");
  53. if (bucketName.Length > 63)
  54. throw new InvalidBucketNameException(bucketName, "Bucket name cannot be greater than 63 characters.");
  55. if (bucketName[0] == '.' || bucketName[^1] == '.')
  56. throw new InvalidBucketNameException(bucketName, "Bucket name cannot start or end with a '.' dot.");
  57. if (bucketName.Any(char.IsUpper))
  58. throw new InvalidBucketNameException(bucketName, "Bucket name cannot have upper case characters");
  59. if (invalidDotBucketName.IsMatch(bucketName))
  60. throw new InvalidBucketNameException(bucketName, "Bucket name cannot have successive periods.");
  61. if (!validBucketName.IsMatch(bucketName))
  62. throw new InvalidBucketNameException(bucketName, "Bucket name contains invalid characters.");
  63. }
  64. // IsValidObjectName - verify object name in accordance with
  65. // http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html
  66. internal static void ValidateObjectName(string objectName)
  67. {
  68. if (string.IsNullOrEmpty(objectName) || string.IsNullOrEmpty(objectName.Trim()))
  69. throw new InvalidObjectNameException(objectName, "Object name cannot be empty.");
  70. // c# strings are in utf16 format. they are already in unicode format when they arrive here.
  71. if (objectName.Length > 512)
  72. throw new InvalidObjectNameException(objectName, "Object name cannot be greater than 1024 characters.");
  73. }
  74. internal static void ValidateObjectPrefix(string objectPrefix)
  75. {
  76. if (objectPrefix.Length > 512)
  77. throw new InvalidObjectPrefixException(objectPrefix,
  78. "Object prefix cannot be greater than 1024 characters.");
  79. }
  80. // Return url encoded string where reserved characters have been percent-encoded
  81. internal static string UrlEncode(string input)
  82. {
  83. // The following characters are not allowed on the server side
  84. // '-', '_', '.', '/', '*'
  85. return Uri.EscapeDataString(input).Replace("\\!", "%21", StringComparison.Ordinal)
  86. .Replace("\\\"", "%22", StringComparison.Ordinal)
  87. .Replace("\\#", "%23", StringComparison.Ordinal)
  88. .Replace("\\$", "%24", StringComparison.Ordinal)
  89. .Replace("\\%", "%25", StringComparison.Ordinal)
  90. .Replace("\\&", "%26", StringComparison.Ordinal)
  91. .Replace("\\'", "%27", StringComparison.Ordinal)
  92. .Replace("\\(", "%28", StringComparison.Ordinal)
  93. .Replace("\\)", "%29", StringComparison.Ordinal)
  94. .Replace("\\+", "%2B", StringComparison.Ordinal)
  95. .Replace("\\,", "%2C", StringComparison.Ordinal)
  96. .Replace("\\:", "%3A", StringComparison.Ordinal)
  97. .Replace("\\;", "%3B", StringComparison.Ordinal)
  98. .Replace("\\<", "%3C", StringComparison.Ordinal)
  99. .Replace("\\=", "%3D", StringComparison.Ordinal)
  100. .Replace("\\>", "%3E", StringComparison.Ordinal)
  101. .Replace("\\?", "%3F", StringComparison.Ordinal)
  102. .Replace("\\@", "%40", StringComparison.Ordinal)
  103. .Replace("\\[", "%5B", StringComparison.Ordinal)
  104. .Replace("\\\\", "%5C", StringComparison.Ordinal)
  105. .Replace("\\]", "%5D", StringComparison.Ordinal)
  106. .Replace("\\^", "%5E", StringComparison.Ordinal)
  107. .Replace("\\'", "%60", StringComparison.Ordinal)
  108. .Replace("\\{", "%7B", StringComparison.Ordinal)
  109. .Replace("\\|", "%7C", StringComparison.Ordinal)
  110. .Replace("\\}", "%7D", StringComparison.Ordinal)
  111. .Replace("\\~", "%7E", StringComparison.Ordinal);
  112. }
  113. // Return encoded path where extra "/" are trimmed off.
  114. internal static string EncodePath(string path)
  115. {
  116. var encodedPathBuf = new StringBuilder();
  117. foreach (var pathSegment in path.Split('/'))
  118. if (pathSegment.Length != 0)
  119. {
  120. if (encodedPathBuf.Length > 0) _ = encodedPathBuf.Append('/');
  121. _ = encodedPathBuf.Append(UrlEncode(pathSegment));
  122. }
  123. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase)) _ = encodedPathBuf.Insert(0, '/');
  124. if (path.EndsWith("/", StringComparison.OrdinalIgnoreCase)) _ = encodedPathBuf.Append('/');
  125. return encodedPathBuf.ToString();
  126. }
  127. internal static bool IsAnonymousClient(string accessKey, string secretKey)
  128. {
  129. return string.IsNullOrEmpty(secretKey) && string.IsNullOrEmpty(accessKey);
  130. }
  131. internal static void ValidateFile(string filePath)
  132. {
  133. if (string.IsNullOrEmpty(filePath))
  134. throw new ArgumentException("empty file name is not allowed", nameof(filePath));
  135. var fileName = Path.GetFileName(filePath);
  136. var fileExists = File.Exists(filePath);
  137. if (fileExists)
  138. {
  139. var attr = File.GetAttributes(filePath);
  140. if (attr.HasFlag(FileAttributes.Directory))
  141. throw new ArgumentException($"'{fileName}': not a regular file", nameof(filePath));
  142. }
  143. }
  144. internal static string GetContentType(string fileName)
  145. {
  146. string extension = null;
  147. try
  148. {
  149. extension = Path.GetExtension(fileName);
  150. }
  151. catch
  152. {
  153. }
  154. if (string.IsNullOrEmpty(extension)) return "application/octet-stream";
  155. return contentTypeMap.Value.TryGetValue(extension, out var contentType)
  156. ? contentType
  157. : "application/octet-stream";
  158. }
  159. public static void MoveWithReplace(string sourceFileName, string destFileName)
  160. {
  161. try
  162. {
  163. // first, delete target file if exists, as File.Move() does not support overwrite
  164. if (File.Exists(destFileName)) File.Delete(destFileName);
  165. File.Move(sourceFileName, destFileName);
  166. }
  167. catch
  168. {
  169. }
  170. }
  171. internal static bool IsSupersetOf(IList<string> l1, IList<string> l2)
  172. {
  173. if (l2 is null) return true;
  174. if (l1 is null) return false;
  175. return !l2.Except(l1, StringComparer.Ordinal).Any();
  176. }
  177. public static async Task ForEachAsync<TSource>(this IEnumerable<TSource> source, bool runInParallel = false,
  178. int maxNoOfParallelProcesses = 4) where TSource : Task
  179. {
  180. if (source is null) throw new ArgumentNullException(nameof(source));
  181. try
  182. {
  183. if (runInParallel)
  184. {
  185. #if NET6_0_OR_GREATER
  186. ParallelOptions parallelOptions = new()
  187. {
  188. MaxDegreeOfParallelism
  189. = maxNoOfParallelProcesses
  190. };
  191. await Parallel.ForEachAsync(source, parallelOptions,
  192. async (task, cancellationToken) => await task.ConfigureAwait(false)).ConfigureAwait(false);
  193. #else
  194. await Task.WhenAll(Partitioner.Create(source).GetPartitions(maxNoOfParallelProcesses)
  195. .Select(partition => Task.Run(async delegate
  196. {
  197. #pragma warning disable IDISP007 // Don't dispose injected
  198. using (partition)
  199. {
  200. while (partition.MoveNext())
  201. await partition.Current.ConfigureAwait(false);
  202. }
  203. #pragma warning restore IDISP007 // Don't dispose injected
  204. }
  205. ))).ConfigureAwait(false);
  206. #endif
  207. }
  208. else
  209. {
  210. foreach (var task in source) await task.ConfigureAwait(false);
  211. }
  212. }
  213. catch (AggregateException ae)
  214. {
  215. foreach (var ex in ae.Flatten().InnerExceptions)
  216. // Handle or log the individual exception 'ex'
  217. Console.WriteLine($"Exception occurred: {ex.Message}");
  218. }
  219. }
  220. public static bool CaseInsensitiveContains(string text, string value,
  221. StringComparison stringComparison = StringComparison.CurrentCultureIgnoreCase)
  222. {
  223. if (string.IsNullOrEmpty(text))
  224. throw new ArgumentException($"'{nameof(text)}' cannot be null or empty.", nameof(text));
  225. return text.Contains(value, stringComparison);
  226. }
  227. /// <summary>
  228. /// Calculate part size and number of parts required.
  229. /// </summary>
  230. /// <param name="size"></param>
  231. /// <param name="copy"> If true, use COPY part size, else use PUT part size</param>
  232. /// <returns></returns>
  233. public static MultiPartInfo CalculateMultiPartSize(long size, bool copy = false)
  234. {
  235. if (size == -1) size = Constants.MaximumStreamObjectSize;
  236. if (size > Constants.MaxMultipartPutObjectSize)
  237. throw new EntityTooLargeException(
  238. $"Your proposed upload size {size} exceeds the maximum allowed object size {Constants.MaxMultipartPutObjectSize}");
  239. var partSize = (double)Math.Ceiling((decimal)size / Constants.MaxParts);
  240. var minPartSize = copy ? Constants.MinimumCOPYPartSize : Constants.MinimumPUTPartSize;
  241. partSize = (double)Math.Ceiling((decimal)partSize / minPartSize) * minPartSize;
  242. var partCount = Math.Ceiling(size / partSize);
  243. var lastPartSize = size - ((partCount - 1) * partSize);
  244. return new MultiPartInfo { PartSize = partSize, PartCount = partCount, LastPartSize = lastPartSize };
  245. }
  246. /// <summary>
  247. /// Check if input expires value is valid.
  248. /// </summary>
  249. /// <param name="expiryInt">time to expiry in seconds</param>
  250. /// <returns>bool</returns>
  251. public static bool IsValidExpiry(int expiryInt)
  252. {
  253. return expiryInt > 0 && expiryInt <= Constants.DefaultExpiryTime;
  254. }
  255. internal static string GetMD5SumStr(ReadOnlySpan<byte> key)
  256. {
  257. #if NETSTANDARD
  258. #pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
  259. using var md5
  260. = MD5.Create();
  261. #pragma warning restore CA5351 // Do Not Use Broken Cryptographic Algorithms
  262. var hashedBytes
  263. = md5.ComputeHash(key.ToArray());
  264. #else
  265. ReadOnlySpan<byte> hashedBytes = MD5.HashData(key);
  266. #endif
  267. return Convert.ToBase64String(hashedBytes);
  268. }
  269. [SuppressMessage("Design", "MA0051:Method is too long", Justification = "One time list of type mappings")]
  270. private static Dictionary<string, string> AddContentTypeMappings()
  271. {
  272. return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
  273. {
  274. { ".323", "text/h323" },
  275. { ".3g2", "video/3gpp2" },
  276. { ".3gp", "video/3gpp" },
  277. { ".3gp2", "video/3gpp2" },
  278. { ".3gpp", "video/3gpp" },
  279. { ".7z", "application/x-7z-compressed" },
  280. { ".aa", "audio/audible" },
  281. { ".AAC", "audio/aac" },
  282. { ".aax", "audio/vnd.audible.aax" },
  283. { ".ac3", "audio/ac3" },
  284. { ".accda", "application/msaccess.addin" },
  285. { ".accdb", "application/msaccess" },
  286. { ".accdc", "application/msaccess.cab" },
  287. { ".accde", "application/msaccess" },
  288. { ".accdr", "application/msaccess.runtime" },
  289. { ".accdt", "application/msaccess" },
  290. { ".accdw", "application/msaccess.webapplication" },
  291. { ".accft", "application/msaccess.ftemplate" },
  292. { ".acx", "application/internet-property-stream" },
  293. { ".AddIn", "text/xml" },
  294. { ".ade", "application/msaccess" },
  295. { ".adobebridge", "application/x-bridge-url" },
  296. { ".adp", "application/msaccess" },
  297. { ".ADT", "audio/vnd.dlna.adts" },
  298. { ".ADTS", "audio/aac" },
  299. { ".ai", "application/postscript" },
  300. { ".aif", "audio/aiff" },
  301. { ".aifc", "audio/aiff" },
  302. { ".aiff", "audio/aiff" },
  303. { ".air", "application/vnd.adobe.air-application-installer-package+zip" },
  304. { ".amc", "application/mpeg" },
  305. { ".anx", "application/annodex" },
  306. { ".apk", "application/vnd.android.package-archive" },
  307. { ".application", "application/x-ms-application" },
  308. { ".art", "image/x-jg" },
  309. { ".asa", "application/xml" },
  310. { ".asax", "application/xml" },
  311. { ".ascx", "application/xml" },
  312. { ".asf", "video/x-ms-asf" },
  313. { ".ashx", "application/xml" },
  314. { ".asm", "text/plain" },
  315. { ".asmx", "application/xml" },
  316. { ".aspx", "application/xml" },
  317. { ".asr", "video/x-ms-asf" },
  318. { ".asx", "video/x-ms-asf" },
  319. { ".atom", "application/atom+xml" },
  320. { ".au", "audio/basic" },
  321. { ".avi", "video/x-msvideo" },
  322. { ".axa", "audio/annodex" },
  323. { ".axs", "application/olescript" },
  324. { ".axv", "video/annodex" },
  325. { ".bas", "text/plain" },
  326. { ".bcpio", "application/x-bcpio" },
  327. { ".bmp", "image/bmp" },
  328. { ".c", "text/plain" },
  329. { ".caf", "audio/x-caf" },
  330. { ".calx", "application/vnd.ms-office.calx" },
  331. { ".cat", "application/vnd.ms-pki.seccat" },
  332. { ".cc", "text/plain" },
  333. { ".cd", "text/plain" },
  334. { ".cdda", "audio/aiff" },
  335. { ".cdf", "application/x-cdf" },
  336. { ".cer", "application/x-x509-ca-cert" },
  337. { ".cfg", "text/plain" },
  338. { ".class", "application/x-java-applet" },
  339. { ".clp", "application/x-msclip" },
  340. { ".cmd", "text/plain" },
  341. { ".cmx", "image/x-cmx" },
  342. { ".cnf", "text/plain" },
  343. { ".cod", "image/cis-cod" },
  344. { ".config", "application/xml" },
  345. { ".contact", "text/x-ms-contact" },
  346. { ".coverage", "application/xml" },
  347. { ".cpio", "application/x-cpio" },
  348. { ".cpp", "text/plain" },
  349. { ".crd", "application/x-mscardfile" },
  350. { ".crl", "application/pkix-crl" },
  351. { ".crt", "application/x-x509-ca-cert" },
  352. { ".cs", "text/plain" },
  353. { ".csdproj", "text/plain" },
  354. { ".csh", "application/x-csh" },
  355. { ".csproj", "text/plain" },
  356. { ".css", "text/css" },
  357. { ".csv", "text/csv" },
  358. { ".cxx", "text/plain" },
  359. { ".datasource", "application/xml" },
  360. { ".dbproj", "text/plain" },
  361. { ".dcr", "application/x-director" },
  362. { ".def", "text/plain" },
  363. { ".der", "application/x-x509-ca-cert" },
  364. { ".dgml", "application/xml" },
  365. { ".dib", "image/bmp" },
  366. { ".dif", "video/x-dv" },
  367. { ".dir", "application/x-director" },
  368. { ".disco", "text/xml" },
  369. { ".divx", "video/divx" },
  370. { ".dll", "application/x-msdownload" },
  371. { ".dll.config", "text/xml" },
  372. { ".dlm", "text/dlm" },
  373. { ".doc", "application/msword" },
  374. { ".docm", "application/vnd.ms-word.document.macroEnabled.12" },
  375. { ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
  376. { ".dot", "application/msword" },
  377. { ".dotm", "application/vnd.ms-word.template.macroEnabled.12" },
  378. { ".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template" },
  379. { ".dsw", "text/plain" },
  380. { ".dtd", "text/xml" },
  381. { ".dtsConfig", "text/xml" },
  382. { ".dv", "video/x-dv" },
  383. { ".dvi", "application/x-dvi" },
  384. { ".dwf", "drawing/x-dwf" },
  385. { ".dwg", "application/acad" },
  386. { ".dxf", "application/x-dxf" },
  387. { ".dxr", "application/x-director" },
  388. { ".eml", "message/rfc822" },
  389. { ".eot", "application/vnd.ms-fontobject" },
  390. { ".eps", "application/postscript" },
  391. { ".etl", "application/etl" },
  392. { ".etx", "text/x-setext" },
  393. { ".evy", "application/envoy" },
  394. { ".exe.config", "text/xml" },
  395. { ".fdf", "application/vnd.fdf" },
  396. { ".fif", "application/fractals" },
  397. { ".filters", "application/xml" },
  398. { ".flac", "audio/flac" },
  399. { ".flr", "x-world/x-vrml" },
  400. { ".flv", "video/x-flv" },
  401. { ".fsscript", "application/fsharp-script" },
  402. { ".fsx", "application/fsharp-script" },
  403. { ".generictest", "application/xml" },
  404. { ".gif", "image/gif" },
  405. { ".gpx", "application/gpx+xml" },
  406. { ".group", "text/x-ms-group" },
  407. { ".gsm", "audio/x-gsm" },
  408. { ".gtar", "application/x-gtar" },
  409. { ".gz", "application/x-gzip" },
  410. { ".h", "text/plain" },
  411. { ".hdf", "application/x-hdf" },
  412. { ".hdml", "text/x-hdml" },
  413. { ".hhc", "application/x-oleobject" },
  414. { ".hlp", "application/winhlp" },
  415. { ".hpp", "text/plain" },
  416. { ".hqx", "application/mac-binhex40" },
  417. { ".hta", "application/hta" },
  418. { ".htc", "text/x-component" },
  419. { ".htm", "text/html" },
  420. { ".html", "text/html" },
  421. { ".htt", "text/webviewhtml" },
  422. { ".hxa", "application/xml" },
  423. { ".hxc", "application/xml" },
  424. { ".hxe", "application/xml" },
  425. { ".hxf", "application/xml" },
  426. { ".hxk", "application/xml" },
  427. { ".hxt", "text/html" },
  428. { ".hxv", "application/xml" },
  429. { ".hxx", "text/plain" },
  430. { ".i", "text/plain" },
  431. { ".ico", "image/x-icon" },
  432. { ".idl", "text/plain" },
  433. { ".ief", "image/ief" },
  434. { ".iii", "application/x-iphone" },
  435. { ".inc", "text/plain" },
  436. { ".ini", "text/plain" },
  437. { ".inl", "text/plain" },
  438. { ".ins", "application/x-internet-signup" },
  439. { ".ipa", "application/x-itunes-ipa" },
  440. { ".ipg", "application/x-itunes-ipg" },
  441. { ".ipproj", "text/plain" },
  442. { ".ipsw", "application/x-itunes-ipsw" },
  443. { ".iqy", "text/x-ms-iqy" },
  444. { ".isp", "application/x-internet-signup" },
  445. { ".ite", "application/x-itunes-ite" },
  446. { ".itlp", "application/x-itunes-itlp" },
  447. { ".itms", "application/x-itunes-itms" },
  448. { ".itpc", "application/x-itunes-itpc" },
  449. { ".IVF", "video/x-ivf" },
  450. { ".jar", "application/java-archive" },
  451. { ".jck", "application/liquidmotion" },
  452. { ".jcz", "application/liquidmotion" },
  453. { ".jfif", "image/pjpeg" },
  454. { ".jnlp", "application/x-java-jnlp-file" },
  455. { ".jpe", "image/jpeg" },
  456. { ".jpeg", "image/jpeg" },
  457. { ".jpg", "image/jpeg" },
  458. { ".js", "application/javascript" },
  459. { ".json", "application/json" },
  460. { ".jsx", "text/jscript" },
  461. { ".jsxbin", "text/plain" },
  462. { ".latex", "application/x-latex" },
  463. { ".library-ms", "application/windows-library+xml" },
  464. { ".lit", "application/x-ms-reader" },
  465. { ".loadtest", "application/xml" },
  466. { ".lsf", "video/x-la-asf" },
  467. { ".lst", "text/plain" },
  468. { ".lsx", "video/x-la-asf" },
  469. { ".m13", "application/x-msmediaview" },
  470. { ".m14", "application/x-msmediaview" },
  471. { ".m1v", "video/mpeg" },
  472. { ".m2t", "video/vnd.dlna.mpeg-tts" },
  473. { ".m2ts", "video/vnd.dlna.mpeg-tts" },
  474. { ".m2v", "video/mpeg" },
  475. { ".m3u", "audio/x-mpegurl" },
  476. { ".m3u8", "audio/x-mpegurl" },
  477. { ".m4a", "audio/m4a" },
  478. { ".m4b", "audio/m4b" },
  479. { ".m4p", "audio/m4p" },
  480. { ".m4r", "audio/x-m4r" },
  481. { ".m4v", "video/x-m4v" },
  482. { ".mac", "image/x-macpaint" },
  483. { ".mak", "text/plain" },
  484. { ".man", "application/x-troff-man" },
  485. { ".manifest", "application/x-ms-manifest" },
  486. { ".map", "text/plain" },
  487. { ".master", "application/xml" },
  488. { ".mbox", "application/mbox" },
  489. { ".mda", "application/msaccess" },
  490. { ".mdb", "application/x-msaccess" },
  491. { ".mde", "application/msaccess" },
  492. { ".me", "application/x-troff-me" },
  493. { ".mfp", "application/x-shockwave-flash" },
  494. { ".mht", "message/rfc822" },
  495. { ".mhtml", "message/rfc822" },
  496. { ".mid", "audio/mid" },
  497. { ".midi", "audio/mid" },
  498. { ".mk", "text/plain" },
  499. { ".mmf", "application/x-smaf" },
  500. { ".mno", "text/xml" },
  501. { ".mny", "application/x-msmoney" },
  502. { ".mod", "video/mpeg" },
  503. { ".mov", "video/quicktime" },
  504. { ".movie", "video/x-sgi-movie" },
  505. { ".mp2", "video/mpeg" },
  506. { ".mp2v", "video/mpeg" },
  507. { ".mp3", "audio/mpeg" },
  508. { ".mp4", "video/mp4" },
  509. { ".mp4v", "video/mp4" },
  510. { ".mpa", "video/mpeg" },
  511. { ".mpe", "video/mpeg" },
  512. { ".mpeg", "video/mpeg" },
  513. { ".mpf", "application/vnd.ms-mediapackage" },
  514. { ".mpg", "video/mpeg" },
  515. { ".mpp", "application/vnd.ms-project" },
  516. { ".mpv2", "video/mpeg" },
  517. { ".mqv", "video/quicktime" },
  518. { ".ms", "application/x-troff-ms" },
  519. { ".msg", "application/vnd.ms-outlook" },
  520. { ".mts", "video/vnd.dlna.mpeg-tts" },
  521. { ".mtx", "application/xml" },
  522. { ".mvb", "application/x-msmediaview" },
  523. { ".mvc", "application/x-miva-compiled" },
  524. { ".mxp", "application/x-mmxp" },
  525. { ".nc", "application/x-netcdf" },
  526. { ".nsc", "video/x-ms-asf" },
  527. { ".nws", "message/rfc822" },
  528. { ".oda", "application/oda" },
  529. { ".odb", "application/vnd.oasis.opendocument.database" },
  530. { ".odc", "application/vnd.oasis.opendocument.chart" },
  531. { ".odf", "application/vnd.oasis.opendocument.formula" },
  532. { ".odg", "application/vnd.oasis.opendocument.graphics" },
  533. { ".odh", "text/plain" },
  534. { ".odi", "application/vnd.oasis.opendocument.image" },
  535. { ".odl", "text/plain" },
  536. { ".odm", "application/vnd.oasis.opendocument.text-master" },
  537. { ".odp", "application/vnd.oasis.opendocument.presentation" },
  538. { ".ods", "application/vnd.oasis.opendocument.spreadsheet" },
  539. { ".odt", "application/vnd.oasis.opendocument.text" },
  540. { ".oga", "audio/ogg" },
  541. { ".ogg", "audio/ogg" },
  542. { ".ogv", "video/ogg" },
  543. { ".ogx", "application/ogg" },
  544. { ".one", "application/onenote" },
  545. { ".onea", "application/onenote" },
  546. { ".onepkg", "application/onenote" },
  547. { ".onetmp", "application/onenote" },
  548. { ".onetoc", "application/onenote" },
  549. { ".onetoc2", "application/onenote" },
  550. { ".opus", "audio/ogg" },
  551. { ".orderedtest", "application/xml" },
  552. { ".osdx", "application/opensearchdescription+xml" },
  553. { ".otf", "application/font-sfnt" },
  554. { ".otg", "application/vnd.oasis.opendocument.graphics-template" },
  555. { ".oth", "application/vnd.oasis.opendocument.text-web" },
  556. { ".otp", "application/vnd.oasis.opendocument.presentation-template" },
  557. { ".ots", "application/vnd.oasis.opendocument.spreadsheet-template" },
  558. { ".ott", "application/vnd.oasis.opendocument.text-template" },
  559. { ".oxt", "application/vnd.openofficeorg.extension" },
  560. { ".p10", "application/pkcs10" },
  561. { ".p12", "application/x-pkcs12" },
  562. { ".p7b", "application/x-pkcs7-certificates" },
  563. { ".p7c", "application/pkcs7-mime" },
  564. { ".p7m", "application/pkcs7-mime" },
  565. { ".p7r", "application/x-pkcs7-certreqresp" },
  566. { ".p7s", "application/pkcs7-signature" },
  567. { ".pbm", "image/x-portable-bitmap" },
  568. { ".pcast", "application/x-podcast" },
  569. { ".pct", "image/pict" },
  570. { ".pdf", "application/pdf" },
  571. { ".pfx", "application/x-pkcs12" },
  572. { ".pgm", "image/x-portable-graymap" },
  573. { ".pic", "image/pict" },
  574. { ".pict", "image/pict" },
  575. { ".pkgdef", "text/plain" },
  576. { ".pkgundef", "text/plain" },
  577. { ".pko", "application/vnd.ms-pki.pko" },
  578. { ".pls", "audio/scpls" },
  579. { ".pma", "application/x-perfmon" },
  580. { ".pmc", "application/x-perfmon" },
  581. { ".pml", "application/x-perfmon" },
  582. { ".pmr", "application/x-perfmon" },
  583. { ".pmw", "application/x-perfmon" },
  584. { ".png", "image/png" },
  585. { ".pnm", "image/x-portable-anymap" },
  586. { ".pnt", "image/x-macpaint" },
  587. { ".pntg", "image/x-macpaint" },
  588. { ".pnz", "image/png" },
  589. { ".pot", "application/vnd.ms-powerpoint" },
  590. { ".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12" },
  591. { ".potx", "application/vnd.openxmlformats-officedocument.presentationml.template" },
  592. { ".ppa", "application/vnd.ms-powerpoint" },
  593. { ".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12" },
  594. { ".ppm", "image/x-portable-pixmap" },
  595. { ".pps", "application/vnd.ms-powerpoint" },
  596. { ".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12" },
  597. { ".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow" },
  598. { ".ppt", "application/vnd.ms-powerpoint" },
  599. { ".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12" },
  600. { ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
  601. { ".prf", "application/pics-rules" },
  602. { ".ps", "application/postscript" },
  603. { ".psc1", "application/PowerShell" },
  604. { ".psess", "application/xml" },
  605. { ".pst", "application/vnd.ms-outlook" },
  606. { ".pub", "application/x-mspublisher" },
  607. { ".pwz", "application/vnd.ms-powerpoint" },
  608. { ".qht", "text/x-html-insertion" },
  609. { ".qhtm", "text/x-html-insertion" },
  610. { ".qt", "video/quicktime" },
  611. { ".qti", "image/x-quicktime" },
  612. { ".qtif", "image/x-quicktime" },
  613. { ".qtl", "application/x-quicktimeplayer" },
  614. { ".ra", "audio/x-pn-realaudio" },
  615. { ".ram", "audio/x-pn-realaudio" },
  616. { ".rar", "application/x-rar-compressed" },
  617. { ".ras", "image/x-cmu-raster" },
  618. { ".rat", "application/rat-file" },
  619. { ".rc", "text/plain" },
  620. { ".rc2", "text/plain" },
  621. { ".rct", "text/plain" },
  622. { ".rdlc", "application/xml" },
  623. { ".reg", "text/plain" },
  624. { ".resx", "application/xml" },
  625. { ".rf", "image/vnd.rn-realflash" },
  626. { ".rgb", "image/x-rgb" },
  627. { ".rgs", "text/plain" },
  628. { ".rm", "application/vnd.rn-realmedia" },
  629. { ".rmi", "audio/mid" },
  630. { ".rmp", "application/vnd.rn-rn_music_package" },
  631. { ".roff", "application/x-troff" },
  632. { ".rpm", "audio/x-pn-realaudio-plugin" },
  633. { ".rqy", "text/x-ms-rqy" },
  634. { ".rtf", "application/rtf" },
  635. { ".rtx", "text/richtext" },
  636. { ".ruleset", "application/xml" },
  637. { ".s", "text/plain" },
  638. { ".safariextz", "application/x-safari-safariextz" },
  639. { ".scd", "application/x-msschedule" },
  640. { ".scr", "text/plain" },
  641. { ".sct", "text/scriptlet" },
  642. { ".sd2", "audio/x-sd2" },
  643. { ".sdp", "application/sdp" },
  644. { ".searchConnector-ms", "application/windows-search-connector+xml" },
  645. { ".setpay", "application/set-payment-initiation" },
  646. { ".setreg", "application/set-registration-initiation" },
  647. { ".settings", "application/xml" },
  648. { ".sgimb", "application/x-sgimb" },
  649. { ".sgml", "text/sgml" },
  650. { ".sh", "application/x-sh" },
  651. { ".shar", "application/x-shar" },
  652. { ".shtml", "text/html" },
  653. { ".sit", "application/x-stuffit" },
  654. { ".sitemap", "application/xml" },
  655. { ".skin", "application/xml" },
  656. { ".skp", "application/x-koan" },
  657. { ".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12" },
  658. { ".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide" },
  659. { ".slk", "application/vnd.ms-excel" },
  660. { ".sln", "text/plain" },
  661. { ".slupkg-ms", "application/x-ms-license" },
  662. { ".smd", "audio/x-smd" },
  663. { ".smx", "audio/x-smd" },
  664. { ".smz", "audio/x-smd" },
  665. { ".snd", "audio/basic" },
  666. { ".snippet", "application/xml" },
  667. { ".sol", "text/plain" },
  668. { ".sor", "text/plain" },
  669. { ".spc", "application/x-pkcs7-certificates" },
  670. { ".spl", "application/futuresplash" },
  671. { ".spx", "audio/ogg" },
  672. { ".src", "application/x-wais-source" },
  673. { ".srf", "text/plain" },
  674. { ".SSISDeploymentManifest", "text/xml" },
  675. { ".ssm", "application/streamingmedia" },
  676. { ".sst", "application/vnd.ms-pki.certstore" },
  677. { ".stl", "application/vnd.ms-pki.stl" },
  678. { ".sv4cpio", "application/x-sv4cpio" },
  679. { ".sv4crc", "application/x-sv4crc" },
  680. { ".svc", "application/xml" },
  681. { ".svg", "image/svg+xml" },
  682. { ".swf", "application/x-shockwave-flash" },
  683. { ".step", "application/step" },
  684. { ".stp", "application/step" },
  685. { ".t", "application/x-troff" },
  686. { ".tar", "application/x-tar" },
  687. { ".tcl", "application/x-tcl" },
  688. { ".testrunconfig", "application/xml" },
  689. { ".testsettings", "application/xml" },
  690. { ".tex", "application/x-tex" },
  691. { ".texi", "application/x-texinfo" },
  692. { ".texinfo", "application/x-texinfo" },
  693. { ".tgz", "application/x-compressed" },
  694. { ".thmx", "application/vnd.ms-officetheme" },
  695. { ".tif", "image/tiff" },
  696. { ".tiff", "image/tiff" },
  697. { ".tlh", "text/plain" },
  698. { ".tli", "text/plain" },
  699. { ".tr", "application/x-troff" },
  700. { ".trm", "application/x-msterminal" },
  701. { ".trx", "application/xml" },
  702. { ".ts", "video/vnd.dlna.mpeg-tts" },
  703. { ".tsv", "text/tab-separated-values" },
  704. { ".ttf", "application/font-sfnt" },
  705. { ".tts", "video/vnd.dlna.mpeg-tts" },
  706. { ".txt", "text/plain" },
  707. { ".uls", "text/iuls" },
  708. { ".user", "text/plain" },
  709. { ".ustar", "application/x-ustar" },
  710. { ".vb", "text/plain" },
  711. { ".vbdproj", "text/plain" },
  712. { ".vbk", "video/mpeg" },
  713. { ".vbproj", "text/plain" },
  714. { ".vbs", "text/vbscript" },
  715. { ".vcf", "text/x-vcard" },
  716. { ".vcproj", "application/xml" },
  717. { ".vcs", "text/plain" },
  718. { ".vcxproj", "application/xml" },
  719. { ".vddproj", "text/plain" },
  720. { ".vdp", "text/plain" },
  721. { ".vdproj", "text/plain" },
  722. { ".vdx", "application/vnd.ms-visio.viewer" },
  723. { ".vml", "text/xml" },
  724. { ".vscontent", "application/xml" },
  725. { ".vsct", "text/xml" },
  726. { ".vsd", "application/vnd.visio" },
  727. { ".vsi", "application/ms-vsi" },
  728. { ".vsix", "application/vsix" },
  729. { ".vsixlangpack", "text/xml" },
  730. { ".vsixmanifest", "text/xml" },
  731. { ".vsmdi", "application/xml" },
  732. { ".vspscc", "text/plain" },
  733. { ".vss", "application/vnd.visio" },
  734. { ".vsscc", "text/plain" },
  735. { ".vssettings", "text/xml" },
  736. { ".vssscc", "text/plain" },
  737. { ".vst", "application/vnd.visio" },
  738. { ".vstemplate", "text/xml" },
  739. { ".vsto", "application/x-ms-vsto" },
  740. { ".vsw", "application/vnd.visio" },
  741. { ".vsx", "application/vnd.visio" },
  742. { ".vtx", "application/vnd.visio" },
  743. { ".wav", "audio/wav" },
  744. { ".wave", "audio/wav" },
  745. { ".wax", "audio/x-ms-wax" },
  746. { ".wbk", "application/msword" },
  747. { ".wbmp", "image/vnd.wap.wbmp" },
  748. { ".wcm", "application/vnd.ms-works" },
  749. { ".wdb", "application/vnd.ms-works" },
  750. { ".wdp", "image/vnd.ms-photo" },
  751. { ".webarchive", "application/x-safari-webarchive" },
  752. { ".webm", "video/webm" },
  753. { ".webp", "image/webp" },
  754. { ".webtest", "application/xml" },
  755. { ".wiq", "application/xml" },
  756. { ".wiz", "application/msword" },
  757. { ".wks", "application/vnd.ms-works" },
  758. { ".WLMP", "application/wlmoviemaker" },
  759. { ".wlpginstall", "application/x-wlpg-detect" },
  760. { ".wlpginstall3", "application/x-wlpg3-detect" },
  761. { ".wm", "video/x-ms-wm" },
  762. { ".wma", "audio/x-ms-wma" },
  763. { ".wmd", "application/x-ms-wmd" },
  764. { ".wmf", "application/x-msmetafile" },
  765. { ".wml", "text/vnd.wap.wml" },
  766. { ".wmlc", "application/vnd.wap.wmlc" },
  767. { ".wmls", "text/vnd.wap.wmlscript" },
  768. { ".wmlsc", "application/vnd.wap.wmlscriptc" },
  769. { ".wmp", "video/x-ms-wmp" },
  770. { ".wmv", "video/x-ms-wmv" },
  771. { ".wmx", "video/x-ms-wmx" },
  772. { ".wmz", "application/x-ms-wmz" },
  773. { ".woff", "application/font-woff" },
  774. { ".wpl", "application/vnd.ms-wpl" },
  775. { ".wps", "application/vnd.ms-works" },
  776. { ".wri", "application/x-mswrite" },
  777. { ".wrl", "x-world/x-vrml" },
  778. { ".wrz", "x-world/x-vrml" },
  779. { ".wsc", "text/scriptlet" },
  780. { ".wsdl", "text/xml" },
  781. { ".wvx", "video/x-ms-wvx" },
  782. { ".x", "application/directx" },
  783. { ".xaf", "x-world/x-vrml" },
  784. { ".xaml", "application/xaml+xml" },
  785. { ".xap", "application/x-silverlight-app" },
  786. { ".xbap", "application/x-ms-xbap" },
  787. { ".xbm", "image/x-xbitmap" },
  788. { ".xdr", "text/plain" },
  789. { ".xht", "application/xhtml+xml" },
  790. { ".xhtml", "application/xhtml+xml" },
  791. { ".xla", "application/vnd.ms-excel" },
  792. { ".xlam", "application/vnd.ms-excel.addin.macroEnabled.12" },
  793. { ".xlc", "application/vnd.ms-excel" },
  794. { ".xld", "application/vnd.ms-excel" },
  795. { ".xlk", "application/vnd.ms-excel" },
  796. { ".xll", "application/vnd.ms-excel" },
  797. { ".xlm", "application/vnd.ms-excel" },
  798. { ".xls", "application/vnd.ms-excel" },
  799. { ".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12" },
  800. { ".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12" },
  801. { ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
  802. { ".xlt", "application/vnd.ms-excel" },
  803. { ".xltm", "application/vnd.ms-excel.template.macroEnabled.12" },
  804. { ".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template" },
  805. { ".xlw", "application/vnd.ms-excel" },
  806. { ".xml", "text/xml" },
  807. { ".xmta", "application/xml" },
  808. { ".xof", "x-world/x-vrml" },
  809. { ".XOML", "text/plain" },
  810. { ".xpm", "image/x-xpixmap" },
  811. { ".xps", "application/vnd.ms-xpsdocument" },
  812. { ".xrm-ms", "text/xml" },
  813. { ".xsc", "application/xml" },
  814. { ".xsd", "text/xml" },
  815. { ".xsf", "text/xml" },
  816. { ".xsl", "text/xml" },
  817. { ".xslt", "text/xml" },
  818. { ".xss", "application/xml" },
  819. { ".xspf", "application/xspf+xml" },
  820. { ".xwd", "image/x-xwindowdump" },
  821. { ".z", "application/x-compress" },
  822. { ".zip", "application/zip" }
  823. };
  824. }
  825. public static string MarshalXML(object obj, string nmspc)
  826. {
  827. if (obj is null) throw new ArgumentNullException(nameof(obj));
  828. XmlWriter xw = null;
  829. var str = string.Empty;
  830. try
  831. {
  832. var settings = new XmlWriterSettings { OmitXmlDeclaration = true };
  833. var ns = new XmlSerializerNamespaces();
  834. ns.Add("", nmspc);
  835. using var sw = new StringWriter(CultureInfo.InvariantCulture);
  836. var xs = new XmlSerializer(obj.GetType());
  837. using (xw = XmlWriter.Create(sw, settings))
  838. {
  839. xs.Serialize(xw, obj, ns);
  840. xw.Flush();
  841. str = sw.ToString();
  842. }
  843. }
  844. finally
  845. {
  846. xw.Close();
  847. }
  848. return str;
  849. }
  850. public static string To8601String(DateTime dt)
  851. {
  852. return dt.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ssZ", CultureInfo.InvariantCulture);
  853. }
  854. public static string RemoveNamespaceInXML(string config)
  855. {
  856. // We'll need to remove the namespace within the serialized configuration
  857. const RegexOptions regexOptions =
  858. RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace |
  859. RegexOptions.Multiline;
  860. var patternToReplace =
  861. @"<\w+\s+\w+:nil=""true""(\s+xmlns:\w+=""http://www.w3.org/2001/XMLSchema-instance"")?\s*/>";
  862. const string patternToMatch = @"<\w+\s+xmlns=""http://s3.amazonaws.com/doc/2006-03-01/""\s*>";
  863. if (Regex.Match(config, patternToMatch, regexOptions, TimeSpan.FromHours(1)).Success)
  864. patternToReplace = @"xmlns=""http://s3.amazonaws.com/doc/2006-03-01/""\s*";
  865. return Regex.Replace(
  866. config,
  867. patternToReplace,
  868. string.Empty,
  869. regexOptions,
  870. TimeSpan.FromHours(1)
  871. );
  872. }
  873. public static DateTime From8601String(string dt)
  874. {
  875. return DateTime.Parse(dt, null, DateTimeStyles.RoundtripKind);
  876. }
  877. public static Uri GetBaseUrl(string endpoint)
  878. {
  879. if (string.IsNullOrEmpty(endpoint))
  880. throw new ArgumentException(
  881. string.Format(CultureInfo.InvariantCulture,
  882. "{0} is the value of the endpoint. It can't be null or empty.", endpoint),
  883. nameof(endpoint));
  884. if (endpoint.EndsWith("/", StringComparison.OrdinalIgnoreCase))
  885. endpoint = endpoint[..^1];
  886. if (!endpoint.StartsWith("http", StringComparison.OrdinalIgnoreCase) &&
  887. !BuilderUtil.IsValidHostnameOrIPAddress(endpoint))
  888. throw new InvalidEndpointException(
  889. string.Format(CultureInfo.InvariantCulture, "{0} is invalid hostname.", endpoint), "endpoint");
  890. string conn_url;
  891. if (endpoint.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  892. throw new InvalidEndpointException(
  893. string.Format(CultureInfo.InvariantCulture,
  894. "{0} the value of the endpoint has the scheme (http/https) in it.", endpoint),
  895. "endpoint");
  896. var enable_https = Environment.GetEnvironmentVariable("ENABLE_HTTPS");
  897. var scheme = enable_https?.Equals("1", StringComparison.OrdinalIgnoreCase) == true ? "https://" : "http://";
  898. conn_url = scheme + endpoint;
  899. var url = new Uri(conn_url);
  900. var hostnameOfUri = url.Authority;
  901. if (!string.IsNullOrWhiteSpace(hostnameOfUri) && !BuilderUtil.IsValidHostnameOrIPAddress(hostnameOfUri))
  902. throw new InvalidEndpointException(
  903. string.Format(CultureInfo.InvariantCulture, "{0}, {1} is invalid hostname.", endpoint, hostnameOfUri),
  904. "endpoint");
  905. return url;
  906. }
  907. internal static HttpRequestMessageBuilder GetEmptyRestRequest(HttpRequestMessageBuilder requestBuilder)
  908. {
  909. var serializedBody = JsonSerializer.Serialize("");
  910. requestBuilder.AddOrUpdateHeaderParameter("application/json; charset=utf-8", serializedBody);
  911. return requestBuilder;
  912. }
  913. // Converts an object to a byte array
  914. public static ReadOnlyMemory<byte> ObjectToByteArray(object obj)
  915. {
  916. switch (obj)
  917. {
  918. case null:
  919. case Memory<byte> memory when memory.IsEmpty:
  920. case ReadOnlyMemory<byte> readOnlyMemory when readOnlyMemory.IsEmpty:
  921. return null;
  922. default:
  923. return JsonSerializer.SerializeToUtf8Bytes(obj);
  924. }
  925. }
  926. // Print object key properties and their values
  927. // Added for debugging purposes
  928. public static void ObjPrint(object obj)
  929. {
  930. foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
  931. {
  932. var name = descriptor.Name;
  933. var value = descriptor.GetValue(obj);
  934. Console.WriteLine($"{name}={value}");
  935. }
  936. }
  937. public static void Print(object obj)
  938. {
  939. if (obj is null) throw new ArgumentNullException(nameof(obj));
  940. foreach (var prop in obj.GetType()
  941. .GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
  942. {
  943. var value = prop.GetValue(obj, Array.Empty<object>());
  944. Console.WriteLine("DEBUG >> {0} = {1}", prop.Name, value);
  945. }
  946. Console.WriteLine("DEBUG >> Print is DONE!\n\n");
  947. }
  948. public static void PrintDict(IDictionary<string, string> d)
  949. {
  950. if (d is not null)
  951. foreach (var kv in d)
  952. Console.WriteLine("DEBUG >> {0} = {1}", kv.Key, kv.Value);
  953. Console.WriteLine("DEBUG >> Done printing\n");
  954. }
  955. public static string DetermineNamespace(XDocument document)
  956. {
  957. if (document is null) throw new ArgumentNullException(nameof(document));
  958. return document.Root.Attributes().FirstOrDefault(attr => attr.IsNamespaceDeclaration)?.Value ?? string.Empty;
  959. }
  960. public static string SerializeToXml<T>(T anyobject) where T : class
  961. {
  962. if (anyobject is null) throw new ArgumentNullException(nameof(anyobject));
  963. var xs = new XmlSerializer(anyobject.GetType());
  964. using var sw = new StringWriter(CultureInfo.InvariantCulture);
  965. using var xw = XmlWriter.Create(sw);
  966. xs.Serialize(xw, anyobject);
  967. xw.Flush();
  968. return sw.ToString();
  969. }
  970. public static T DeserializeXml<T>(Stream stream) where T : class, new()
  971. {
  972. if (stream == null || stream.Length == 0) return default;
  973. var ns = GetNamespace<T>();
  974. if (!string.IsNullOrWhiteSpace(ns) && string.Equals(ns, "http://s3.amazonaws.com/doc/2006-03-01/",
  975. StringComparison.OrdinalIgnoreCase))
  976. {
  977. using var amazonAwsS3XmlReader = new AmazonAwsS3XmlReader(stream);
  978. return (T)new XmlSerializer(typeof(T)).Deserialize(amazonAwsS3XmlReader);
  979. }
  980. using var reader = new StreamReader(stream);
  981. var xmlContent = reader.ReadToEnd();
  982. return DeserializeXml<T>(xmlContent); // Call the string overload
  983. }
  984. public static T DeserializeXml<T>(string xml) where T : class, new()
  985. {
  986. if (string.IsNullOrEmpty(xml)) return default;
  987. var settings = new XmlReaderSettings
  988. {
  989. // Disable DTD processing
  990. DtdProcessing = DtdProcessing.Prohibit,
  991. // Disable XML schema validation
  992. XmlResolver = null
  993. };
  994. using var stringReader = new StringReader(xml);
  995. using var xmlReader = XmlReader.Create(stringReader, settings);
  996. var serializer = new XmlSerializer(typeof(T));
  997. return (T)serializer.Deserialize(xmlReader);
  998. }
  999. private static string GetNamespace<T>()
  1000. {
  1001. return typeof(T).GetCustomAttributes(typeof(XmlRootAttribute), true)
  1002. .FirstOrDefault() is XmlRootAttribute xmlRootAttribute
  1003. ? xmlRootAttribute.Namespace
  1004. : null;
  1005. }
  1006. }