123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248 |
- // 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.Text;
- using System.Xml;
- using System.Xml.Linq;
- using System.Xml.Schema;
- namespace OpenXmlPowerTools
- {
- public static class PtUtils
- {
- 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)
- {
- System.Threading.Thread.Sleep(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)
- {
- System.Threading.Thread.Sleep(50);
- }
- }
- }
- public static void ThreadSafeCreateEmptyTextFileIfNotExist(FileInfo file)
- {
- while (true)
- {
- if (file.Exists)
- break;
- try
- {
- File.WriteAllText(file.FullName, "");
- break;
- }
- catch (IOException)
- {
- System.Threading.Thread.Sleep(50);
- }
- }
- }
- #if !NET35
- internal static void ThreadSafeAppendAllLines(FileInfo file, string[] strings)
- {
- while (true)
- {
- try
- {
- File.AppendAllLines(file.FullName, strings);
- break;
- }
- catch (IOException)
- {
- System.Threading.Thread.Sleep(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> SkipLast<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;
- }
- }
- }
- 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 static class PtBucketTimer
- {
- private class BucketInfo
- {
- public int Count;
- public TimeSpan Time;
- }
- private 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)
- {
- TimeSpan d = now - LastTime;
- if (Buckets.ContainsKey(LastBucket))
- {
- Buckets[LastBucket].Count = Buckets[LastBucket].Count + 1;
- Buckets[LastBucket].Time += d;
- }
- else
- {
- Buckets.Add(LastBucket, new BucketInfo()
- {
- Count = 1,
- Time = d,
- });
- }
- }
- LastBucket = bucket;
- 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(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 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(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 static void Init()
- {
- 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)
- {
- }
- }
- public static class Xsi
- {
- public static XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
- public static XName schemaLocation = xsi + "schemaLocation";
- public static XName noNamespaceSchemaLocation = xsi + "noNamespaceSchemaLocation";
- }
- }
|