1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462 |
- // Copyright (c) Microsoft. All rights reserved.
- // Licensed under the MIT license. See LICENSE file in the project root for full license information.
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.CodeAnalysis;
- using System.IO;
- using System.Linq;
- using System.Security.Cryptography;
- using System.Text;
- using System.Threading.Tasks;
- using System.Xml;
- using System.Xml.Linq;
- using System.Xml.Schema;
- namespace OpenXmlPowerTools
- {
- public static class PtUtils
- {
- public static string SHA1HashStringForUTF8String(string s)
- {
- byte[] bytes = Encoding.UTF8.GetBytes(s);
- var sha1 = SHA1.Create();
- byte[] hashBytes = sha1.ComputeHash(bytes);
- return HexStringFromBytes(hashBytes);
- }
- public static string SHA1HashStringForByteArray(byte[] bytes)
- {
- var sha1 = SHA1.Create();
- byte[] hashBytes = sha1.ComputeHash(bytes);
- return HexStringFromBytes(hashBytes);
- }
- public static string HexStringFromBytes(byte[] bytes)
- {
- var sb = new StringBuilder();
- foreach (byte b in bytes)
- {
- var hex = b.ToString("x2");
- sb.Append(hex);
- }
- return sb.ToString();
- }
- public static string NormalizeDirName(string dirName)
- {
- string d = dirName.Replace('\\', '/');
- if (d[dirName.Length - 1] != '/' && d[dirName.Length - 1] != '\\')
- return d + "/";
- return d;
- }
- public static string MakeValidXml(string p)
- {
- return p.Any(c => c < 0x20)
- ? p.Select(c => c < 0x20 ? string.Format("_{0:X}_", (int) c) : c.ToString()).StringConcatenate()
- : p;
- }
- public static void AddElementIfMissing(XDocument partXDoc, XElement existing, string newElement)
- {
- if (existing != null)
- return;
- XElement newXElement = XElement.Parse(newElement);
- newXElement.Attributes().Where(a => a.IsNamespaceDeclaration).Remove();
- if (partXDoc.Root != null) partXDoc.Root.Add(newXElement);
- }
- }
- public class MhtParser
- {
- public string MimeVersion;
- public string ContentType;
- public MhtParserPart[] Parts;
- public class MhtParserPart
- {
- public string ContentLocation;
- public string ContentTransferEncoding;
- public string ContentType;
- public string CharSet;
- public string Text;
- public byte[] Binary;
- }
- public static MhtParser Parse(string src)
- {
- string mimeVersion = null;
- string contentType = null;
- string boundary = null;
- string[] lines = src.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
- var priambleKeyWords = new[]
- {
- "MIME-VERSION:",
- "CONTENT-TYPE:",
- };
- var priamble = lines.TakeWhile(l =>
- {
- var s = l.ToUpper();
- return priambleKeyWords.Any(pk => s.StartsWith(pk));
- }).ToArray();
- foreach (var item in priamble)
- {
- if (item.ToUpper().StartsWith("MIME-VERSION:"))
- mimeVersion = item.Substring("MIME-VERSION:".Length).Trim();
- else if (item.ToUpper().StartsWith("CONTENT-TYPE:"))
- {
- var contentTypeLine = item.Substring("CONTENT-TYPE:".Length).Trim();
- var spl = contentTypeLine.Split(';').Select(z => z.Trim()).ToArray();
- foreach (var s in spl)
- {
- if (s.StartsWith("boundary"))
- {
- var begText = "boundary=\"";
- var begLen = begText.Length;
- boundary = s.Substring(begLen, s.Length - begLen - 1).TrimStart('-');
- continue;
- }
- if (contentType == null)
- {
- contentType = s;
- continue;
- }
- throw new OpenXmlPowerToolsException("Unexpected content in MHTML");
- }
- }
- }
- var grouped = lines
- .Skip(priamble.Length)
- .GroupAdjacent(l =>
- {
- var b = l.TrimStart('-') == boundary;
- return b;
- })
- .Where(g => g.Key == false)
- .ToArray();
- var parts = grouped.Select(rp =>
- {
- var partPriambleKeyWords = new[]
- {
- "CONTENT-LOCATION:",
- "CONTENT-TRANSFER-ENCODING:",
- "CONTENT-TYPE:",
- };
- var partPriamble = rp.TakeWhile(l =>
- {
- var s = l.ToUpper();
- return partPriambleKeyWords.Any(pk => s.StartsWith(pk));
- }).ToArray();
- string contentLocation = null;
- string contentTransferEncoding = null;
- string partContentType = null;
- string partCharSet = null;
- byte[] partBinary = null;
- foreach (var item in partPriamble)
- {
- if (item.ToUpper().StartsWith("CONTENT-LOCATION:"))
- contentLocation = item.Substring("CONTENT-LOCATION:".Length).Trim();
- else if (item.ToUpper().StartsWith("CONTENT-TRANSFER-ENCODING:"))
- contentTransferEncoding = item.Substring("CONTENT-TRANSFER-ENCODING:".Length).Trim();
- else if (item.ToUpper().StartsWith("CONTENT-TYPE:"))
- partContentType = item.Substring("CONTENT-TYPE:".Length).Trim();
- }
- var blankLinesAtBeginning = rp
- .Skip(partPriamble.Length)
- .TakeWhile(l => l == "")
- .Count();
- var partText = rp
- .Skip(partPriamble.Length)
- .Skip(blankLinesAtBeginning)
- .Select(l => l + Environment.NewLine)
- .StringConcatenate();
- if (partContentType != null && partContentType.Contains(";"))
- {
- string thisPartContentType = null;
- var spl = partContentType.Split(';').Select(s => s.Trim()).ToArray();
- foreach (var s in spl)
- {
- if (s.StartsWith("charset"))
- {
- var begText = "charset=\"";
- var begLen = begText.Length;
- partCharSet = s.Substring(begLen, s.Length - begLen - 1);
- continue;
- }
- if (thisPartContentType == null)
- {
- thisPartContentType = s;
- continue;
- }
- throw new OpenXmlPowerToolsException("Unexpected content in MHTML");
- }
- partContentType = thisPartContentType;
- }
- if (contentTransferEncoding != null && contentTransferEncoding.ToUpper() == "BASE64")
- {
- partBinary = Convert.FromBase64String(partText);
- }
- return new MhtParserPart()
- {
- ContentLocation = contentLocation,
- ContentTransferEncoding = contentTransferEncoding,
- ContentType = partContentType,
- CharSet = partCharSet,
- Text = partText,
- Binary = partBinary,
- };
- })
- .Where(p => p.ContentType != null)
- .ToArray();
- return new MhtParser()
- {
- ContentType = contentType,
- MimeVersion = mimeVersion,
- Parts = parts,
- };
- }
- }
- public class Normalizer
- {
- public static XDocument Normalize(XDocument source, XmlSchemaSet schema)
- {
- bool havePSVI = false;
- // validate, throw errors, add PSVI information
- if (schema != null)
- {
- source.Validate(schema, null, true);
- havePSVI = true;
- }
- return new XDocument(
- source.Declaration,
- source.Nodes().Select(n =>
- {
- // Remove comments, processing instructions, and text nodes that are
- // children of XDocument. Only white space text nodes are allowed as
- // children of a document, so we can remove all text nodes.
- if (n is XComment || n is XProcessingInstruction || n is XText)
- return null;
- XElement e = n as XElement;
- if (e != null)
- return NormalizeElement(e, havePSVI);
- return n;
- }
- )
- );
- }
- public static bool DeepEqualsWithNormalization(XDocument doc1, XDocument doc2,
- XmlSchemaSet schemaSet)
- {
- XDocument d1 = Normalize(doc1, schemaSet);
- XDocument d2 = Normalize(doc2, schemaSet);
- return XNode.DeepEquals(d1, d2);
- }
- private static IEnumerable<XAttribute> NormalizeAttributes(XElement element,
- bool havePSVI)
- {
- return element.Attributes()
- .Where(a => !a.IsNamespaceDeclaration &&
- a.Name != XSI.schemaLocation &&
- a.Name != XSI.noNamespaceSchemaLocation)
- .OrderBy(a => a.Name.NamespaceName)
- .ThenBy(a => a.Name.LocalName)
- .Select(
- a =>
- {
- if (havePSVI)
- {
- var dt = a.GetSchemaInfo().SchemaType.TypeCode;
- switch (dt)
- {
- case XmlTypeCode.Boolean:
- return new XAttribute(a.Name, (bool)a);
- case XmlTypeCode.DateTime:
- return new XAttribute(a.Name, (DateTime)a);
- case XmlTypeCode.Decimal:
- return new XAttribute(a.Name, (decimal)a);
- case XmlTypeCode.Double:
- return new XAttribute(a.Name, (double)a);
- case XmlTypeCode.Float:
- return new XAttribute(a.Name, (float)a);
- case XmlTypeCode.HexBinary:
- case XmlTypeCode.Language:
- return new XAttribute(a.Name,
- ((string)a).ToLower());
- }
- }
- return a;
- }
- );
- }
- private static XNode NormalizeNode(XNode node, bool havePSVI)
- {
- // trim comments and processing instructions from normalized tree
- if (node is XComment || node is XProcessingInstruction)
- return null;
- XElement e = node as XElement;
- if (e != null)
- return NormalizeElement(e, havePSVI);
- // Only thing left is XCData and XText, so clone them
- return node;
- }
- private static XElement NormalizeElement(XElement element, bool havePSVI)
- {
- if (havePSVI)
- {
- var dt = element.GetSchemaInfo();
- switch (dt.SchemaType.TypeCode)
- {
- case XmlTypeCode.Boolean:
- return new XElement(element.Name,
- NormalizeAttributes(element, havePSVI),
- (bool)element);
- case XmlTypeCode.DateTime:
- return new XElement(element.Name,
- NormalizeAttributes(element, havePSVI),
- (DateTime)element);
- case XmlTypeCode.Decimal:
- return new XElement(element.Name,
- NormalizeAttributes(element, havePSVI),
- (decimal)element);
- case XmlTypeCode.Double:
- return new XElement(element.Name,
- NormalizeAttributes(element, havePSVI),
- (double)element);
- case XmlTypeCode.Float:
- return new XElement(element.Name,
- NormalizeAttributes(element, havePSVI),
- (float)element);
- case XmlTypeCode.HexBinary:
- case XmlTypeCode.Language:
- return new XElement(element.Name,
- NormalizeAttributes(element, havePSVI),
- ((string)element).ToLower());
- default:
- return new XElement(element.Name,
- NormalizeAttributes(element, havePSVI),
- element.Nodes().Select(n => NormalizeNode(n, havePSVI))
- );
- }
- }
- else
- {
- return new XElement(element.Name,
- NormalizeAttributes(element, havePSVI),
- element.Nodes().Select(n => NormalizeNode(n, havePSVI))
- );
- }
- }
- }
- public class FileUtils
- {
- public static DirectoryInfo GetDateTimeStampedDirectoryInfo(string prefix)
- {
- DateTime now = DateTime.Now;
- string dirName =
- prefix +
- string.Format("-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", now.Year - 2000, now.Month, now.Day, now.Hour,
- now.Minute, now.Second);
- return new DirectoryInfo(dirName);
- }
- public static FileInfo GetDateTimeStampedFileInfo(string prefix, string suffix)
- {
- DateTime now = DateTime.Now;
- string fileName =
- prefix +
- string.Format("-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", now.Year - 2000, now.Month, now.Day, now.Hour,
- now.Minute, now.Second) +
- suffix;
- return new FileInfo(fileName);
- }
- public static void ThreadSafeCreateDirectory(DirectoryInfo dir)
- {
- while (true)
- {
- if (dir.Exists)
- break;
- try
- {
- dir.Create();
- break;
- }
- catch (IOException)
- {
- Task.Delay (50);
- }
- }
- }
- public static void ThreadSafeCopy(FileInfo sourceFile, FileInfo destFile)
- {
- while (true)
- {
- if (destFile.Exists)
- break;
- try
- {
- File.Copy(sourceFile.FullName, destFile.FullName);
- break;
- }
- catch (IOException)
- {
- Task.Delay(50);
- }
- }
- }
- public static void ThreadSafeCreateEmptyTextFileIfNotExist(FileInfo file)
- {
- while (true)
- {
- if (file.Exists)
- break;
- try
- {
- File.WriteAllText(file.FullName, "");
- break;
- }
- catch (IOException)
- {
- Task.Delay(50);
- }
- }
- }
- #if !NET35
- internal static void ThreadSafeAppendAllLines(FileInfo file, string[] strings)
- {
- while (true)
- {
- try
- {
- File.AppendAllLines(file.FullName, strings);
- break;
- }
- catch (IOException)
- {
- Task.Delay(50);
- }
- }
- }
- #endif
- public static List<string> GetFilesRecursive(DirectoryInfo dir, string searchPattern)
- {
- var fileList = new List<string>();
- GetFilesRecursiveInternal(dir, searchPattern, fileList);
- return fileList;
- }
- private static void GetFilesRecursiveInternal(DirectoryInfo dir, string searchPattern, List<string> fileList)
- {
- fileList.AddRange(dir.GetFiles(searchPattern).Select(file => file.FullName));
- foreach (DirectoryInfo subdir in dir.GetDirectories())
- GetFilesRecursiveInternal(subdir, searchPattern, fileList);
- }
- public static List<string> GetFilesRecursive(DirectoryInfo dir)
- {
- var fileList = new List<string>();
- GetFilesRecursiveInternal(dir, fileList);
- return fileList;
- }
- private static void GetFilesRecursiveInternal(DirectoryInfo dir, List<string> fileList)
- {
- fileList.AddRange(dir.GetFiles().Select(file => file.FullName));
- foreach (DirectoryInfo subdir in dir.GetDirectories())
- GetFilesRecursiveInternal(subdir, fileList);
- }
- public static void CopyStream(Stream source, Stream target)
- {
- const int bufSize = 0x4096;
- var buf = new byte[bufSize];
- int bytesRead;
- while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
- target.Write(buf, 0, bytesRead);
- }
- }
- public static class PtExtensions
- {
- public static XElement GetXElement(this XmlNode node)
- {
- var xDoc = new XDocument();
- using (XmlWriter xmlWriter = xDoc.CreateWriter())
- node.WriteTo(xmlWriter);
- return xDoc.Root;
- }
- public static XmlNode GetXmlNode(this XElement element)
- {
- var xmlDoc = new XmlDocument();
- using (XmlReader xmlReader = element.CreateReader())
- xmlDoc.Load(xmlReader);
- return xmlDoc;
- }
- public static XDocument GetXDocument(this XmlDocument document)
- {
- var xDoc = new XDocument();
- using (XmlWriter xmlWriter = xDoc.CreateWriter())
- document.WriteTo(xmlWriter);
- XmlDeclaration decl = document.ChildNodes.OfType<XmlDeclaration>().FirstOrDefault();
- if (decl != null)
- xDoc.Declaration = new XDeclaration(decl.Version, decl.Encoding, decl.Standalone);
- return xDoc;
- }
- public static XmlDocument GetXmlDocument(this XDocument document)
- {
- var xmlDoc = new XmlDocument();
- using (XmlReader xmlReader = document.CreateReader())
- {
- xmlDoc.Load(xmlReader);
- if (document.Declaration != null)
- {
- XmlDeclaration dec = xmlDoc.CreateXmlDeclaration(document.Declaration.Version,
- document.Declaration.Encoding, document.Declaration.Standalone);
- xmlDoc.InsertBefore(dec, xmlDoc.FirstChild);
- }
- }
- return xmlDoc;
- }
- public static string StringConcatenate(this IEnumerable<string> source)
- {
- return source.Aggregate(
- new StringBuilder(),
- (sb, s) => sb.Append(s),
- sb => sb.ToString());
- }
- public static string StringConcatenate<T>(this IEnumerable<T> source, Func<T, string> projectionFunc)
- {
- return source.Aggregate(
- new StringBuilder(),
- (sb, i) => sb.Append(projectionFunc(i)),
- sb => sb.ToString());
- }
- public static IEnumerable<TResult> PtZip<TFirst, TSecond, TResult>(
- this IEnumerable<TFirst> first,
- IEnumerable<TSecond> second,
- Func<TFirst, TSecond, TResult> func)
- {
- using (IEnumerator<TFirst> ie1 = first.GetEnumerator())
- using (IEnumerator<TSecond> ie2 = second.GetEnumerator())
- while (ie1.MoveNext() && ie2.MoveNext())
- yield return func(ie1.Current, ie2.Current);
- }
- public static IEnumerable<IGrouping<TKey, TSource>> GroupAdjacent<TSource, TKey>(
- this IEnumerable<TSource> source,
- Func<TSource, TKey> keySelector)
- {
- TKey last = default(TKey);
- var haveLast = false;
- var list = new List<TSource>();
- foreach (TSource s in source)
- {
- TKey k = keySelector(s);
- if (haveLast)
- {
- if (!k.Equals(last))
- {
- yield return new GroupOfAdjacent<TSource, TKey>(list, last);
- list = new List<TSource> { s };
- last = k;
- }
- else
- {
- list.Add(s);
- last = k;
- }
- }
- else
- {
- list.Add(s);
- last = k;
- haveLast = true;
- }
- }
- if (haveLast)
- yield return new GroupOfAdjacent<TSource, TKey>(list, last);
- }
- private static void InitializeSiblingsReverseDocumentOrder(XElement element)
- {
- XElement prev = null;
- foreach (XElement e in element.Elements())
- {
- e.AddAnnotation(new SiblingsReverseDocumentOrderInfo { PreviousSibling = prev });
- prev = e;
- }
- }
- [SuppressMessage("ReSharper", "PossibleNullReferenceException")]
- public static IEnumerable<XElement> SiblingsBeforeSelfReverseDocumentOrder(
- this XElement element)
- {
- if (element.Annotation<SiblingsReverseDocumentOrderInfo>() == null)
- InitializeSiblingsReverseDocumentOrder(element.Parent);
- XElement current = element;
- while (true)
- {
- XElement previousElement = current
- .Annotation<SiblingsReverseDocumentOrderInfo>()
- .PreviousSibling;
- if (previousElement == null)
- yield break;
- yield return previousElement;
- current = previousElement;
- }
- }
- private static void InitializeDescendantsReverseDocumentOrder(XElement element)
- {
- XElement prev = null;
- foreach (XElement e in element.Descendants())
- {
- e.AddAnnotation(new DescendantsReverseDocumentOrderInfo { PreviousElement = prev });
- prev = e;
- }
- }
- [SuppressMessage("ReSharper", "PossibleNullReferenceException")]
- public static IEnumerable<XElement> DescendantsBeforeSelfReverseDocumentOrder(
- this XElement element)
- {
- if (element.Annotation<DescendantsReverseDocumentOrderInfo>() == null)
- InitializeDescendantsReverseDocumentOrder(element.AncestorsAndSelf().Last());
- XElement current = element;
- while (true)
- {
- XElement previousElement = current
- .Annotation<DescendantsReverseDocumentOrderInfo>()
- .PreviousElement;
- if (previousElement == null)
- yield break;
- yield return previousElement;
- current = previousElement;
- }
- }
- private static void InitializeDescendantsTrimmedReverseDocumentOrder(XElement element, XName trimName)
- {
- XElement prev = null;
- foreach (XElement e in element.DescendantsTrimmed(trimName))
- {
- e.AddAnnotation(new DescendantsTrimmedReverseDocumentOrderInfo { PreviousElement = prev });
- prev = e;
- }
- }
- [SuppressMessage("ReSharper", "PossibleNullReferenceException")]
- public static IEnumerable<XElement> DescendantsTrimmedBeforeSelfReverseDocumentOrder(
- this XElement element, XName trimName)
- {
- if (element.Annotation<DescendantsTrimmedReverseDocumentOrderInfo>() == null)
- {
- XElement ances = element.AncestorsAndSelf(W.txbxContent).FirstOrDefault() ??
- element.AncestorsAndSelf().Last();
- InitializeDescendantsTrimmedReverseDocumentOrder(ances, trimName);
- }
- XElement current = element;
- while (true)
- {
- XElement previousElement = current
- .Annotation<DescendantsTrimmedReverseDocumentOrderInfo>()
- .PreviousElement;
- if (previousElement == null)
- yield break;
- yield return previousElement;
- current = previousElement;
- }
- }
- public static string ToStringNewLineOnAttributes(this XElement element)
- {
- var settings = new XmlWriterSettings
- {
- Indent = true,
- OmitXmlDeclaration = true,
- NewLineOnAttributes = true
- };
- var stringBuilder = new StringBuilder();
- using (var stringWriter = new StringWriter(stringBuilder))
- using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
- element.WriteTo(xmlWriter);
- return stringBuilder.ToString();
- }
- public static IEnumerable<XElement> DescendantsTrimmed(this XElement element,
- XName trimName)
- {
- return DescendantsTrimmed(element, e => e.Name == trimName);
- }
- public static IEnumerable<XElement> DescendantsTrimmed(this XElement element,
- Func<XElement, bool> predicate)
- {
- Stack<IEnumerator<XElement>> iteratorStack = new Stack<IEnumerator<XElement>>();
- iteratorStack.Push(element.Elements().GetEnumerator());
- while (iteratorStack.Count > 0)
- {
- while (iteratorStack.Peek().MoveNext())
- {
- XElement currentXElement = iteratorStack.Peek().Current;
- if (predicate(currentXElement))
- {
- yield return currentXElement;
- continue;
- }
- yield return currentXElement;
- iteratorStack.Push(currentXElement.Elements().GetEnumerator());
- }
- iteratorStack.Pop();
- }
- }
- public static IEnumerable<TResult> Rollup<TSource, TResult>(
- this IEnumerable<TSource> source,
- TResult seed,
- Func<TSource, TResult, TResult> projection)
- {
- TResult nextSeed = seed;
- foreach (TSource src in source)
- {
- TResult projectedValue = projection(src, nextSeed);
- nextSeed = projectedValue;
- yield return projectedValue;
- }
- }
- public static IEnumerable<TResult> Rollup<TSource, TResult>(
- this IEnumerable<TSource> source,
- TResult seed,
- Func<TSource, TResult, int, TResult> projection)
- {
- TResult nextSeed = seed;
- int index = 0;
- foreach (TSource src in source)
- {
- TResult projectedValue = projection(src, nextSeed, index++);
- nextSeed = projectedValue;
- yield return projectedValue;
- }
- }
- public static IEnumerable<TSource> SequenceAt<TSource>(this TSource[] source, int index)
- {
- int i = index;
- while (i < source.Length)
- yield return source[i++];
- }
- public static IEnumerable<T> PtSkipLast<T>(this IEnumerable<T> source, int count)
- {
- var saveList = new Queue<T>();
- var saved = 0;
- foreach (T item in source)
- {
- if (saved < count)
- {
- saveList.Enqueue(item);
- ++saved;
- continue;
- }
- saveList.Enqueue(item);
- yield return saveList.Dequeue();
- }
- }
- public static bool? ToBoolean(this XAttribute a)
- {
- if (a == null)
- return null;
- string s = ((string) a).ToLower();
- switch (s)
- {
- case "1":
- return true;
- case "0":
- return false;
- case "true":
- return true;
- case "false":
- return false;
- case "on":
- return true;
- case "off":
- return false;
- default:
- return (bool) a;
- }
- }
- private static string GetQName(XElement xe)
- {
- string prefix = xe.GetPrefixOfNamespace(xe.Name.Namespace);
- if (xe.Name.Namespace == XNamespace.None || prefix == null)
- return xe.Name.LocalName;
- return prefix + ":" + xe.Name.LocalName;
- }
- private static string GetQName(XAttribute xa)
- {
- string prefix = xa.Parent != null ? xa.Parent.GetPrefixOfNamespace(xa.Name.Namespace) : null;
- if (xa.Name.Namespace == XNamespace.None || prefix == null)
- return xa.Name.ToString();
- return prefix + ":" + xa.Name.LocalName;
- }
- private static string NameWithPredicate(XElement el)
- {
- if (el.Parent != null && el.Parent.Elements(el.Name).Count() != 1)
- return GetQName(el) + "[" +
- (el.ElementsBeforeSelf(el.Name).Count() + 1) + "]";
- else
- return GetQName(el);
- }
- public static string StrCat<T>(this IEnumerable<T> source,
- string separator)
- {
- return source.Aggregate(new StringBuilder(),
- (sb, i) => sb
- .Append(i.ToString())
- .Append(separator),
- s => s.ToString());
- }
- public static string GetXPath(this XObject xobj)
- {
- if (xobj.Parent == null)
- {
- var doc = xobj as XDocument;
- if (doc != null)
- return ".";
- var el = xobj as XElement;
- if (el != null)
- return "/" + NameWithPredicate(el);
- var xt = xobj as XText;
- if (xt != null)
- return null;
- //
- //the following doesn't work because the XPath data
- //model doesn't include white space text nodes that
- //are children of the document.
- //
- //return
- // "/" +
- // (
- // xt
- // .Document
- // .Nodes()
- // .OfType<XText>()
- // .Count() != 1 ?
- // "text()[" +
- // (xt
- // .NodesBeforeSelf()
- // .OfType<XText>()
- // .Count() + 1) + "]" :
- // "text()"
- // );
- //
- var com = xobj as XComment;
- if (com != null && com.Document != null)
- return
- "/" +
- (
- com
- .Document
- .Nodes()
- .OfType<XComment>()
- .Count() != 1
- ? "comment()[" +
- (com
- .NodesBeforeSelf()
- .OfType<XComment>()
- .Count() + 1) +
- "]"
- : "comment()"
- );
- var pi = xobj as XProcessingInstruction;
- if (pi != null)
- return
- "/" +
- (
- pi.Document != null && pi.Document.Nodes().OfType<XProcessingInstruction>().Count() != 1
- ? "processing-instruction()[" +
- (pi
- .NodesBeforeSelf()
- .OfType<XProcessingInstruction>()
- .Count() + 1) +
- "]"
- : "processing-instruction()"
- );
- return null;
- }
- else
- {
- var el = xobj as XElement;
- if (el != null)
- {
- return
- "/" +
- el
- .Ancestors()
- .InDocumentOrder()
- .Select(e => NameWithPredicate(e))
- .StrCat("/") +
- NameWithPredicate(el);
- }
- var at = xobj as XAttribute;
- if (at != null && at.Parent != null)
- return
- "/" +
- at
- .Parent
- .AncestorsAndSelf()
- .InDocumentOrder()
- .Select(e => NameWithPredicate(e))
- .StrCat("/") +
- "@" + GetQName(at);
- var com = xobj as XComment;
- if (com != null && com.Parent != null)
- return
- "/" +
- com
- .Parent
- .AncestorsAndSelf()
- .InDocumentOrder()
- .Select(e => NameWithPredicate(e))
- .StrCat("/") +
- (
- com
- .Parent
- .Nodes()
- .OfType<XComment>()
- .Count() != 1
- ? "comment()[" +
- (com
- .NodesBeforeSelf()
- .OfType<XComment>()
- .Count() + 1) + "]"
- : "comment()"
- );
- var cd = xobj as XCData;
- if (cd != null && cd.Parent != null)
- return
- "/" +
- cd
- .Parent
- .AncestorsAndSelf()
- .InDocumentOrder()
- .Select(e => NameWithPredicate(e))
- .StrCat("/") +
- (
- cd
- .Parent
- .Nodes()
- .OfType<XText>()
- .Count() != 1
- ? "text()[" +
- (cd
- .NodesBeforeSelf()
- .OfType<XText>()
- .Count() + 1) + "]"
- : "text()"
- );
- var tx = xobj as XText;
- if (tx != null && tx.Parent != null)
- return
- "/" +
- tx
- .Parent
- .AncestorsAndSelf()
- .InDocumentOrder()
- .Select(e => NameWithPredicate(e))
- .StrCat("/") +
- (
- tx
- .Parent
- .Nodes()
- .OfType<XText>()
- .Count() != 1
- ? "text()[" +
- (tx
- .NodesBeforeSelf()
- .OfType<XText>()
- .Count() + 1) + "]"
- : "text()"
- );
- var pi = xobj as XProcessingInstruction;
- if (pi != null && pi.Parent != null)
- return
- "/" +
- pi
- .Parent
- .AncestorsAndSelf()
- .InDocumentOrder()
- .Select(e => NameWithPredicate(e))
- .StrCat("/") +
- (
- pi
- .Parent
- .Nodes()
- .OfType<XProcessingInstruction>()
- .Count() != 1
- ? "processing-instruction()[" +
- (pi
- .NodesBeforeSelf()
- .OfType<XProcessingInstruction>()
- .Count() + 1) + "]"
- : "processing-instruction()"
- );
- return null;
- }
- }
- /// <summary>
- /// Gets or creates the given container's first child element having the given
- /// <see cref="XName"/>.
- /// </summary>
- /// <param name="container">The container <see cref="XElement"/>.</param>
- /// <param name="childName">The child element's <see cref="XName"/>.</param>
- /// <returns>The container's first child <see cref="XElement"/>.</returns>
- public static XElement GetOrCreateFirstChild(this XElement container, XName childName)
- {
- if (container == null) throw new ArgumentNullException(nameof(container));
- if (childName == null) throw new ArgumentNullException(nameof(childName));
- XElement child = container.Element(childName);
- if (child == null)
- {
- child = new XElement(childName);
- container.AddFirst(child);
- }
- return child;
- }
- /// <summary>
- /// Gets the given element's parent element or throws an <see cref="ArgumentException"/>
- /// in case the element does not have a parent.
- /// </summary>
- /// <param name="element">The element.</param>
- /// <returns>The element's parent.</returns>
- public static XElement GetParent(this XElement element)
- {
- if (element == null) throw new ArgumentNullException(nameof(element));
- return element.Parent ?? throw new ArgumentException("Element does not have a parent.");
- }
- /// <summary>
- /// Moves the given element to a new parent.
- /// </summary>
- /// <param name="element">The element.</param>
- /// <param name="parent">The new parent.</param>
- public static void MoveTo(this XElement element, XElement parent)
- {
- if (element == null) throw new ArgumentNullException(nameof(element));
- if (parent == null) throw new ArgumentNullException(nameof(parent));
- element.Remove();
- parent.Add(element);
- }
- }
- public class ExecutableRunner
- {
- public class RunResults
- {
- public int ExitCode;
- public Exception RunException;
- public StringBuilder Output;
- public StringBuilder Error;
- }
- public static RunResults RunExecutable(string executablePath, string arguments, string workingDirectory)
- {
- RunResults runResults = new RunResults
- {
- Output = new StringBuilder(),
- Error = new StringBuilder(),
- RunException = null
- };
- try
- {
- if (File.Exists(executablePath))
- {
- using (Process proc = new Process())
- {
- proc.StartInfo.FileName = executablePath;
- proc.StartInfo.Arguments = arguments;
- proc.StartInfo.WorkingDirectory = workingDirectory;
- proc.StartInfo.UseShellExecute = false;
- proc.StartInfo.RedirectStandardOutput = true;
- proc.StartInfo.RedirectStandardError = true;
- proc.OutputDataReceived +=
- (o, e) => runResults.Output.Append(e.Data).Append(Environment.NewLine);
- proc.ErrorDataReceived +=
- (o, e) => runResults.Error.Append(e.Data).Append(Environment.NewLine);
- proc.Start();
- proc.BeginOutputReadLine();
- proc.BeginErrorReadLine();
- proc.WaitForExit();
- runResults.ExitCode = proc.ExitCode;
- }
- }
- else
- {
- throw new ArgumentException("Invalid executable path.", "executablePath");
- }
- }
- catch (Exception e)
- {
- runResults.RunException = e;
- }
- return runResults;
- }
- }
- public class SiblingsReverseDocumentOrderInfo
- {
- public XElement PreviousSibling;
- }
- public class DescendantsReverseDocumentOrderInfo
- {
- public XElement PreviousElement;
- }
- public class DescendantsTrimmedReverseDocumentOrderInfo
- {
- public XElement PreviousElement;
- }
- public class GroupOfAdjacent<TSource, TKey> : IGrouping<TKey, TSource>
- {
- public GroupOfAdjacent(List<TSource> source, TKey key)
- {
- GroupList = source;
- Key = key;
- }
- public TKey Key { get; set; }
- private List<TSource> GroupList { get; set; }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return ((IEnumerable<TSource>) this).GetEnumerator();
- }
- IEnumerator<TSource> IEnumerable<TSource>.GetEnumerator()
- {
- return ((IEnumerable<TSource>) GroupList).GetEnumerator();
- }
- }
- public class BucketTimer
- {
- public BucketTimer()
- {
- Buckets = new Dictionary<string, BucketInfo>();
- }
- private class BucketInfo
- {
- public int Count;
- public TimeSpan Time;
- }
- private string LastBucket = null;
- private DateTime LastTime;
- private Dictionary<string, BucketInfo> Buckets;
- public void Bucket(string bucket)
- {
- DateTime now = DateTime.Now;
- if (LastBucket != null)
- AddToBuckets(now);
- LastBucket = bucket;
- LastTime = now;
- }
- public void End()
- {
- DateTime now = DateTime.Now;
- if (LastBucket != null)
- AddToBuckets(now);
- LastBucket = null;
- }
- private void AddToBuckets(DateTime now)
- {
- TimeSpan d = now - LastTime;
- var bucketParts = LastBucket.Split('/');
- var bucketList = bucketParts.Select((t, i) => bucketParts
- .Take(i + 1)
- .Select(z => z + "/")
- .StringConcatenate()
- .Trim('/'))
- .ToList();
- foreach (var b in bucketList)
- {
- if (Buckets.ContainsKey(b))
- {
- Buckets[b].Count = Buckets[b].Count + 1;
- Buckets[b].Time += d;
- }
- else
- {
- Buckets.Add(b, new BucketInfo()
- {
- Count = 1,
- Time = d,
- });
- }
- }
- LastTime = now;
- }
- public string DumpBucketsByKey()
- {
- StringBuilder sb = new StringBuilder();
- foreach (var bucket in Buckets.OrderBy(b => b.Key))
- {
- string ts = bucket.Value.Time.ToString();
- if (ts.Contains('.'))
- ts = ts.Substring(0, ts.Length - 5);
- string s = bucket.Key.PadRight(60, '-') + " " + string.Format("{0:00000000}", bucket.Value.Count) + " " + ts;
- sb.Append(s + Environment.NewLine);
- }
- TimeSpan total = Buckets
- .Aggregate(TimeSpan.Zero, (t, b) => t + b.Value.Time);
- var tz = total.ToString();
- sb.Append(string.Format("Total: {0}", tz.Substring(0, tz.Length - 5)));
- return sb.ToString();
- }
- public string DumpBucketsToCsvByKey()
- {
- StringBuilder sb = new StringBuilder();
- foreach (var bucket in Buckets.OrderBy(b => b.Key))
- {
- string ts = bucket.Value.Time.ToString();
- if (ts.Contains('.'))
- ts = ts.Substring(0, ts.Length - 5);
- string s = bucket.Key + "," + bucket.Value.Count.ToString() + "," + ts;
- sb.Append(s + Environment.NewLine);
- }
- return sb.ToString();
- }
- public string DumpBucketsByTime()
- {
- StringBuilder sb = new StringBuilder();
- foreach (var bucket in Buckets.OrderBy(b => b.Value.Time))
- {
- string ts = bucket.Value.Time.ToString();
- if (ts.Contains('.'))
- ts = ts.Substring(0, ts.Length - 5);
- string s = bucket.Key.PadRight(60, '-') + " " + string.Format("{0:00000000}", bucket.Value.Count) + " " + ts;
- sb.Append(s + Environment.NewLine);
- }
- TimeSpan total = Buckets
- .Aggregate(TimeSpan.Zero, (t, b) => t + b.Value.Time);
- var tz = total.ToString();
- sb.Append(string.Format("Total: {0}", tz.Substring(0, tz.Length - 5)));
- return sb.ToString();
- }
- public void Init()
- {
- Buckets = new Dictionary<string, BucketInfo>();
- }
- }
- public static class PtBucketTimer
- {
- private class BucketInfo
- {
- public int Count;
- public TimeSpan Time;
- }
- public static string LastBucket = null;
- private static DateTime LastTime;
- private static Dictionary<string, BucketInfo> Buckets;
- public static void Bucket(string bucket)
- {
- DateTime now = DateTime.Now;
- if (LastBucket != null)
- AddToBuckets(now);
- LastBucket = bucket;
- LastTime = now;
- }
- public static void End()
- {
- DateTime now = DateTime.Now;
- if (LastBucket != null)
- AddToBuckets(now);
- LastBucket = null;
- }
- private static void AddToBuckets(DateTime now)
- {
- TimeSpan d = now - LastTime;
- if (Buckets.ContainsKey(LastBucket))
- {
- Buckets[LastBucket].Count += 1;
- Buckets[LastBucket].Time += d;
- }
- else
- {
- Buckets.Add(LastBucket, new BucketInfo()
- {
- Count = 1,
- Time = d,
- });
- }
- LastTime = now;
- }
- public static string DumpBucketsByKey()
- {
- StringBuilder sb = new StringBuilder();
- foreach (var bucket in Buckets.OrderBy(b => b.Key))
- {
- string ts = bucket.Value.Time.ToString();
- if (ts.Contains('.'))
- ts = ts.Substring(0, ts.Length - 5);
- string s = bucket.Key.PadRight(80, '-') + " " + string.Format("{0:00000000}", bucket.Value.Count) + " " + ts;
- sb.Append(s + Environment.NewLine);
- }
- TimeSpan total = Buckets
- .Aggregate(TimeSpan.Zero, (t, b) => t + b.Value.Time);
- var tz = total.ToString();
- sb.Append(string.Format("Total: {0}", tz.Substring(0, tz.Length - 5)));
- return sb.ToString();
- }
- public static string DumpBucketsToCsvByKey()
- {
- StringBuilder sb = new StringBuilder();
- foreach (var bucket in Buckets.OrderBy(b => b.Key))
- {
- string ts = bucket.Value.Time.TotalMilliseconds.ToString();
- if (ts.Contains('.'))
- ts = ts.Substring(0, ts.Length - 5);
- string s = bucket.Key + "," + bucket.Value.Count.ToString() + "," + ts;
- sb.Append(s + Environment.NewLine);
- }
- return sb.ToString();
- }
- public static string DumpBucketsByTime()
- {
- StringBuilder sb = new StringBuilder();
- foreach (var bucket in Buckets.OrderBy(b => b.Value.Time))
- {
- string ts = bucket.Value.Time.ToString();
- if (ts.Contains('.'))
- ts = ts.Substring(0, ts.Length - 5);
- string s = bucket.Key.PadRight(80, '-') + " " + string.Format("{0:00000000}", bucket.Value.Count) + " " + ts;
- sb.Append(s + Environment.NewLine);
- }
- TimeSpan total = Buckets
- .Aggregate(TimeSpan.Zero, (t, b) => t + b.Value.Time);
- var tz = total.ToString();
- sb.Append(string.Format("Total: {0}", tz.Substring(0, tz.Length - 5)));
- return sb.ToString();
- }
- public static void Init()
- {
- LastBucket = null;
- Buckets = new Dictionary<string, BucketInfo>();
- }
- }
- public class XEntity : XText
- {
- public override void WriteTo(XmlWriter writer)
- {
- if (Value.Substring(0, 1) == "#")
- {
- string e = string.Format("&{0};", Value);
- writer.WriteRaw(e);
- }
- else
- writer.WriteEntityRef(Value);
- }
- public XEntity(string value) : base(value)
- {
- }
- }
-
- }
|