PtUtil.cs 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462
  1. // Copyright (c) Microsoft. All rights reserved.
  2. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Diagnostics.CodeAnalysis;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Security.Cryptography;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using System.Xml;
  14. using System.Xml.Linq;
  15. using System.Xml.Schema;
  16. namespace OpenXmlPowerTools
  17. {
  18. public static class PtUtils
  19. {
  20. public static string SHA1HashStringForUTF8String(string s)
  21. {
  22. byte[] bytes = Encoding.UTF8.GetBytes(s);
  23. var sha1 = SHA1.Create();
  24. byte[] hashBytes = sha1.ComputeHash(bytes);
  25. return HexStringFromBytes(hashBytes);
  26. }
  27. public static string SHA1HashStringForByteArray(byte[] bytes)
  28. {
  29. var sha1 = SHA1.Create();
  30. byte[] hashBytes = sha1.ComputeHash(bytes);
  31. return HexStringFromBytes(hashBytes);
  32. }
  33. public static string HexStringFromBytes(byte[] bytes)
  34. {
  35. var sb = new StringBuilder();
  36. foreach (byte b in bytes)
  37. {
  38. var hex = b.ToString("x2");
  39. sb.Append(hex);
  40. }
  41. return sb.ToString();
  42. }
  43. public static string NormalizeDirName(string dirName)
  44. {
  45. string d = dirName.Replace('\\', '/');
  46. if (d[dirName.Length - 1] != '/' && d[dirName.Length - 1] != '\\')
  47. return d + "/";
  48. return d;
  49. }
  50. public static string MakeValidXml(string p)
  51. {
  52. return p.Any(c => c < 0x20)
  53. ? p.Select(c => c < 0x20 ? string.Format("_{0:X}_", (int) c) : c.ToString()).StringConcatenate()
  54. : p;
  55. }
  56. public static void AddElementIfMissing(XDocument partXDoc, XElement existing, string newElement)
  57. {
  58. if (existing != null)
  59. return;
  60. XElement newXElement = XElement.Parse(newElement);
  61. newXElement.Attributes().Where(a => a.IsNamespaceDeclaration).Remove();
  62. if (partXDoc.Root != null) partXDoc.Root.Add(newXElement);
  63. }
  64. }
  65. public class MhtParser
  66. {
  67. public string MimeVersion;
  68. public string ContentType;
  69. public MhtParserPart[] Parts;
  70. public class MhtParserPart
  71. {
  72. public string ContentLocation;
  73. public string ContentTransferEncoding;
  74. public string ContentType;
  75. public string CharSet;
  76. public string Text;
  77. public byte[] Binary;
  78. }
  79. public static MhtParser Parse(string src)
  80. {
  81. string mimeVersion = null;
  82. string contentType = null;
  83. string boundary = null;
  84. string[] lines = src.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
  85. var priambleKeyWords = new[]
  86. {
  87. "MIME-VERSION:",
  88. "CONTENT-TYPE:",
  89. };
  90. var priamble = lines.TakeWhile(l =>
  91. {
  92. var s = l.ToUpper();
  93. return priambleKeyWords.Any(pk => s.StartsWith(pk));
  94. }).ToArray();
  95. foreach (var item in priamble)
  96. {
  97. if (item.ToUpper().StartsWith("MIME-VERSION:"))
  98. mimeVersion = item.Substring("MIME-VERSION:".Length).Trim();
  99. else if (item.ToUpper().StartsWith("CONTENT-TYPE:"))
  100. {
  101. var contentTypeLine = item.Substring("CONTENT-TYPE:".Length).Trim();
  102. var spl = contentTypeLine.Split(';').Select(z => z.Trim()).ToArray();
  103. foreach (var s in spl)
  104. {
  105. if (s.StartsWith("boundary"))
  106. {
  107. var begText = "boundary=\"";
  108. var begLen = begText.Length;
  109. boundary = s.Substring(begLen, s.Length - begLen - 1).TrimStart('-');
  110. continue;
  111. }
  112. if (contentType == null)
  113. {
  114. contentType = s;
  115. continue;
  116. }
  117. throw new OpenXmlPowerToolsException("Unexpected content in MHTML");
  118. }
  119. }
  120. }
  121. var grouped = lines
  122. .Skip(priamble.Length)
  123. .GroupAdjacent(l =>
  124. {
  125. var b = l.TrimStart('-') == boundary;
  126. return b;
  127. })
  128. .Where(g => g.Key == false)
  129. .ToArray();
  130. var parts = grouped.Select(rp =>
  131. {
  132. var partPriambleKeyWords = new[]
  133. {
  134. "CONTENT-LOCATION:",
  135. "CONTENT-TRANSFER-ENCODING:",
  136. "CONTENT-TYPE:",
  137. };
  138. var partPriamble = rp.TakeWhile(l =>
  139. {
  140. var s = l.ToUpper();
  141. return partPriambleKeyWords.Any(pk => s.StartsWith(pk));
  142. }).ToArray();
  143. string contentLocation = null;
  144. string contentTransferEncoding = null;
  145. string partContentType = null;
  146. string partCharSet = null;
  147. byte[] partBinary = null;
  148. foreach (var item in partPriamble)
  149. {
  150. if (item.ToUpper().StartsWith("CONTENT-LOCATION:"))
  151. contentLocation = item.Substring("CONTENT-LOCATION:".Length).Trim();
  152. else if (item.ToUpper().StartsWith("CONTENT-TRANSFER-ENCODING:"))
  153. contentTransferEncoding = item.Substring("CONTENT-TRANSFER-ENCODING:".Length).Trim();
  154. else if (item.ToUpper().StartsWith("CONTENT-TYPE:"))
  155. partContentType = item.Substring("CONTENT-TYPE:".Length).Trim();
  156. }
  157. var blankLinesAtBeginning = rp
  158. .Skip(partPriamble.Length)
  159. .TakeWhile(l => l == "")
  160. .Count();
  161. var partText = rp
  162. .Skip(partPriamble.Length)
  163. .Skip(blankLinesAtBeginning)
  164. .Select(l => l + Environment.NewLine)
  165. .StringConcatenate();
  166. if (partContentType != null && partContentType.Contains(";"))
  167. {
  168. string thisPartContentType = null;
  169. var spl = partContentType.Split(';').Select(s => s.Trim()).ToArray();
  170. foreach (var s in spl)
  171. {
  172. if (s.StartsWith("charset"))
  173. {
  174. var begText = "charset=\"";
  175. var begLen = begText.Length;
  176. partCharSet = s.Substring(begLen, s.Length - begLen - 1);
  177. continue;
  178. }
  179. if (thisPartContentType == null)
  180. {
  181. thisPartContentType = s;
  182. continue;
  183. }
  184. throw new OpenXmlPowerToolsException("Unexpected content in MHTML");
  185. }
  186. partContentType = thisPartContentType;
  187. }
  188. if (contentTransferEncoding != null && contentTransferEncoding.ToUpper() == "BASE64")
  189. {
  190. partBinary = Convert.FromBase64String(partText);
  191. }
  192. return new MhtParserPart()
  193. {
  194. ContentLocation = contentLocation,
  195. ContentTransferEncoding = contentTransferEncoding,
  196. ContentType = partContentType,
  197. CharSet = partCharSet,
  198. Text = partText,
  199. Binary = partBinary,
  200. };
  201. })
  202. .Where(p => p.ContentType != null)
  203. .ToArray();
  204. return new MhtParser()
  205. {
  206. ContentType = contentType,
  207. MimeVersion = mimeVersion,
  208. Parts = parts,
  209. };
  210. }
  211. }
  212. public class Normalizer
  213. {
  214. public static XDocument Normalize(XDocument source, XmlSchemaSet schema)
  215. {
  216. bool havePSVI = false;
  217. // validate, throw errors, add PSVI information
  218. if (schema != null)
  219. {
  220. source.Validate(schema, null, true);
  221. havePSVI = true;
  222. }
  223. return new XDocument(
  224. source.Declaration,
  225. source.Nodes().Select(n =>
  226. {
  227. // Remove comments, processing instructions, and text nodes that are
  228. // children of XDocument. Only white space text nodes are allowed as
  229. // children of a document, so we can remove all text nodes.
  230. if (n is XComment || n is XProcessingInstruction || n is XText)
  231. return null;
  232. XElement e = n as XElement;
  233. if (e != null)
  234. return NormalizeElement(e, havePSVI);
  235. return n;
  236. }
  237. )
  238. );
  239. }
  240. public static bool DeepEqualsWithNormalization(XDocument doc1, XDocument doc2,
  241. XmlSchemaSet schemaSet)
  242. {
  243. XDocument d1 = Normalize(doc1, schemaSet);
  244. XDocument d2 = Normalize(doc2, schemaSet);
  245. return XNode.DeepEquals(d1, d2);
  246. }
  247. private static IEnumerable<XAttribute> NormalizeAttributes(XElement element,
  248. bool havePSVI)
  249. {
  250. return element.Attributes()
  251. .Where(a => !a.IsNamespaceDeclaration &&
  252. a.Name != XSI.schemaLocation &&
  253. a.Name != XSI.noNamespaceSchemaLocation)
  254. .OrderBy(a => a.Name.NamespaceName)
  255. .ThenBy(a => a.Name.LocalName)
  256. .Select(
  257. a =>
  258. {
  259. if (havePSVI)
  260. {
  261. var dt = a.GetSchemaInfo().SchemaType.TypeCode;
  262. switch (dt)
  263. {
  264. case XmlTypeCode.Boolean:
  265. return new XAttribute(a.Name, (bool)a);
  266. case XmlTypeCode.DateTime:
  267. return new XAttribute(a.Name, (DateTime)a);
  268. case XmlTypeCode.Decimal:
  269. return new XAttribute(a.Name, (decimal)a);
  270. case XmlTypeCode.Double:
  271. return new XAttribute(a.Name, (double)a);
  272. case XmlTypeCode.Float:
  273. return new XAttribute(a.Name, (float)a);
  274. case XmlTypeCode.HexBinary:
  275. case XmlTypeCode.Language:
  276. return new XAttribute(a.Name,
  277. ((string)a).ToLower());
  278. }
  279. }
  280. return a;
  281. }
  282. );
  283. }
  284. private static XNode NormalizeNode(XNode node, bool havePSVI)
  285. {
  286. // trim comments and processing instructions from normalized tree
  287. if (node is XComment || node is XProcessingInstruction)
  288. return null;
  289. XElement e = node as XElement;
  290. if (e != null)
  291. return NormalizeElement(e, havePSVI);
  292. // Only thing left is XCData and XText, so clone them
  293. return node;
  294. }
  295. private static XElement NormalizeElement(XElement element, bool havePSVI)
  296. {
  297. if (havePSVI)
  298. {
  299. var dt = element.GetSchemaInfo();
  300. switch (dt.SchemaType.TypeCode)
  301. {
  302. case XmlTypeCode.Boolean:
  303. return new XElement(element.Name,
  304. NormalizeAttributes(element, havePSVI),
  305. (bool)element);
  306. case XmlTypeCode.DateTime:
  307. return new XElement(element.Name,
  308. NormalizeAttributes(element, havePSVI),
  309. (DateTime)element);
  310. case XmlTypeCode.Decimal:
  311. return new XElement(element.Name,
  312. NormalizeAttributes(element, havePSVI),
  313. (decimal)element);
  314. case XmlTypeCode.Double:
  315. return new XElement(element.Name,
  316. NormalizeAttributes(element, havePSVI),
  317. (double)element);
  318. case XmlTypeCode.Float:
  319. return new XElement(element.Name,
  320. NormalizeAttributes(element, havePSVI),
  321. (float)element);
  322. case XmlTypeCode.HexBinary:
  323. case XmlTypeCode.Language:
  324. return new XElement(element.Name,
  325. NormalizeAttributes(element, havePSVI),
  326. ((string)element).ToLower());
  327. default:
  328. return new XElement(element.Name,
  329. NormalizeAttributes(element, havePSVI),
  330. element.Nodes().Select(n => NormalizeNode(n, havePSVI))
  331. );
  332. }
  333. }
  334. else
  335. {
  336. return new XElement(element.Name,
  337. NormalizeAttributes(element, havePSVI),
  338. element.Nodes().Select(n => NormalizeNode(n, havePSVI))
  339. );
  340. }
  341. }
  342. }
  343. public class FileUtils
  344. {
  345. public static DirectoryInfo GetDateTimeStampedDirectoryInfo(string prefix)
  346. {
  347. DateTime now = DateTime.Now;
  348. string dirName =
  349. prefix +
  350. string.Format("-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", now.Year - 2000, now.Month, now.Day, now.Hour,
  351. now.Minute, now.Second);
  352. return new DirectoryInfo(dirName);
  353. }
  354. public static FileInfo GetDateTimeStampedFileInfo(string prefix, string suffix)
  355. {
  356. DateTime now = DateTime.Now;
  357. string fileName =
  358. prefix +
  359. string.Format("-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", now.Year - 2000, now.Month, now.Day, now.Hour,
  360. now.Minute, now.Second) +
  361. suffix;
  362. return new FileInfo(fileName);
  363. }
  364. public static void ThreadSafeCreateDirectory(DirectoryInfo dir)
  365. {
  366. while (true)
  367. {
  368. if (dir.Exists)
  369. break;
  370. try
  371. {
  372. dir.Create();
  373. break;
  374. }
  375. catch (IOException)
  376. {
  377. Task.Delay (50);
  378. }
  379. }
  380. }
  381. public static void ThreadSafeCopy(FileInfo sourceFile, FileInfo destFile)
  382. {
  383. while (true)
  384. {
  385. if (destFile.Exists)
  386. break;
  387. try
  388. {
  389. File.Copy(sourceFile.FullName, destFile.FullName);
  390. break;
  391. }
  392. catch (IOException)
  393. {
  394. Task.Delay(50);
  395. }
  396. }
  397. }
  398. public static void ThreadSafeCreateEmptyTextFileIfNotExist(FileInfo file)
  399. {
  400. while (true)
  401. {
  402. if (file.Exists)
  403. break;
  404. try
  405. {
  406. File.WriteAllText(file.FullName, "");
  407. break;
  408. }
  409. catch (IOException)
  410. {
  411. Task.Delay(50);
  412. }
  413. }
  414. }
  415. #if !NET35
  416. internal static void ThreadSafeAppendAllLines(FileInfo file, string[] strings)
  417. {
  418. while (true)
  419. {
  420. try
  421. {
  422. File.AppendAllLines(file.FullName, strings);
  423. break;
  424. }
  425. catch (IOException)
  426. {
  427. Task.Delay(50);
  428. }
  429. }
  430. }
  431. #endif
  432. public static List<string> GetFilesRecursive(DirectoryInfo dir, string searchPattern)
  433. {
  434. var fileList = new List<string>();
  435. GetFilesRecursiveInternal(dir, searchPattern, fileList);
  436. return fileList;
  437. }
  438. private static void GetFilesRecursiveInternal(DirectoryInfo dir, string searchPattern, List<string> fileList)
  439. {
  440. fileList.AddRange(dir.GetFiles(searchPattern).Select(file => file.FullName));
  441. foreach (DirectoryInfo subdir in dir.GetDirectories())
  442. GetFilesRecursiveInternal(subdir, searchPattern, fileList);
  443. }
  444. public static List<string> GetFilesRecursive(DirectoryInfo dir)
  445. {
  446. var fileList = new List<string>();
  447. GetFilesRecursiveInternal(dir, fileList);
  448. return fileList;
  449. }
  450. private static void GetFilesRecursiveInternal(DirectoryInfo dir, List<string> fileList)
  451. {
  452. fileList.AddRange(dir.GetFiles().Select(file => file.FullName));
  453. foreach (DirectoryInfo subdir in dir.GetDirectories())
  454. GetFilesRecursiveInternal(subdir, fileList);
  455. }
  456. public static void CopyStream(Stream source, Stream target)
  457. {
  458. const int bufSize = 0x4096;
  459. var buf = new byte[bufSize];
  460. int bytesRead;
  461. while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
  462. target.Write(buf, 0, bytesRead);
  463. }
  464. }
  465. public static class PtExtensions
  466. {
  467. public static XElement GetXElement(this XmlNode node)
  468. {
  469. var xDoc = new XDocument();
  470. using (XmlWriter xmlWriter = xDoc.CreateWriter())
  471. node.WriteTo(xmlWriter);
  472. return xDoc.Root;
  473. }
  474. public static XmlNode GetXmlNode(this XElement element)
  475. {
  476. var xmlDoc = new XmlDocument();
  477. using (XmlReader xmlReader = element.CreateReader())
  478. xmlDoc.Load(xmlReader);
  479. return xmlDoc;
  480. }
  481. public static XDocument GetXDocument(this XmlDocument document)
  482. {
  483. var xDoc = new XDocument();
  484. using (XmlWriter xmlWriter = xDoc.CreateWriter())
  485. document.WriteTo(xmlWriter);
  486. XmlDeclaration decl = document.ChildNodes.OfType<XmlDeclaration>().FirstOrDefault();
  487. if (decl != null)
  488. xDoc.Declaration = new XDeclaration(decl.Version, decl.Encoding, decl.Standalone);
  489. return xDoc;
  490. }
  491. public static XmlDocument GetXmlDocument(this XDocument document)
  492. {
  493. var xmlDoc = new XmlDocument();
  494. using (XmlReader xmlReader = document.CreateReader())
  495. {
  496. xmlDoc.Load(xmlReader);
  497. if (document.Declaration != null)
  498. {
  499. XmlDeclaration dec = xmlDoc.CreateXmlDeclaration(document.Declaration.Version,
  500. document.Declaration.Encoding, document.Declaration.Standalone);
  501. xmlDoc.InsertBefore(dec, xmlDoc.FirstChild);
  502. }
  503. }
  504. return xmlDoc;
  505. }
  506. public static string StringConcatenate(this IEnumerable<string> source)
  507. {
  508. return source.Aggregate(
  509. new StringBuilder(),
  510. (sb, s) => sb.Append(s),
  511. sb => sb.ToString());
  512. }
  513. public static string StringConcatenate<T>(this IEnumerable<T> source, Func<T, string> projectionFunc)
  514. {
  515. return source.Aggregate(
  516. new StringBuilder(),
  517. (sb, i) => sb.Append(projectionFunc(i)),
  518. sb => sb.ToString());
  519. }
  520. public static IEnumerable<TResult> PtZip<TFirst, TSecond, TResult>(
  521. this IEnumerable<TFirst> first,
  522. IEnumerable<TSecond> second,
  523. Func<TFirst, TSecond, TResult> func)
  524. {
  525. using (IEnumerator<TFirst> ie1 = first.GetEnumerator())
  526. using (IEnumerator<TSecond> ie2 = second.GetEnumerator())
  527. while (ie1.MoveNext() && ie2.MoveNext())
  528. yield return func(ie1.Current, ie2.Current);
  529. }
  530. public static IEnumerable<IGrouping<TKey, TSource>> GroupAdjacent<TSource, TKey>(
  531. this IEnumerable<TSource> source,
  532. Func<TSource, TKey> keySelector)
  533. {
  534. TKey last = default(TKey);
  535. var haveLast = false;
  536. var list = new List<TSource>();
  537. foreach (TSource s in source)
  538. {
  539. TKey k = keySelector(s);
  540. if (haveLast)
  541. {
  542. if (!k.Equals(last))
  543. {
  544. yield return new GroupOfAdjacent<TSource, TKey>(list, last);
  545. list = new List<TSource> { s };
  546. last = k;
  547. }
  548. else
  549. {
  550. list.Add(s);
  551. last = k;
  552. }
  553. }
  554. else
  555. {
  556. list.Add(s);
  557. last = k;
  558. haveLast = true;
  559. }
  560. }
  561. if (haveLast)
  562. yield return new GroupOfAdjacent<TSource, TKey>(list, last);
  563. }
  564. private static void InitializeSiblingsReverseDocumentOrder(XElement element)
  565. {
  566. XElement prev = null;
  567. foreach (XElement e in element.Elements())
  568. {
  569. e.AddAnnotation(new SiblingsReverseDocumentOrderInfo { PreviousSibling = prev });
  570. prev = e;
  571. }
  572. }
  573. [SuppressMessage("ReSharper", "PossibleNullReferenceException")]
  574. public static IEnumerable<XElement> SiblingsBeforeSelfReverseDocumentOrder(
  575. this XElement element)
  576. {
  577. if (element.Annotation<SiblingsReverseDocumentOrderInfo>() == null)
  578. InitializeSiblingsReverseDocumentOrder(element.Parent);
  579. XElement current = element;
  580. while (true)
  581. {
  582. XElement previousElement = current
  583. .Annotation<SiblingsReverseDocumentOrderInfo>()
  584. .PreviousSibling;
  585. if (previousElement == null)
  586. yield break;
  587. yield return previousElement;
  588. current = previousElement;
  589. }
  590. }
  591. private static void InitializeDescendantsReverseDocumentOrder(XElement element)
  592. {
  593. XElement prev = null;
  594. foreach (XElement e in element.Descendants())
  595. {
  596. e.AddAnnotation(new DescendantsReverseDocumentOrderInfo { PreviousElement = prev });
  597. prev = e;
  598. }
  599. }
  600. [SuppressMessage("ReSharper", "PossibleNullReferenceException")]
  601. public static IEnumerable<XElement> DescendantsBeforeSelfReverseDocumentOrder(
  602. this XElement element)
  603. {
  604. if (element.Annotation<DescendantsReverseDocumentOrderInfo>() == null)
  605. InitializeDescendantsReverseDocumentOrder(element.AncestorsAndSelf().Last());
  606. XElement current = element;
  607. while (true)
  608. {
  609. XElement previousElement = current
  610. .Annotation<DescendantsReverseDocumentOrderInfo>()
  611. .PreviousElement;
  612. if (previousElement == null)
  613. yield break;
  614. yield return previousElement;
  615. current = previousElement;
  616. }
  617. }
  618. private static void InitializeDescendantsTrimmedReverseDocumentOrder(XElement element, XName trimName)
  619. {
  620. XElement prev = null;
  621. foreach (XElement e in element.DescendantsTrimmed(trimName))
  622. {
  623. e.AddAnnotation(new DescendantsTrimmedReverseDocumentOrderInfo { PreviousElement = prev });
  624. prev = e;
  625. }
  626. }
  627. [SuppressMessage("ReSharper", "PossibleNullReferenceException")]
  628. public static IEnumerable<XElement> DescendantsTrimmedBeforeSelfReverseDocumentOrder(
  629. this XElement element, XName trimName)
  630. {
  631. if (element.Annotation<DescendantsTrimmedReverseDocumentOrderInfo>() == null)
  632. {
  633. XElement ances = element.AncestorsAndSelf(W.txbxContent).FirstOrDefault() ??
  634. element.AncestorsAndSelf().Last();
  635. InitializeDescendantsTrimmedReverseDocumentOrder(ances, trimName);
  636. }
  637. XElement current = element;
  638. while (true)
  639. {
  640. XElement previousElement = current
  641. .Annotation<DescendantsTrimmedReverseDocumentOrderInfo>()
  642. .PreviousElement;
  643. if (previousElement == null)
  644. yield break;
  645. yield return previousElement;
  646. current = previousElement;
  647. }
  648. }
  649. public static string ToStringNewLineOnAttributes(this XElement element)
  650. {
  651. var settings = new XmlWriterSettings
  652. {
  653. Indent = true,
  654. OmitXmlDeclaration = true,
  655. NewLineOnAttributes = true
  656. };
  657. var stringBuilder = new StringBuilder();
  658. using (var stringWriter = new StringWriter(stringBuilder))
  659. using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
  660. element.WriteTo(xmlWriter);
  661. return stringBuilder.ToString();
  662. }
  663. public static IEnumerable<XElement> DescendantsTrimmed(this XElement element,
  664. XName trimName)
  665. {
  666. return DescendantsTrimmed(element, e => e.Name == trimName);
  667. }
  668. public static IEnumerable<XElement> DescendantsTrimmed(this XElement element,
  669. Func<XElement, bool> predicate)
  670. {
  671. Stack<IEnumerator<XElement>> iteratorStack = new Stack<IEnumerator<XElement>>();
  672. iteratorStack.Push(element.Elements().GetEnumerator());
  673. while (iteratorStack.Count > 0)
  674. {
  675. while (iteratorStack.Peek().MoveNext())
  676. {
  677. XElement currentXElement = iteratorStack.Peek().Current;
  678. if (predicate(currentXElement))
  679. {
  680. yield return currentXElement;
  681. continue;
  682. }
  683. yield return currentXElement;
  684. iteratorStack.Push(currentXElement.Elements().GetEnumerator());
  685. }
  686. iteratorStack.Pop();
  687. }
  688. }
  689. public static IEnumerable<TResult> Rollup<TSource, TResult>(
  690. this IEnumerable<TSource> source,
  691. TResult seed,
  692. Func<TSource, TResult, TResult> projection)
  693. {
  694. TResult nextSeed = seed;
  695. foreach (TSource src in source)
  696. {
  697. TResult projectedValue = projection(src, nextSeed);
  698. nextSeed = projectedValue;
  699. yield return projectedValue;
  700. }
  701. }
  702. public static IEnumerable<TResult> Rollup<TSource, TResult>(
  703. this IEnumerable<TSource> source,
  704. TResult seed,
  705. Func<TSource, TResult, int, TResult> projection)
  706. {
  707. TResult nextSeed = seed;
  708. int index = 0;
  709. foreach (TSource src in source)
  710. {
  711. TResult projectedValue = projection(src, nextSeed, index++);
  712. nextSeed = projectedValue;
  713. yield return projectedValue;
  714. }
  715. }
  716. public static IEnumerable<TSource> SequenceAt<TSource>(this TSource[] source, int index)
  717. {
  718. int i = index;
  719. while (i < source.Length)
  720. yield return source[i++];
  721. }
  722. public static IEnumerable<T> PtSkipLast<T>(this IEnumerable<T> source, int count)
  723. {
  724. var saveList = new Queue<T>();
  725. var saved = 0;
  726. foreach (T item in source)
  727. {
  728. if (saved < count)
  729. {
  730. saveList.Enqueue(item);
  731. ++saved;
  732. continue;
  733. }
  734. saveList.Enqueue(item);
  735. yield return saveList.Dequeue();
  736. }
  737. }
  738. public static bool? ToBoolean(this XAttribute a)
  739. {
  740. if (a == null)
  741. return null;
  742. string s = ((string) a).ToLower();
  743. switch (s)
  744. {
  745. case "1":
  746. return true;
  747. case "0":
  748. return false;
  749. case "true":
  750. return true;
  751. case "false":
  752. return false;
  753. case "on":
  754. return true;
  755. case "off":
  756. return false;
  757. default:
  758. return (bool) a;
  759. }
  760. }
  761. private static string GetQName(XElement xe)
  762. {
  763. string prefix = xe.GetPrefixOfNamespace(xe.Name.Namespace);
  764. if (xe.Name.Namespace == XNamespace.None || prefix == null)
  765. return xe.Name.LocalName;
  766. return prefix + ":" + xe.Name.LocalName;
  767. }
  768. private static string GetQName(XAttribute xa)
  769. {
  770. string prefix = xa.Parent != null ? xa.Parent.GetPrefixOfNamespace(xa.Name.Namespace) : null;
  771. if (xa.Name.Namespace == XNamespace.None || prefix == null)
  772. return xa.Name.ToString();
  773. return prefix + ":" + xa.Name.LocalName;
  774. }
  775. private static string NameWithPredicate(XElement el)
  776. {
  777. if (el.Parent != null && el.Parent.Elements(el.Name).Count() != 1)
  778. return GetQName(el) + "[" +
  779. (el.ElementsBeforeSelf(el.Name).Count() + 1) + "]";
  780. else
  781. return GetQName(el);
  782. }
  783. public static string StrCat<T>(this IEnumerable<T> source,
  784. string separator)
  785. {
  786. return source.Aggregate(new StringBuilder(),
  787. (sb, i) => sb
  788. .Append(i.ToString())
  789. .Append(separator),
  790. s => s.ToString());
  791. }
  792. public static string GetXPath(this XObject xobj)
  793. {
  794. if (xobj.Parent == null)
  795. {
  796. var doc = xobj as XDocument;
  797. if (doc != null)
  798. return ".";
  799. var el = xobj as XElement;
  800. if (el != null)
  801. return "/" + NameWithPredicate(el);
  802. var xt = xobj as XText;
  803. if (xt != null)
  804. return null;
  805. //
  806. //the following doesn't work because the XPath data
  807. //model doesn't include white space text nodes that
  808. //are children of the document.
  809. //
  810. //return
  811. // "/" +
  812. // (
  813. // xt
  814. // .Document
  815. // .Nodes()
  816. // .OfType<XText>()
  817. // .Count() != 1 ?
  818. // "text()[" +
  819. // (xt
  820. // .NodesBeforeSelf()
  821. // .OfType<XText>()
  822. // .Count() + 1) + "]" :
  823. // "text()"
  824. // );
  825. //
  826. var com = xobj as XComment;
  827. if (com != null && com.Document != null)
  828. return
  829. "/" +
  830. (
  831. com
  832. .Document
  833. .Nodes()
  834. .OfType<XComment>()
  835. .Count() != 1
  836. ? "comment()[" +
  837. (com
  838. .NodesBeforeSelf()
  839. .OfType<XComment>()
  840. .Count() + 1) +
  841. "]"
  842. : "comment()"
  843. );
  844. var pi = xobj as XProcessingInstruction;
  845. if (pi != null)
  846. return
  847. "/" +
  848. (
  849. pi.Document != null && pi.Document.Nodes().OfType<XProcessingInstruction>().Count() != 1
  850. ? "processing-instruction()[" +
  851. (pi
  852. .NodesBeforeSelf()
  853. .OfType<XProcessingInstruction>()
  854. .Count() + 1) +
  855. "]"
  856. : "processing-instruction()"
  857. );
  858. return null;
  859. }
  860. else
  861. {
  862. var el = xobj as XElement;
  863. if (el != null)
  864. {
  865. return
  866. "/" +
  867. el
  868. .Ancestors()
  869. .InDocumentOrder()
  870. .Select(e => NameWithPredicate(e))
  871. .StrCat("/") +
  872. NameWithPredicate(el);
  873. }
  874. var at = xobj as XAttribute;
  875. if (at != null && at.Parent != null)
  876. return
  877. "/" +
  878. at
  879. .Parent
  880. .AncestorsAndSelf()
  881. .InDocumentOrder()
  882. .Select(e => NameWithPredicate(e))
  883. .StrCat("/") +
  884. "@" + GetQName(at);
  885. var com = xobj as XComment;
  886. if (com != null && com.Parent != null)
  887. return
  888. "/" +
  889. com
  890. .Parent
  891. .AncestorsAndSelf()
  892. .InDocumentOrder()
  893. .Select(e => NameWithPredicate(e))
  894. .StrCat("/") +
  895. (
  896. com
  897. .Parent
  898. .Nodes()
  899. .OfType<XComment>()
  900. .Count() != 1
  901. ? "comment()[" +
  902. (com
  903. .NodesBeforeSelf()
  904. .OfType<XComment>()
  905. .Count() + 1) + "]"
  906. : "comment()"
  907. );
  908. var cd = xobj as XCData;
  909. if (cd != null && cd.Parent != null)
  910. return
  911. "/" +
  912. cd
  913. .Parent
  914. .AncestorsAndSelf()
  915. .InDocumentOrder()
  916. .Select(e => NameWithPredicate(e))
  917. .StrCat("/") +
  918. (
  919. cd
  920. .Parent
  921. .Nodes()
  922. .OfType<XText>()
  923. .Count() != 1
  924. ? "text()[" +
  925. (cd
  926. .NodesBeforeSelf()
  927. .OfType<XText>()
  928. .Count() + 1) + "]"
  929. : "text()"
  930. );
  931. var tx = xobj as XText;
  932. if (tx != null && tx.Parent != null)
  933. return
  934. "/" +
  935. tx
  936. .Parent
  937. .AncestorsAndSelf()
  938. .InDocumentOrder()
  939. .Select(e => NameWithPredicate(e))
  940. .StrCat("/") +
  941. (
  942. tx
  943. .Parent
  944. .Nodes()
  945. .OfType<XText>()
  946. .Count() != 1
  947. ? "text()[" +
  948. (tx
  949. .NodesBeforeSelf()
  950. .OfType<XText>()
  951. .Count() + 1) + "]"
  952. : "text()"
  953. );
  954. var pi = xobj as XProcessingInstruction;
  955. if (pi != null && pi.Parent != null)
  956. return
  957. "/" +
  958. pi
  959. .Parent
  960. .AncestorsAndSelf()
  961. .InDocumentOrder()
  962. .Select(e => NameWithPredicate(e))
  963. .StrCat("/") +
  964. (
  965. pi
  966. .Parent
  967. .Nodes()
  968. .OfType<XProcessingInstruction>()
  969. .Count() != 1
  970. ? "processing-instruction()[" +
  971. (pi
  972. .NodesBeforeSelf()
  973. .OfType<XProcessingInstruction>()
  974. .Count() + 1) + "]"
  975. : "processing-instruction()"
  976. );
  977. return null;
  978. }
  979. }
  980. /// <summary>
  981. /// Gets or creates the given container's first child element having the given
  982. /// <see cref="XName"/>.
  983. /// </summary>
  984. /// <param name="container">The container <see cref="XElement"/>.</param>
  985. /// <param name="childName">The child element's <see cref="XName"/>.</param>
  986. /// <returns>The container's first child <see cref="XElement"/>.</returns>
  987. public static XElement GetOrCreateFirstChild(this XElement container, XName childName)
  988. {
  989. if (container == null) throw new ArgumentNullException(nameof(container));
  990. if (childName == null) throw new ArgumentNullException(nameof(childName));
  991. XElement child = container.Element(childName);
  992. if (child == null)
  993. {
  994. child = new XElement(childName);
  995. container.AddFirst(child);
  996. }
  997. return child;
  998. }
  999. /// <summary>
  1000. /// Gets the given element's parent element or throws an <see cref="ArgumentException"/>
  1001. /// in case the element does not have a parent.
  1002. /// </summary>
  1003. /// <param name="element">The element.</param>
  1004. /// <returns>The element's parent.</returns>
  1005. public static XElement GetParent(this XElement element)
  1006. {
  1007. if (element == null) throw new ArgumentNullException(nameof(element));
  1008. return element.Parent ?? throw new ArgumentException("Element does not have a parent.");
  1009. }
  1010. /// <summary>
  1011. /// Moves the given element to a new parent.
  1012. /// </summary>
  1013. /// <param name="element">The element.</param>
  1014. /// <param name="parent">The new parent.</param>
  1015. public static void MoveTo(this XElement element, XElement parent)
  1016. {
  1017. if (element == null) throw new ArgumentNullException(nameof(element));
  1018. if (parent == null) throw new ArgumentNullException(nameof(parent));
  1019. element.Remove();
  1020. parent.Add(element);
  1021. }
  1022. }
  1023. public class ExecutableRunner
  1024. {
  1025. public class RunResults
  1026. {
  1027. public int ExitCode;
  1028. public Exception RunException;
  1029. public StringBuilder Output;
  1030. public StringBuilder Error;
  1031. }
  1032. public static RunResults RunExecutable(string executablePath, string arguments, string workingDirectory)
  1033. {
  1034. RunResults runResults = new RunResults
  1035. {
  1036. Output = new StringBuilder(),
  1037. Error = new StringBuilder(),
  1038. RunException = null
  1039. };
  1040. try
  1041. {
  1042. if (File.Exists(executablePath))
  1043. {
  1044. using (Process proc = new Process())
  1045. {
  1046. proc.StartInfo.FileName = executablePath;
  1047. proc.StartInfo.Arguments = arguments;
  1048. proc.StartInfo.WorkingDirectory = workingDirectory;
  1049. proc.StartInfo.UseShellExecute = false;
  1050. proc.StartInfo.RedirectStandardOutput = true;
  1051. proc.StartInfo.RedirectStandardError = true;
  1052. proc.OutputDataReceived +=
  1053. (o, e) => runResults.Output.Append(e.Data).Append(Environment.NewLine);
  1054. proc.ErrorDataReceived +=
  1055. (o, e) => runResults.Error.Append(e.Data).Append(Environment.NewLine);
  1056. proc.Start();
  1057. proc.BeginOutputReadLine();
  1058. proc.BeginErrorReadLine();
  1059. proc.WaitForExit();
  1060. runResults.ExitCode = proc.ExitCode;
  1061. }
  1062. }
  1063. else
  1064. {
  1065. throw new ArgumentException("Invalid executable path.", "executablePath");
  1066. }
  1067. }
  1068. catch (Exception e)
  1069. {
  1070. runResults.RunException = e;
  1071. }
  1072. return runResults;
  1073. }
  1074. }
  1075. public class SiblingsReverseDocumentOrderInfo
  1076. {
  1077. public XElement PreviousSibling;
  1078. }
  1079. public class DescendantsReverseDocumentOrderInfo
  1080. {
  1081. public XElement PreviousElement;
  1082. }
  1083. public class DescendantsTrimmedReverseDocumentOrderInfo
  1084. {
  1085. public XElement PreviousElement;
  1086. }
  1087. public class GroupOfAdjacent<TSource, TKey> : IGrouping<TKey, TSource>
  1088. {
  1089. public GroupOfAdjacent(List<TSource> source, TKey key)
  1090. {
  1091. GroupList = source;
  1092. Key = key;
  1093. }
  1094. public TKey Key { get; set; }
  1095. private List<TSource> GroupList { get; set; }
  1096. IEnumerator IEnumerable.GetEnumerator()
  1097. {
  1098. return ((IEnumerable<TSource>) this).GetEnumerator();
  1099. }
  1100. IEnumerator<TSource> IEnumerable<TSource>.GetEnumerator()
  1101. {
  1102. return ((IEnumerable<TSource>) GroupList).GetEnumerator();
  1103. }
  1104. }
  1105. public class BucketTimer
  1106. {
  1107. public BucketTimer()
  1108. {
  1109. Buckets = new Dictionary<string, BucketInfo>();
  1110. }
  1111. private class BucketInfo
  1112. {
  1113. public int Count;
  1114. public TimeSpan Time;
  1115. }
  1116. private string LastBucket = null;
  1117. private DateTime LastTime;
  1118. private Dictionary<string, BucketInfo> Buckets;
  1119. public void Bucket(string bucket)
  1120. {
  1121. DateTime now = DateTime.Now;
  1122. if (LastBucket != null)
  1123. AddToBuckets(now);
  1124. LastBucket = bucket;
  1125. LastTime = now;
  1126. }
  1127. public void End()
  1128. {
  1129. DateTime now = DateTime.Now;
  1130. if (LastBucket != null)
  1131. AddToBuckets(now);
  1132. LastBucket = null;
  1133. }
  1134. private void AddToBuckets(DateTime now)
  1135. {
  1136. TimeSpan d = now - LastTime;
  1137. var bucketParts = LastBucket.Split('/');
  1138. var bucketList = bucketParts.Select((t, i) => bucketParts
  1139. .Take(i + 1)
  1140. .Select(z => z + "/")
  1141. .StringConcatenate()
  1142. .Trim('/'))
  1143. .ToList();
  1144. foreach (var b in bucketList)
  1145. {
  1146. if (Buckets.ContainsKey(b))
  1147. {
  1148. Buckets[b].Count = Buckets[b].Count + 1;
  1149. Buckets[b].Time += d;
  1150. }
  1151. else
  1152. {
  1153. Buckets.Add(b, new BucketInfo()
  1154. {
  1155. Count = 1,
  1156. Time = d,
  1157. });
  1158. }
  1159. }
  1160. LastTime = now;
  1161. }
  1162. public string DumpBucketsByKey()
  1163. {
  1164. StringBuilder sb = new StringBuilder();
  1165. foreach (var bucket in Buckets.OrderBy(b => b.Key))
  1166. {
  1167. string ts = bucket.Value.Time.ToString();
  1168. if (ts.Contains('.'))
  1169. ts = ts.Substring(0, ts.Length - 5);
  1170. string s = bucket.Key.PadRight(60, '-') + " " + string.Format("{0:00000000}", bucket.Value.Count) + " " + ts;
  1171. sb.Append(s + Environment.NewLine);
  1172. }
  1173. TimeSpan total = Buckets
  1174. .Aggregate(TimeSpan.Zero, (t, b) => t + b.Value.Time);
  1175. var tz = total.ToString();
  1176. sb.Append(string.Format("Total: {0}", tz.Substring(0, tz.Length - 5)));
  1177. return sb.ToString();
  1178. }
  1179. public string DumpBucketsToCsvByKey()
  1180. {
  1181. StringBuilder sb = new StringBuilder();
  1182. foreach (var bucket in Buckets.OrderBy(b => b.Key))
  1183. {
  1184. string ts = bucket.Value.Time.ToString();
  1185. if (ts.Contains('.'))
  1186. ts = ts.Substring(0, ts.Length - 5);
  1187. string s = bucket.Key + "," + bucket.Value.Count.ToString() + "," + ts;
  1188. sb.Append(s + Environment.NewLine);
  1189. }
  1190. return sb.ToString();
  1191. }
  1192. public string DumpBucketsByTime()
  1193. {
  1194. StringBuilder sb = new StringBuilder();
  1195. foreach (var bucket in Buckets.OrderBy(b => b.Value.Time))
  1196. {
  1197. string ts = bucket.Value.Time.ToString();
  1198. if (ts.Contains('.'))
  1199. ts = ts.Substring(0, ts.Length - 5);
  1200. string s = bucket.Key.PadRight(60, '-') + " " + string.Format("{0:00000000}", bucket.Value.Count) + " " + ts;
  1201. sb.Append(s + Environment.NewLine);
  1202. }
  1203. TimeSpan total = Buckets
  1204. .Aggregate(TimeSpan.Zero, (t, b) => t + b.Value.Time);
  1205. var tz = total.ToString();
  1206. sb.Append(string.Format("Total: {0}", tz.Substring(0, tz.Length - 5)));
  1207. return sb.ToString();
  1208. }
  1209. public void Init()
  1210. {
  1211. Buckets = new Dictionary<string, BucketInfo>();
  1212. }
  1213. }
  1214. public static class PtBucketTimer
  1215. {
  1216. private class BucketInfo
  1217. {
  1218. public int Count;
  1219. public TimeSpan Time;
  1220. }
  1221. public static string LastBucket = null;
  1222. private static DateTime LastTime;
  1223. private static Dictionary<string, BucketInfo> Buckets;
  1224. public static void Bucket(string bucket)
  1225. {
  1226. DateTime now = DateTime.Now;
  1227. if (LastBucket != null)
  1228. AddToBuckets(now);
  1229. LastBucket = bucket;
  1230. LastTime = now;
  1231. }
  1232. public static void End()
  1233. {
  1234. DateTime now = DateTime.Now;
  1235. if (LastBucket != null)
  1236. AddToBuckets(now);
  1237. LastBucket = null;
  1238. }
  1239. private static void AddToBuckets(DateTime now)
  1240. {
  1241. TimeSpan d = now - LastTime;
  1242. if (Buckets.ContainsKey(LastBucket))
  1243. {
  1244. Buckets[LastBucket].Count += 1;
  1245. Buckets[LastBucket].Time += d;
  1246. }
  1247. else
  1248. {
  1249. Buckets.Add(LastBucket, new BucketInfo()
  1250. {
  1251. Count = 1,
  1252. Time = d,
  1253. });
  1254. }
  1255. LastTime = now;
  1256. }
  1257. public static string DumpBucketsByKey()
  1258. {
  1259. StringBuilder sb = new StringBuilder();
  1260. foreach (var bucket in Buckets.OrderBy(b => b.Key))
  1261. {
  1262. string ts = bucket.Value.Time.ToString();
  1263. if (ts.Contains('.'))
  1264. ts = ts.Substring(0, ts.Length - 5);
  1265. string s = bucket.Key.PadRight(80, '-') + " " + string.Format("{0:00000000}", bucket.Value.Count) + " " + ts;
  1266. sb.Append(s + Environment.NewLine);
  1267. }
  1268. TimeSpan total = Buckets
  1269. .Aggregate(TimeSpan.Zero, (t, b) => t + b.Value.Time);
  1270. var tz = total.ToString();
  1271. sb.Append(string.Format("Total: {0}", tz.Substring(0, tz.Length - 5)));
  1272. return sb.ToString();
  1273. }
  1274. public static string DumpBucketsToCsvByKey()
  1275. {
  1276. StringBuilder sb = new StringBuilder();
  1277. foreach (var bucket in Buckets.OrderBy(b => b.Key))
  1278. {
  1279. string ts = bucket.Value.Time.TotalMilliseconds.ToString();
  1280. if (ts.Contains('.'))
  1281. ts = ts.Substring(0, ts.Length - 5);
  1282. string s = bucket.Key + "," + bucket.Value.Count.ToString() + "," + ts;
  1283. sb.Append(s + Environment.NewLine);
  1284. }
  1285. return sb.ToString();
  1286. }
  1287. public static string DumpBucketsByTime()
  1288. {
  1289. StringBuilder sb = new StringBuilder();
  1290. foreach (var bucket in Buckets.OrderBy(b => b.Value.Time))
  1291. {
  1292. string ts = bucket.Value.Time.ToString();
  1293. if (ts.Contains('.'))
  1294. ts = ts.Substring(0, ts.Length - 5);
  1295. string s = bucket.Key.PadRight(80, '-') + " " + string.Format("{0:00000000}", bucket.Value.Count) + " " + ts;
  1296. sb.Append(s + Environment.NewLine);
  1297. }
  1298. TimeSpan total = Buckets
  1299. .Aggregate(TimeSpan.Zero, (t, b) => t + b.Value.Time);
  1300. var tz = total.ToString();
  1301. sb.Append(string.Format("Total: {0}", tz.Substring(0, tz.Length - 5)));
  1302. return sb.ToString();
  1303. }
  1304. public static void Init()
  1305. {
  1306. LastBucket = null;
  1307. Buckets = new Dictionary<string, BucketInfo>();
  1308. }
  1309. }
  1310. public class XEntity : XText
  1311. {
  1312. public override void WriteTo(XmlWriter writer)
  1313. {
  1314. if (Value.Substring(0, 1) == "#")
  1315. {
  1316. string e = string.Format("&{0};", Value);
  1317. writer.WriteRaw(e);
  1318. }
  1319. else
  1320. writer.WriteEntityRef(Value);
  1321. }
  1322. public XEntity(string value) : base(value)
  1323. {
  1324. }
  1325. }
  1326. }